diff --git a/reminder-dashboard/src/components/Reminder/Avatar.tsx b/reminder-dashboard/src/components/Reminder/Avatar.tsx index 61127ed..bb9b63d 100644 --- a/reminder-dashboard/src/components/Reminder/Avatar.tsx +++ b/reminder-dashboard/src/components/Reminder/Avatar.tsx @@ -9,7 +9,8 @@ export const Avatar = () => { return guild ? ( { setReminder((reminder) => ({ diff --git a/reminder-dashboard/src/components/Reminder/ImagePicker.tsx b/reminder-dashboard/src/components/Reminder/ImagePicker.tsx index 903c768..dc545dc 100644 --- a/reminder-dashboard/src/components/Reminder/ImagePicker.tsx +++ b/reminder-dashboard/src/components/Reminder/ImagePicker.tsx @@ -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(null); const { data: userInfo } = useQuery(fetchUserInfo()); @@ -64,7 +65,7 @@ export const ImagePicker = ({ alt, url, setImage, ...props }) => { }} role={"button"} > - {alt} + {alt} {modalOpen && ( { - setImage(value); + // Saving an untouched picker must not mark the field as edited. + if (value !== (url || "")) setImage(value); setModalOpen(false); }} onSubmitText={"Save"} diff --git a/src/image_cleanup.rs b/src/image_cleanup.rs index f203e16..4044240 100644 --- a/src/image_cleanup.rs +++ b/src/image_cleanup.rs @@ -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) -> 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 = sqlx::query_scalar(&format!( + "SELECT id FROM image_uploads AS upload WHERE orphaned_at IS NULL AND {unreferenced}" )) - .execute(pool) + .fetch_all(pool) .await?; + let referenced_again: Vec = 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(()) } diff --git a/src/image_upload.rs b/src/image_upload.rs index 7b90cb0..2b82b7f 100644 --- a/src/image_upload.rs +++ b/src/image_upload.rs @@ -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 = 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 }) } diff --git a/src/image_upload/tests.rs b/src/image_upload/tests.rs index 2bd4d3c..dc4352a 100644 --- a/src/image_upload/tests.rs +++ b/src/image_upload/tests.rs @@ -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) { +async fn maps_managed_urls_to_ids_and_drops_deleted_uploads(pool: Pool) { 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) 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)] diff --git a/src/web/macros.rs b/src/web/macros.rs index de19997..adf1e7b 100644 --- a/src/web/macros.rs +++ b/src/web/macros.rs @@ -110,32 +110,38 @@ 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!( - "UPDATE reminders SET `", - stringify!($field), - "` = ?, `", - stringify!($id), - "` = ? WHERE uid = ?" - )) - .bind(image.url) - .bind(image.id) - .bind(&$reminder.uid) - .execute($pool) - .await - { - warn!("Could not update image reference: {:?}", 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))); - } + let result = match crate::image_upload::ImageReference::from_url( + $pool, + value.as_deref(), + ) + .await + { + Ok(image) => sqlx::query(concat!( + "UPDATE reminders SET `", + stringify!($field), + "` = ?, `", + stringify!($id), + "` = ? WHERE uid = ?" + )) + .bind(image.url) + .bind(image.id) + .bind(&$reminder.uid) + .execute($pool) + .await + .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))); + return Err(json!({ "reminder": null, "errors": $error })); } } }; diff --git a/src/web/routes/dashboard/mod.rs b/src/web/routes/dashboard/mod.rs index 847fbe8..499ef00 100644 --- a/src/web/routes/dashboard/mod.rs +++ b/src/web/routes/dashboard/mod.rs @@ -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(); - update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id); + 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, Option) = 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(); - update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id); + 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, Option) = 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(); - update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id); + 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, Option) = sqlx::query_as( "SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'", )