Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bd6395e9f | ||
|
|
5f65727c19 | ||
|
|
f8d8cdc9cb | ||
|
|
d206da181b | ||
|
|
46186a8abc |
No files matched your search
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM ubuntu:20.04
|
FROM ubuntu:22.04
|
||||||
|
|
||||||
ENV RUSTUP_HOME=/usr/local/rustup \
|
ENV RUSTUP_HOME=/usr/local/rustup \
|
||||||
CARGO_HOME=/usr/local/cargo \
|
CARGO_HOME=/usr/local/cargo \
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ replacement for dateparser in Rust)
|
|||||||
|
|
||||||
Recommended method.
|
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.
|
different platform. These instructions are written using `podman`, but `docker` should work too.
|
||||||
|
|
||||||
1. Install container software and Make: `sudo apt install podman make`.
|
1. Install container software and Make: `sudo apt install podman make`.
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ export const Avatar = () => {
|
|||||||
return guild ? (
|
return guild ? (
|
||||||
<ImagePicker
|
<ImagePicker
|
||||||
class="is-rounded avatar"
|
class="is-rounded avatar"
|
||||||
url={reminder.avatar || "/static/img/icon.png"}
|
url={reminder.avatar}
|
||||||
|
fallback={"/static/img/icon.png"}
|
||||||
alt="Image for discord avatar"
|
alt="Image for discord avatar"
|
||||||
setImage={(url: string) => {
|
setImage={(url: string) => {
|
||||||
setReminder((reminder) => ({
|
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 [modalOpen, setModalOpen] = useState(false);
|
||||||
const [droppedFiles, setDroppedFiles] = useState<File[] | null>(null);
|
const [droppedFiles, setDroppedFiles] = useState<File[] | null>(null);
|
||||||
const { data: userInfo } = useQuery(fetchUserInfo());
|
const { data: userInfo } = useQuery(fetchUserInfo());
|
||||||
@@ -64,7 +65,7 @@ export const ImagePicker = ({ alt, url, setImage, ...props }) => {
|
|||||||
}}
|
}}
|
||||||
role={"button"}
|
role={"button"}
|
||||||
>
|
>
|
||||||
<img {...props} src={url || "/static/img/bg.webp"} alt={alt}></img>
|
<img {...props} src={url || fallback} alt={alt}></img>
|
||||||
</a>
|
</a>
|
||||||
{modalOpen && (
|
{modalOpen && (
|
||||||
<ImagePickerModal
|
<ImagePickerModal
|
||||||
@@ -134,7 +135,8 @@ const ImagePickerModal = ({ setModalOpen, setImage, url, uploadsEnabled, dropped
|
|||||||
setModalOpen={setModalOpen}
|
setModalOpen={setModalOpen}
|
||||||
title={"Enter Image URL"}
|
title={"Enter Image URL"}
|
||||||
onSubmit={() => {
|
onSubmit={() => {
|
||||||
setImage(value);
|
// Saving an untouched picker must not mark the field as edited.
|
||||||
|
if (value !== (url || "")) setImage(value);
|
||||||
setModalOpen(false);
|
setModalOpen(false);
|
||||||
}}
|
}}
|
||||||
onSubmitText={"Save"}
|
onSubmitText={"Save"}
|
||||||
|
|||||||
+29
-4
@@ -32,14 +32,39 @@ fn unreferenced_predicate() -> String {
|
|||||||
.join(" AND ")
|
.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> {
|
async fn mark_orphans(pool: &Pool<MySql>) -> Result<(), Error> {
|
||||||
sqlx::query(&format!(
|
let unreferenced = unreferenced_predicate();
|
||||||
"UPDATE image_uploads AS upload SET orphaned_at = CASE
|
let newly_orphaned: Vec<u64> = sqlx::query_scalar(&format!(
|
||||||
WHEN {} THEN COALESCE(upload.orphaned_at, UTC_TIMESTAMP(6)) ELSE NULL END",
|
"SELECT id FROM image_uploads AS upload WHERE orphaned_at IS NULL AND {unreferenced}"
|
||||||
unreferenced_predicate()
|
|
||||||
))
|
))
|
||||||
|
.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)
|
.execute(pool)
|
||||||
.await?;
|
.await?;
|
||||||
|
}
|
||||||
|
for id in referenced_again {
|
||||||
|
sqlx::query("UPDATE image_uploads SET orphaned_at = NULL WHERE id = ?")
|
||||||
|
.bind(id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+9
-3
@@ -77,13 +77,19 @@ impl ImageReference {
|
|||||||
if let Some(path) = path {
|
if let Some(path) = path {
|
||||||
// Hold a shared upload lock until the caller commits its reference. Cleanup
|
// Hold a shared upload lock until the caller commits its reference. Cleanup
|
||||||
// locks that same row exclusively before checking references and deleting S3.
|
// 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",
|
"SELECT id FROM image_uploads WHERE path = ? LOCK IN SHARE MODE",
|
||||||
)
|
)
|
||||||
.bind(path)
|
.bind(path)
|
||||||
.fetch_one(executor)
|
.fetch_optional(executor)
|
||||||
.await?;
|
.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 {
|
} else {
|
||||||
Ok(Self { url: url.map(str::to_string), id: None })
|
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]
|
#[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 path = format!("uploads/{:064x}.png", 1);
|
||||||
let id = sqlx::query("INSERT INTO image_uploads (uploader, path) VALUES (123, ?)")
|
let id = sqlx::query("INSERT INTO image_uploads (uploader, path) VALUES (123, ?)")
|
||||||
.bind(&path)
|
.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);
|
assert_eq!(reference.url.as_deref(), url);
|
||||||
}
|
}
|
||||||
let missing = format!("{base}/uploads/{:064x}.png", 2);
|
let missing = format!("{base}/uploads/{:064x}.png", 2);
|
||||||
assert!(matches!(
|
let reference = ImageReference::with_base(&pool, Some(&missing), base).await.unwrap();
|
||||||
ImageReference::with_base(&pool, Some(&missing), base).await,
|
assert_eq!(reference.id, None);
|
||||||
Err(sqlx::Error::RowNotFound)
|
assert_eq!(reference.url, None);
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrations = false)]
|
#[sqlx::test(migrations = false)]
|
||||||
|
|||||||
+17
-11
@@ -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 {
|
macro_rules! update_image_field {
|
||||||
($pool:expr, $error:ident, $reminder:ident, $field:ident, $id:ident) => {
|
($pool:expr, $error:ident, $reminder:ident, $field:ident, $id:ident) => {
|
||||||
if let Some(value) = &$reminder.$field {
|
if let Some(value) = &$reminder.$field {
|
||||||
match crate::image_upload::ImageReference::from_url($pool, value.as_deref()).await {
|
let result = match crate::image_upload::ImageReference::from_url(
|
||||||
Ok(image) => {
|
$pool,
|
||||||
if let Err(e) = sqlx::query(concat!(
|
value.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(image) => sqlx::query(concat!(
|
||||||
"UPDATE reminders SET `",
|
"UPDATE reminders SET `",
|
||||||
stringify!($field),
|
stringify!($field),
|
||||||
"` = ?, `",
|
"` = ?, `",
|
||||||
@@ -127,15 +135,13 @@ macro_rules! update_image_field {
|
|||||||
.bind(&$reminder.uid)
|
.bind(&$reminder.uid)
|
||||||
.execute($pool)
|
.execute($pool)
|
||||||
.await
|
.await
|
||||||
{
|
.map(|_| ()),
|
||||||
warn!("Could not update image reference: {:?}", e);
|
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)));
|
$error.push(format!("Error setting field {}", stringify!($field)));
|
||||||
}
|
return Err(json!({ "reminder": null, "errors": $error }));
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
warn!("Could not resolve image upload: {:?}", e);
|
|
||||||
$error.push(format!("Error setting field {}", stringify!($field)));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -987,7 +987,12 @@ mod tests {
|
|||||||
let mut transaction = pool.begin().await.unwrap();
|
let mut transaction = pool.begin().await.unwrap();
|
||||||
let mut errors = vec![];
|
let mut errors = vec![];
|
||||||
let reminder: PatchReminder = serde_json::from_value(json!({"uid": "image-edit"})).unwrap();
|
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);
|
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(
|
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
|
||||||
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
|
"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
|
"uid": "image-edit", "embed_image_url": external
|
||||||
}))
|
}))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let result: Result<(), serde_json::Value> = async {
|
||||||
update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id);
|
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(
|
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
|
||||||
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
|
"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
|
"uid": "image-edit", "embed_image_url": null
|
||||||
}))
|
}))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
let result: Result<(), serde_json::Value> = async {
|
||||||
update_image_field!(&mut *transaction, errors, reminder, embed_image_url, embed_image_id);
|
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(
|
let stored: (Option<String>, Option<u64>) = sqlx::query_as(
|
||||||
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
|
"SELECT embed_image_url, embed_image_id FROM reminders WHERE uid = 'image-edit'",
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in new issue
Block a user