Skip to main content

max / makenotwork

2.1 KB · 75 lines History Blame Raw
1 //! image lifecycle from insert through to S3 purge marking
2
3 use super::{PgPool, Uuid};
4
5 /// Insert an uploaded image record.
6 #[tracing::instrument(skip_all)]
7 pub async fn insert_image(
8 pool: &PgPool,
9 uploader_id: Uuid,
10 community_id: Uuid,
11 s3_key: &str,
12 filename: &str,
13 content_type: &str,
14 size_bytes: i64,
15 ) -> Result<Uuid, sqlx::Error> {
16 sqlx::query_scalar!(
17 "INSERT INTO images (uploader_id, community_id, s3_key, filename, content_type, size_bytes)
18 VALUES ($1, $2, $3, $4, $5, $6)
19 RETURNING id",
20 uploader_id,
21 community_id,
22 s3_key,
23 filename,
24 content_type,
25 size_bytes,
26 )
27 .fetch_one(pool)
28 .await
29 }
30
31 /// Mark an image as removed by a moderator.
32 #[tracing::instrument(skip_all)]
33 pub async fn remove_image<'e, E: sqlx::PgExecutor<'e>>(
34 executor: E,
35 image_id: Uuid,
36 removed_by: Uuid,
37 ) -> Result<(), sqlx::Error> {
38 sqlx::query!(
39 "UPDATE images SET removed_at = now(), removed_by = $2 WHERE id = $1 AND removed_at IS NULL",
40 image_id,
41 removed_by,
42 )
43 .execute(executor)
44 .await?;
45 Ok(())
46 }
47
48 /// Hard-delete an image row. Used to roll back the row inserted just before a
49 /// failed S3 upload, the object never landed in the bucket, so there is
50 /// nothing to reconcile and the row should not exist.
51 #[tracing::instrument(skip_all)]
52 pub async fn delete_image_row(pool: &PgPool, image_id: Uuid) -> Result<(), sqlx::Error> {
53 sqlx::query!("DELETE FROM images WHERE id = $1", image_id)
54 .execute(pool)
55 .await?;
56 Ok(())
57 }
58
59 /// Mark images whose backing S3 object has been deleted, so the reconcile sweep
60 /// never revisits them. Called inline after a successful best-effort delete and
61 /// in batch by the background sweep.
62 #[tracing::instrument(skip_all)]
63 pub async fn mark_images_s3_purged(pool: &PgPool, image_ids: &[Uuid]) -> Result<(), sqlx::Error> {
64 if image_ids.is_empty() {
65 return Ok(());
66 }
67 sqlx::query!(
68 "UPDATE images SET s3_purged_at = now() WHERE id = ANY($1)",
69 image_ids
70 )
71 .execute(pool)
72 .await?;
73 Ok(())
74 }
75