Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bd6395e9f |
No files matched your search
@@ -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"}
|
||||
|
||||
+30
-5
@@ -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}"
|
||||
))
|
||||
.execute(pool)
|
||||
.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
@@ -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 })
|
||||
}
|
||||
|
||||
@@ -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)]
|
||||
|
||||
+29
-23
@@ -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 }));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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<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();
|
||||
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<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();
|
||||
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<String>, Option<u64>) = sqlx::query_as(
|
||||
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user