Compare commits

..
Author SHA1 Message Date
claude Bot 5bd6395e9f Fix bugs 2026-11-21 18:58:10 +00:00
claude Bot 5f65727c19 Adjust migration 2026-11-21 18:16:44 +00:00
claude Bot f8d8cdc9cb Move to FKs 2026-11-21 18:16:44 +00:00
claude Bot d206da181b Add support for S3-backed image storage 2026-11-21 18:16:44 +00:00
claude Bot 46186a8abc Increase Ubuntu target version 2026-11-07 18:12:11 +00:00
9 changed files with 83 additions and 29 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
FROM ubuntu:20.04
FROM ubuntu:22.04
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
+1 -1
View File
@@ -15,7 +15,7 @@ replacement for dateparser in Rust)
Recommended method.
By default, this builds targeting Ubuntu 20.04. Modify the Containerfile if you wish to target a
By default, this builds targeting Ubuntu 22.04. Modify the Containerfile if you wish to target a
different platform. These instructions are written using `podman`, but `docker` should work too.
1. Install container software and Make: `sudo apt install podman make`.
@@ -9,7 +9,8 @@ export const Avatar = () => {
return guild ? (
<ImagePicker
class="is-rounded avatar"
url={reminder.avatar || "/static/img/icon.png"}
url={reminder.avatar}
fallback={"/static/img/icon.png"}
alt="Image for discord avatar"
setImage={(url: string) => {
setReminder((reminder) => ({
@@ -42,7 +42,8 @@ const useImageDrop = (enabled: boolean, onFiles: (files: File[]) => void, busy =
};
};
export const ImagePicker = ({ alt, url, setImage, ...props }) => {
// `url` is the stored value; `fallback` is only displayed and never saved.
export const ImagePicker = ({ alt, url, setImage, fallback = "/static/img/bg.webp", ...props }) => {
const [modalOpen, setModalOpen] = useState(false);
const [droppedFiles, setDroppedFiles] = useState<File[] | null>(null);
const { data: userInfo } = useQuery(fetchUserInfo());
@@ -64,7 +65,7 @@ export const ImagePicker = ({ alt, url, setImage, ...props }) => {
}}
role={"button"}
>
<img {...props} src={url || "/static/img/bg.webp"} alt={alt}></img>
<img {...props} src={url || fallback} alt={alt}></img>
</a>
{modalOpen && (
<ImagePickerModal
@@ -134,7 +135,8 @@ const ImagePickerModal = ({ setModalOpen, setImage, url, uploadsEnabled, dropped
setModalOpen={setModalOpen}
title={"Enter Image URL"}
onSubmit={() => {
setImage(value);
// Saving an untouched picker must not mark the field as edited.
if (value !== (url || "")) setImage(value);
setModalOpen(false);
}}
onSubmitText={"Save"}
+29 -4
View File
@@ -32,14 +32,39 @@ fn unreferenced_predicate() -> String {
.join(" AND ")
}
// The orphan mark only starts the retention clock: delete_orphan rechecks references
// under an exclusive lock before deleting anything. So candidates come from a
// non-locking snapshot read, and each change is a single-row autocommit update by
// primary key. Every statement holds at most one lock, so it cannot form a deadlock
// cycle with dashboard saves that share-lock several uploads in field order.
async fn mark_orphans(pool: &Pool<MySql>) -> Result<(), Error> {
sqlx::query(&format!(
"UPDATE image_uploads AS upload SET orphaned_at = CASE
WHEN {} THEN COALESCE(upload.orphaned_at, UTC_TIMESTAMP(6)) ELSE NULL END",
unreferenced_predicate()
let unreferenced = unreferenced_predicate();
let newly_orphaned: Vec<u64> = sqlx::query_scalar(&format!(
"SELECT id FROM image_uploads AS upload WHERE orphaned_at IS NULL AND {unreferenced}"
))
.fetch_all(pool)
.await?;
let referenced_again: Vec<u64> = sqlx::query_scalar(&format!(
"SELECT id FROM image_uploads AS upload WHERE orphaned_at IS NOT NULL AND NOT ({unreferenced})"
))
.fetch_all(pool)
.await?;
for id in newly_orphaned {
sqlx::query(
"UPDATE image_uploads SET orphaned_at = COALESCE(orphaned_at, UTC_TIMESTAMP(6))
WHERE id = ?",
)
.bind(id)
.execute(pool)
.await?;
}
for id in referenced_again {
sqlx::query("UPDATE image_uploads SET orphaned_at = NULL WHERE id = ?")
.bind(id)
.execute(pool)
.await?;
}
Ok(())
}
+9 -3
View File
@@ -77,13 +77,19 @@ impl ImageReference {
if let Some(path) = path {
// Hold a shared upload lock until the caller commits its reference. Cleanup
// locks that same row exclusively before checking references and deleting S3.
let id = sqlx::query_scalar(
let id: Option<u64> = sqlx::query_scalar(
"SELECT id FROM image_uploads WHERE path = ? LOCK IN SHARE MODE",
)
.bind(path)
.fetch_one(executor)
.fetch_optional(executor)
.await?;
Ok(Self { url: None, id: Some(id) })
// Cleanup only deletes the row after the S3 object is gone, so a missing row
// means the image no longer exists. Drop this field instead of failing the
// whole save or import.
if id.is_none() {
log::warn!("Dropping reference to deleted image upload {path}");
}
Ok(Self { url: None, id })
} else {
Ok(Self { url: url.map(str::to_string), id: None })
}
+4 -5
View File
@@ -19,7 +19,7 @@ fn resolves_paths_using_the_current_base_and_preserves_external_urls() {
}
#[sqlx::test]
async fn maps_managed_urls_to_ids_and_rejects_deleted_uploads(pool: Pool<MySql>) {
async fn maps_managed_urls_to_ids_and_drops_deleted_uploads(pool: Pool<MySql>) {
let path = format!("uploads/{:064x}.png", 1);
let id = sqlx::query("INSERT INTO image_uploads (uploader, path) VALUES (123, ?)")
.bind(&path)
@@ -42,10 +42,9 @@ async fn maps_managed_urls_to_ids_and_rejects_deleted_uploads(pool: Pool<MySql>)
assert_eq!(reference.url.as_deref(), url);
}
let missing = format!("{base}/uploads/{:064x}.png", 2);
assert!(matches!(
ImageReference::with_base(&pool, Some(&missing), base).await,
Err(sqlx::Error::RowNotFound)
));
let reference = ImageReference::with_base(&pool, Some(&missing), base).await.unwrap();
assert_eq!(reference.id, None);
assert_eq!(reference.url, None);
}
#[sqlx::test(migrations = false)]
+17 -11
View File
@@ -110,12 +110,20 @@ macro_rules! path {
}};
}
// Returns early on a database error. Image lookups take share locks, so they can be
// deadlock victims; InnoDB then rolls back the whole transaction, and carrying on
// would commit the later statements without the earlier ones. Returning drops the
// transaction guard, which rolls back, and the client sees the save failed.
macro_rules! update_image_field {
($pool:expr, $error:ident, $reminder:ident, $field:ident, $id:ident) => {
if let Some(value) = &$reminder.$field {
match crate::image_upload::ImageReference::from_url($pool, value.as_deref()).await {
Ok(image) => {
if let Err(e) = sqlx::query(concat!(
let result = match crate::image_upload::ImageReference::from_url(
$pool,
value.as_deref(),
)
.await
{
Ok(image) => sqlx::query(concat!(
"UPDATE reminders SET `",
stringify!($field),
"` = ?, `",
@@ -127,15 +135,13 @@ macro_rules! update_image_field {
.bind(&$reminder.uid)
.execute($pool)
.await
{
warn!("Could not update image reference: {:?}", e);
.map(|_| ()),
Err(e) => Err(e),
};
if let Err(e) = result {
warn!("Could not update image field {}: {:?}", stringify!($field), e);
$error.push(format!("Error setting field {}", stringify!($field)));
}
}
Err(e) => {
warn!("Could not resolve image upload: {:?}", e);
$error.push(format!("Error setting field {}", stringify!($field)));
}
return Err(json!({ "reminder": null, "errors": $error }));
}
}
};
+15
View File
@@ -987,7 +987,12 @@ mod tests {
let mut transaction = pool.begin().await.unwrap();
let mut errors = vec![];
let reminder: PatchReminder = serde_json::from_value(json!({"uid": "image-edit"})).unwrap();
let result: Result<(), serde_json::Value> = async {
update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id);
Ok(())
}
.await;
result.unwrap();
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
)
@@ -1001,7 +1006,12 @@ mod tests {
"uid": "image-edit", "embed_image_url": external
}))
.unwrap();
let result: Result<(), serde_json::Value> = async {
update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id);
Ok(())
}
.await;
result.unwrap();
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
)
@@ -1016,7 +1026,12 @@ mod tests {
"uid": "image-edit", "embed_image_url": null
}))
.unwrap();
let result: Result<(), serde_json::Value> = async {
update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id);
Ok(())
}
.await;
result.unwrap();
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
)