Skip to main content

rustango_cms/
uploaded_file.rs

1//! Scratch storage for multi-step media uploads.
2//!
3//! The editor uploads
4//! bytes first, then fills in title / alt / collection on a follow-up
5//! form, then the row commits to [`crate::media::Media`]. If the
6//! editor cancels or closes the tab mid-step, the scratch row is
7//! collected by the background sweep — no orphan media leaks into
8//! `cms_media`.
9//!
10//! Existing single-step `media_upload_submit` keeps working unchanged;
11//! this primitive is the foundation for future drag-drop / multi-file
12//! UIs where bytes arrive faster than the editor can fill metadata.
13//!
14//! Scratch objects live under the storage key `<tenant>/scratch/<hash>-<filename>`
15//! so the commit path can rename in place rather than copying bytes
16//! across volumes.
17
18use chrono::{DateTime, Duration, Utc};
19use rustango::sql::Auto;
20use rustango::Model;
21use serde::{Deserialize, Serialize};
22
23/// How long a scratch upload sticks around before the sweep collects
24/// it. Generous — editors sometimes step away mid-upload.
25pub const STALE_THRESHOLD_HOURS: i64 = 24;
26
27#[derive(Model, Debug, Clone, Serialize, Deserialize)]
28#[rustango(
29    table = "cms_uploaded_file",
30    app = "cms",
31    display = "original_filename",
32    admin(
33        list_display = "user_id, original_filename, mime, size, uploaded_at",
34        ordering = "-uploaded_at",
35    )
36)]
37pub struct UploadedFile {
38    #[rustango(primary_key)]
39    pub id: Auto<i64>,
40
41    /// Editor who uploaded — for permission gating on commit.
42    #[rustango(fk = "rustango_users", on = "id", index)]
43    pub user_id: i64,
44
45    /// Opaque key inside the tenant's media storage backend. Living
46    /// under a `scratch/` prefix so directory listings make the
47    /// distinction obvious.
48    #[rustango(max_length = 512)]
49    pub storage_key: String,
50
51    #[rustango(max_length = 255)]
52    pub original_filename: String,
53
54    #[rustango(max_length = 128)]
55    pub mime: String,
56
57    pub size: i64,
58
59    /// SHA-256 hex. Used by commit to dedup against existing
60    /// `cms_media` rows.
61    #[rustango(max_length = 64, index)]
62    pub content_hash: String,
63
64    #[rustango(auto_now_add)]
65    pub uploaded_at: Auto<DateTime<Utc>>,
66}
67
68/// Insert one scratch row.
69///
70/// # Errors
71/// Driver / query failures.
72pub async fn create(
73    pool: &rustango::sql::Pool,
74    user_id: i64,
75    storage_key: String,
76    original_filename: String,
77    mime: String,
78    size: i64,
79    content_hash: String,
80) -> Result<UploadedFile, rustango::sql::ExecError> {
81    let mut row = UploadedFile {
82        id: Auto::Unset,
83        user_id,
84        storage_key,
85        original_filename,
86        mime,
87        size,
88        content_hash,
89        uploaded_at: Auto::Unset,
90    };
91    row.insert_pool(pool).await?;
92    Ok(row)
93}
94
95/// Look up a scratch row by id. Returns `None` when missing — callers
96/// should treat that as the editor cancelled / sweep collected.
97///
98/// # Errors
99/// Driver / query failures.
100pub async fn get(
101    pool: &rustango::sql::Pool,
102    id: i64,
103) -> Result<Option<UploadedFile>, rustango::sql::ExecError> {
104    use rustango::core::Column as _;
105    use rustango::sql::FetcherPool as _;
106    let mut rows: Vec<UploadedFile> = UploadedFile::objects()
107        .where_(UploadedFile::id.eq(id))
108        .fetch(pool)
109        .await?;
110    Ok(rows.pop())
111}
112
113/// Delete one scratch row by id. Returns the number of rows removed
114/// (0 or 1). Filesystem cleanup is the caller's responsibility — this
115/// only touches the DB row.
116///
117/// # Errors
118/// Driver / query failures.
119pub async fn delete(
120    pool: &rustango::sql::Pool,
121    id: i64,
122) -> Result<usize, rustango::sql::ExecError> {
123    use rustango::core::Column as _;
124    use rustango::sql::FetcherPool as _;
125    let rows: Vec<UploadedFile> = UploadedFile::objects()
126        .where_(UploadedFile::id.eq(id))
127        .fetch(pool)
128        .await?;
129    let mut removed = 0;
130    for row in rows {
131        row.delete_pool(pool).await?;
132        removed += 1;
133    }
134    Ok(removed)
135}
136
137/// Drop every scratch row older than [`STALE_THRESHOLD_HOURS`].
138/// Filesystem-side cleanup is the caller's responsibility — the sweep
139/// returns the list of `storage_key`s the caller should unlink so the
140/// IO happens outside any held DB lock.
141///
142/// # Errors
143/// Driver / query failures.
144pub async fn gc_stale(pool: &rustango::sql::Pool) -> Result<Vec<String>, rustango::sql::ExecError> {
145    use rustango::sql::FetcherPool as _;
146    let cutoff = Utc::now() - Duration::hours(STALE_THRESHOLD_HOURS);
147    let all: Vec<UploadedFile> = UploadedFile::objects().fetch(pool).await?;
148    let mut unlinked: Vec<String> = Vec::new();
149    for row in all {
150        let uploaded_at = row.uploaded_at.get().copied();
151        let Some(ts) = uploaded_at else {
152            continue;
153        };
154        if ts >= cutoff {
155            continue;
156        }
157        let key = row.storage_key.clone();
158        if row.delete_pool(pool).await.is_ok() {
159            unlinked.push(key);
160        }
161    }
162    Ok(unlinked)
163}