forge
Explore
Log in

Don't you dare go Hollow

a restore can no longer lose a race with a purge: every trash delete re-validates its predicate inside the immediate transaction that deletes, so a file or subtree brought back inside the selection window keeps its row, its shares and its bytes; purge_expired and empty_trash route through one guarded delete side, purge_file answers false for what a restore returned and purge_folder refuses it; an upload session is re-read as finishable inside the finish transaction, so an abort landing mid-finish never commits a file and a second finish never duplicates one; delete_file carries the already-trashed guard its folder sibling has had all along

Browse files at this commit

f5e4675e8bfd3569fb09497d6b9aac323a4872bdAhmet Kaan GümüşParent: 465a24b
crates/in-core/src/store/turso_store.rsmodified+477 -123
@@ -1648,7 +1648,7 @@ impl Store for TursoStore {
1648 let now = now_text()?;1648 let now = now_text()?;
1649 let conn = self.conn.lock().await;1649 let conn = self.conn.lock().await;
1650 conn.execute(1650 conn.execute(
1651- "UPDATE file SET deleted_at = ?1, updated_at = ?1 WHERE id = ?2",1651+ "UPDATE file SET deleted_at = ?1, updated_at = ?1 WHERE id = ?2 AND deleted_at IS NULL",
1652 params![now, id],1652 params![now, id],
1653 )1653 )
1654 .await1654 .await
@@ -1934,7 +1934,13 @@ impl Store for TursoStore {
1934 .transaction_with_behavior(TransactionBehavior::Immediate)1934 .transaction_with_behavior(TransactionBehavior::Immediate)
1935 .await1935 .await
1936 .map_err(backend)?;1936 .map_err(backend)?;
1937- delete_file_rows(&tx, &[id.to_string()]).await?;1937+ let deleted = delete_file_rows(&tx, &[id.to_string()], &TrashGuard::Trashed).await?;
1938+ if deleted.is_empty() {
1939+ // A restore landed between the live-check and this
1940+ // transaction: the file is live again, and a live file is not
1941+ // trash — the purge answers so truthfully.
1942+ return Ok(false);
1943+ }
1938 refresh_usage(&tx, &owner).await?;1944 refresh_usage(&tx, &owner).await?;
1939 tx.commit().await.map_err(backend)?;1945 tx.commit().await.map_err(backend)?;
1940 // After the delete: the bytes may only follow a delete that1946 // After the delete: the bytes may only follow a delete that
@@ -2003,13 +2009,14 @@ impl Store for TursoStore {
2003 .transaction_with_behavior(TransactionBehavior::Immediate)2009 .transaction_with_behavior(TransactionBehavior::Immediate)
2004 .await2010 .await
2005 .map_err(backend)?;2011 .map_err(backend)?;
2006- delete_file_rows(&tx, &file_ids).await?;2012+ let deleted_files = delete_file_rows(&tx, &file_ids, &TrashGuard::Trashed).await?;
2007- delete_folder_rows(&tx, &folder_ids).await?;2013+ let deleted_folders = delete_folder_rows(&tx, &folder_ids, &TrashGuard::Trashed).await?;
2008 refresh_usage(&tx, &owner).await?;2014 refresh_usage(&tx, &owner).await?;
2009 tx.commit().await.map_err(backend)?;2015 tx.commit().await.map_err(backend)?;
2010- // After the delete: bytes may only follow a delete that committed.2016+ // After the delete: bytes may only follow a delete that committed,
2011- // Best-effort — survivors are orphaned bytes the boot sweep collects.2017+ // and only for rows that went — a restore that landed in the read
2012- for file_id in &file_ids {2018+ // window keeps its bytes.
2019+ for file_id in &deleted_files {
2013 let _ = self2020 let _ = self
2014 .blobs2021 .blobs
2015 .delete(&[2022 .delete(&[
@@ -2018,7 +2025,7 @@ impl Store for TursoStore {
2018 ])2025 ])
2019 .await;2026 .await;
2020 }2027 }
2021- let purged = (file_ids.len() + folder_ids.len()) as u64;2028+ let purged = (deleted_files.len() + deleted_folders.len()) as u64;
2022 self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);2029 self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
2023 Ok(purged)2030 Ok(purged)
2024 }2031 }
@@ -2026,130 +2033,46 @@ impl Store for TursoStore {
2026 async fn purge_expired(&self, before: OffsetDateTime) -> Result<u64> {2033 async fn purge_expired(&self, before: OffsetDateTime) -> Result<u64> {
2027 let before = stamp(before)?;2034 let before = stamp(before)?;
2028 let conn = self.conn.lock().await;2035 let conn = self.conn.lock().await;
2029- let mut file_ids = Vec::new();2036+ let (file_ids, folder_rows) = select_expired(&conn, before.as_str()).await?;
2030- let mut rows = conn
2031- .query(
2032- "SELECT id, owner_id FROM file WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
2033- params![before.as_str()],
2034- )
2035- .await
2036- .map_err(backend)?;
2037- while let Some(row) = rows.next().await.map_err(backend)? {
2038- file_ids.push((text(&row, 0)?, text(&row, 1)?));
2039- }
2040- let mut folder_rows = Vec::new();
2041- let mut rows = conn
2042- .query(
2043- "SELECT id, owner_id, parent_id FROM folder \
2044- WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
2045- params![before],
2046- )
2047- .await
2048- .map_err(backend)?;
2049- while let Some(row) = rows.next().await.map_err(backend)? {
2050- folder_rows.push((text(&row, 0)?, text(&row, 1)?, opt_text(&row, 2)?));
2051- }
2052 drop(conn);2037 drop(conn);
2053 if file_ids.is_empty() && folder_rows.is_empty() {2038 if file_ids.is_empty() && folder_rows.is_empty() {
2054 return Ok(0);2039 return Ok(0);
2055 }2040 }
2056- // Folders deepest first: a parent row cannot go while a child row2041+ let (deleted_files, deleted_folders) = commit_trash_purge(
2057- // still names it.2042+ self,
2058- let folder_ids = order_deepest_first(2043+ file_ids,
2059- &folder_rows2044+ folder_rows,
2060- .iter()2045+ &TrashGuard::Expired {
2061- .map(|(id, _, parent)| (id.clone(), parent.clone()))2046+ before: before.as_str(),
2062- .collect::<Vec<_>>(),2047+ },
2063- );
2064- let owners = {
2065- let mut owners: Vec<String> = file_ids.iter().map(|(_, o)| o.clone()).collect();
2066- owners.extend(folder_rows.iter().map(|(_, o, _)| o.clone()));
2067- owners.sort();
2068- owners.dedup();
2069- owners
2070- };
2071- let mut conn = self.tx_conn().await?;
2072- let tx = conn
2073- .transaction_with_behavior(TransactionBehavior::Immediate)
2074- .await
2075- .map_err(backend)?;
2076- delete_file_rows(
2077- &tx,
2078- &file_ids
2079- .iter()
2080- .map(|(id, _)| id.clone())
2081- .collect::<Vec<_>>(),
2082 )2048 )
2083 .await?;2049 .await?;
2084- delete_folder_rows(&tx, &folder_ids).await?;2050+ Ok((deleted_files.len() + deleted_folders.len()) as u64)
2085- for owner in &owners {
2086- refresh_usage(&tx, owner).await?;
2087- }
2088- tx.commit().await.map_err(backend)?;
2089- for (id, _) in &file_ids {
2090- let _ = self
2091- .blobs
2092- .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")])
2093- .await;
2094- }
2095- let purged = (file_ids.len() + folder_ids.len()) as u64;
2096- for owner in owners {
2097- self.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
2098- }
2099- Ok(purged)
2100 }2051 }
2101 2052
2102 async fn empty_trash(&self, owner_id: &str) -> Result<u64> {2053 async fn empty_trash(&self, owner_id: &str) -> Result<u64> {
2103 let conn = self.conn.lock().await;2054 let conn = self.conn.lock().await;
2104- let mut file_ids = Vec::new();2055+ let (file_ids, folder_rows) = select_trash(&conn, owner_id).await?;
2105- let mut rows = conn
2106- .query(
2107- "SELECT id FROM file WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
2108- params![owner_id],
2109- )
2110- .await
2111- .map_err(backend)?;
2112- while let Some(row) = rows.next().await.map_err(backend)? {
2113- file_ids.push(text(&row, 0)?);
2114- }
2115- let mut folder_rows = Vec::new();
2116- let mut rows = conn
2117- .query(
2118- "SELECT id, parent_id FROM folder WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
2119- params![owner_id],
2120- )
2121- .await
2122- .map_err(backend)?;
2123- while let Some(row) = rows.next().await.map_err(backend)? {
2124- folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?));
2125- }
2126 drop(conn);2056 drop(conn);
2127 if file_ids.is_empty() && folder_rows.is_empty() {2057 if file_ids.is_empty() && folder_rows.is_empty() {
2128 return Ok(0);2058 return Ok(0);
2129 }2059 }
2130- let folder_ids = order_deepest_first(&folder_rows);2060+ let (deleted_files, deleted_folders) = commit_trash_purge(
2131- let mut conn = self.tx_conn().await?;2061+ self,
2132- let tx = conn2062+ file_ids
2133- .transaction_with_behavior(TransactionBehavior::Immediate)2063+ .into_iter()
2134- .await2064+ .map(|id| (id, owner_id.to_string()))
2135- .map_err(backend)?;2065+ .collect::<Vec<_>>(),
2136- delete_file_rows(&tx, &file_ids).await?;2066+ folder_rows
2137- delete_folder_rows(&tx, &folder_ids).await?;2067+ .into_iter()
2138- refresh_usage(&tx, owner_id).await?;2068+ .map(|(id, parent)| (id, owner_id.to_string(), parent))
2139- tx.commit().await.map_err(backend)?;2069+ .collect::<Vec<_>>(),
2140- for id in &file_ids {2070+ &TrashGuard::Trashed,
2141- let _ = self2071+ )
2142- .blobs2072+ .await?;
2143- .delete(&[&format!("files/{id}"), &format!("thumbs/{id}")])2073+ Ok((deleted_files.len() + deleted_folders.len()) as u64)
2144- .await;
2145- }
2146- let purged = (file_ids.len() + folder_ids.len()) as u64;
2147- self.announce([
2148- Topic::Library(owner_id.to_string()),
2149- Topic::Trash(owner_id.to_string()),
2150- ]);
2151- Ok(purged)
2152 }2074 }
2075+
2153 async fn create_share_link(2076 async fn create_share_link(
2154 &self,2077 &self,
2155 created_by: &str,2078 created_by: &str,
@@ -2734,6 +2657,10 @@ impl Store for TursoStore {
2734 .await2657 .await
2735 .map_err(backend)?;2658 .map_err(backend)?;
2736 let vetted: Result<String> = async {2659 let vetted: Result<String> = async {
2660+ // The session was vetted outside this transaction; the window
2661+ // since then belongs to abort, expiry and a second finish. The
2662+ // row itself is the last word under the write lock.
2663+ finishable_session(&tx, id).await?;
2737 check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?;2664 check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?;
2738 let (quota, used) = check_quota(&tx, &session.owner_id).await?;2665 let (quota, used) = check_quota(&tx, &session.owner_id).await?;
2739 fit_quota(quota, used, session.size_bytes)?;2666 fit_quota(quota, used, session.size_bytes)?;
@@ -3265,11 +3192,207 @@ async fn target_owner(
3265 }3192 }
3266 }3193 }
3267 3194
3195+/// The trash predicate a delete re-tests inside its own transaction. The
3196+/// candidate lists of a purge are read before the delete transaction
3197+/// opens; a restore committing in that window must keep its row, so the
3198+/// guarded deletes re-check `deleted_at` under the write lock the
3199+/// immediate transaction holds from begin to commit.
3200+enum TrashGuard<'a> {
3201+ /// Unconditional: the caller vetted the rows itself (`purge_file`,
3202+ /// `purge_folder`).
3203+ None,
3204+ /// The row must still be trashed (`empty_trash`).
3205+ Trashed,
3206+ /// The row must still be trashed before the cutoff (`purge_expired`).
3207+ Expired { before: &'a str },
3208+}
3209+
3210+/// Whether `id` still satisfies the guard, re-read inside the delete
3211+/// transaction. The write lock an immediate transaction holds makes this
3212+/// the last word: a restore either committed before it and shows up live
3213+/// here, or waits behind the delete and cannot resurrect the row.
3214+async fn passes_trash_guard(
3215+ tx: &Transaction<'_>,
3216+ table: &str,
3217+ id: &str,
3218+ guard: &TrashGuard<'_>,
3219+) -> Result<bool> {
3220+ let (sql, bind) = match guard {
3221+ TrashGuard::None => return Ok(true),
3222+ TrashGuard::Trashed => (
3223+ format!("SELECT 1 FROM {table} WHERE id = ?1 AND deleted_at IS NOT NULL"),
3224+ vec![id],
3225+ ),
3226+ TrashGuard::Expired { before } => (
3227+ format!(
3228+ "SELECT 1 FROM {table} WHERE id = ?1 \
3229+ AND deleted_at IS NOT NULL AND deleted_at < ?2"
3230+ ),
3231+ vec![id, *before],
3232+ ),
3233+ };
3234+ let mut rows = tx.query(&sql, bind).await.map_err(backend)?;
3235+ Ok(rows.next().await.map_err(backend)?.is_some())
3236+}
3237+
3238+/// The delete side of a trash purge. The candidates were read outside any
3239+/// transaction; this opens the immediate transaction, re-validates every
3240+/// candidate against `guard` under its write lock, takes the survivors'
3241+/// rows and shares, recomputes each owner's usage, and commits. Only then
3242+/// do the bytes go, and only for rows that actually went — a restore that
3243+/// landed in the selection window keeps its row, shares and bytes. The
3244+/// return carries what was really deleted.
3245+async fn commit_trash_purge(
3246+ store: &TursoStore,
3247+ files: Vec<(String, String)>,
3248+ folders: Vec<(String, String, Option<String>)>,
3249+ guard: &TrashGuard<'_>,
3250+) -> Result<(Vec<String>, Vec<String>)> {
3251+ // Folders deepest first: a parent row cannot go while a child row
3252+ // still names it.
3253+ let folder_ids = order_deepest_first(
3254+ &folders
3255+ .iter()
3256+ .map(|(id, _, parent)| (id.clone(), parent.clone()))
3257+ .collect::<Vec<_>>(),
3258+ );
3259+ let mut owners: Vec<String> = files.iter().map(|(_, owner)| owner.clone()).collect();
3260+ owners.extend(folders.iter().map(|(_, owner, _)| owner.clone()));
3261+ owners.sort();
3262+ owners.dedup();
3263+ let file_ids = files.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>();
3264+ let mut conn = store.tx_conn().await?;
3265+ let tx = conn
3266+ .transaction_with_behavior(TransactionBehavior::Immediate)
3267+ .await
3268+ .map_err(backend)?;
3269+ let deleted_files = delete_file_rows(&tx, &file_ids, guard).await?;
3270+ let deleted_folders = delete_folder_rows(&tx, &folder_ids, guard).await?;
3271+ for owner in &owners {
3272+ refresh_usage(&tx, owner).await?;
3273+ }
3274+ tx.commit().await.map_err(backend)?;
3275+ // After the delete: bytes may only follow a delete that committed.
3276+ // Best-effort — survivors are orphaned bytes the boot sweep collects.
3277+ if !deleted_files.is_empty() {
3278+ let mut keys = Vec::with_capacity(deleted_files.len() * 2);
3279+ for id in &deleted_files {
3280+ keys.push(format!("{FILES_DIR}/{id}"));
3281+ keys.push(format!("{THUMBS_DIR}/{id}"));
3282+ }
3283+ let keys = keys.iter().map(String::as_str).collect::<Vec<_>>();
3284+ let _ = store.blobs.delete(&keys).await;
3285+ }
3286+ for owner in owners {
3287+ store.announce([Topic::Library(owner.clone()), Topic::Trash(owner)]);
3288+ }
3289+ Ok((deleted_files, deleted_folders))
3290+}
3291+
3292+/// The trash candidates for `purge_expired`, read off the shared
3293+/// connection: files as `(id, owner)`, folders as `(id, owner, parent)`.
3294+/// Reading is deliberately outside the delete transaction — the two are
3295+/// separate moments, and `commit_trash_purge` re-validates every candidate
3296+/// under the write lock before taking it.
3297+async fn select_expired(
3298+ conn: &Connection,
3299+ before: &str,
3300+) -> Result<(Vec<(String, String)>, Vec<(String, String, Option<String>)>)> {
3301+ let mut file_ids = Vec::new();
3302+ let mut rows = conn
3303+ .query(
3304+ "SELECT id, owner_id FROM file WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
3305+ params![before],
3306+ )
3307+ .await
3308+ .map_err(backend)?;
3309+ while let Some(row) = rows.next().await.map_err(backend)? {
3310+ file_ids.push((text(&row, 0)?, text(&row, 1)?));
3311+ }
3312+ let mut folder_rows = Vec::new();
3313+ let mut rows = conn
3314+ .query(
3315+ "SELECT id, owner_id, parent_id FROM folder \
3316+ WHERE deleted_at IS NOT NULL AND deleted_at < ?1",
3317+ params![before],
3318+ )
3319+ .await
3320+ .map_err(backend)?;
3321+ while let Some(row) = rows.next().await.map_err(backend)? {
3322+ folder_rows.push((text(&row, 0)?, text(&row, 1)?, opt_text(&row, 2)?));
3323+ }
3324+ Ok((file_ids, folder_rows))
3325+}
3326+
3327+/// The trash candidates for `empty_trash`: the owner's files as bare ids
3328+/// and folders as `(id, parent_id)`, read off the shared connection with
3329+/// the same outside-the-transaction caveat as `select_expired`.
3330+async fn select_trash(
3331+ conn: &Connection,
3332+ owner_id: &str,
3333+) -> Result<(Vec<String>, Vec<(String, Option<String>)>)> {
3334+ let mut file_ids = Vec::new();
3335+ let mut rows = conn
3336+ .query(
3337+ "SELECT id FROM file WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
3338+ params![owner_id],
3339+ )
3340+ .await
3341+ .map_err(backend)?;
3342+ while let Some(row) = rows.next().await.map_err(backend)? {
3343+ file_ids.push(text(&row, 0)?);
3344+ }
3345+ let mut folder_rows = Vec::new();
3346+ let mut rows = conn
3347+ .query(
3348+ "SELECT id, parent_id FROM folder WHERE owner_id = ?1 AND deleted_at IS NOT NULL",
3349+ params![owner_id],
3350+ )
3351+ .await
3352+ .map_err(backend)?;
3353+ while let Some(row) = rows.next().await.map_err(backend)? {
3354+ folder_rows.push((text(&row, 0)?, opt_text(&row, 1)?));
3355+ }
3356+ Ok((file_ids, folder_rows))
3357+}
3358+
3359+/// The last word on an upload session, re-read inside the finish
3360+/// transaction: the row was vetted outside it, and the window since then
3361+/// belongs to abort, expiry and a second finish. Every expiry wears the
3362+/// same stamp format, so the text order is the time order.
3363+async fn finishable_session(tx: &Transaction<'_>, id: &str) -> Result<()> {
3364+ let mut rows = tx
3365+ .query(
3366+ "SELECT 1 FROM upload_session \
3367+ WHERE id = ?1 AND state = 'active' AND expires_at > ?2",
3368+ params![id, now_text()?],
3369+ )
3370+ .await
3371+ .map_err(backend)?;
3372+ let live = rows.next().await.map_err(backend)?.is_some();
3373+ drop(rows);
3374+ if !live {
3375+ return Err(StoreError::UploadExpired);
3376+ }
3377+ Ok(())
3378+}
3379+
3268 /// Deletes file rows and every share naming them: links and grants onto a3380 /// Deletes file rows and every share naming them: links and grants onto a
3269 /// purged file are dead, and the purge is what says so. Upload sessions that3381 /// purged file are dead, and the purge is what says so. Upload sessions that
3270-/// named these files never exist — sessions name folders, not files.3382+/// named these files never exist — sessions name folders, not files. Rows
3271-async fn delete_file_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()> {3383+/// the guard finds alive again are skipped whole — row and shares both,
3384+/// a live file keeps its grants — and the return carries the ids that
3385+/// actually went.
3386+async fn delete_file_rows(
3387+ tx: &Transaction<'_>,
3388+ ids: &[String],
3389+ guard: &TrashGuard<'_>,
3390+) -> Result<Vec<String>> {
3391+ let mut deleted = Vec::with_capacity(ids.len());
3272 for id in ids {3392 for id in ids {
3393+ if !passes_trash_guard(tx, "file", id, guard).await? {
3394+ continue;
3395+ }
3273 tx.execute(3396 tx.execute(
3274 "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'file'",3397 "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'file'",
3275 params![id.as_str()],3398 params![id.as_str()],
@@ -3285,16 +3408,26 @@ async fn delete_file_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()> {
3285 tx.execute("DELETE FROM file WHERE id = ?1", params![id.as_str()])3408 tx.execute("DELETE FROM file WHERE id = ?1", params![id.as_str()])
3286 .await3409 .await
3287 .map_err(backend)?;3410 .map_err(backend)?;
3411+ deleted.push(id.clone());
3288 }3412 }
3289- Ok(())3413+ Ok(deleted)
3290 }3414 }
3291 3415
3292 /// Deletes folder rows deepest first, with every share naming them. Active3416 /// Deletes folder rows deepest first, with every share naming them. Active
3293 /// upload sessions staged into these folders keep their rows — the upload3417 /// upload sessions staged into these folders keep their rows — the upload
3294 /// may still finish into the root's listing — but lose the folder: a session3418 /// may still finish into the root's listing — but lose the folder: a session
3295-/// cannot finish into trash that has been purged.3419+/// cannot finish into trash that has been purged. Rows the guard finds
3296-async fn delete_folder_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()> {3420+/// alive again are skipped whole; the return carries the ids that went.
3421+async fn delete_folder_rows(
3422+ tx: &Transaction<'_>,
3423+ ids: &[String],
3424+ guard: &TrashGuard<'_>,
3425+) -> Result<Vec<String>> {
3426+ let mut deleted = Vec::with_capacity(ids.len());
3297 for id in ids {3427 for id in ids {
3428+ if !passes_trash_guard(tx, "folder", id, guard).await? {
3429+ continue;
3430+ }
3298 tx.execute(3431 tx.execute(
3299 "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'folder'",3432 "DELETE FROM share_link WHERE target_id = ?1 AND kind = 'folder'",
3300 params![id.as_str()],3433 params![id.as_str()],
@@ -3316,8 +3449,9 @@ async fn delete_folder_rows(tx: &Transaction<'_>, ids: &[String]) -> Result<()>
3316 tx.execute("DELETE FROM folder WHERE id = ?1", params![id.as_str()])3449 tx.execute("DELETE FROM folder WHERE id = ?1", params![id.as_str()])
3317 .await3450 .await
3318 .map_err(backend)?;3451 .map_err(backend)?;
3452+ deleted.push(id.clone());
3319 }3453 }
3320- Ok(())3454+ Ok(deleted)
3321 }3455 }
3322 3456
3323 /// Orders `(id, parent_id)` rows deepest first, so a purge deletes children3457 /// Orders `(id, parent_id)` rows deepest first, so a purge deletes children
@@ -3464,4 +3598,224 @@ mod tests {
3464 assert!(cut.ends_with(" (2)"));3598 assert!(cut.ends_with(" (2)"));
3465 assert!(cut.starts_with("é"));3599 assert!(cut.starts_with("é"));
3466 }3600 }
3601+
3602+ #[tokio::test]
3603+ async fn a_restore_landing_between_select_and_delete_keeps_the_file() {
3604+ use time::Duration;
3605+
3606+ let dir = tempfile::tempdir().unwrap();
3607+ let storage = dir.path().join("storage");
3608+ let store = TursoStore::open(
3609+ dir.path().join("in.db").to_str().unwrap(),
3610+ Some(&storage),
3611+ )
3612+ .await
3613+ .unwrap();
3614+ let user = store
3615+ .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024)
3616+ .await
3617+ .unwrap();
3618+
3619+ // The purge_expired window: candidates read, then a restore lands,
3620+ // then the delete transaction opens on the stale candidates.
3621+ let file = store
3622+ .insert_file(&user.id, None, "keep.txt", b"precious")
3623+ .await
3624+ .unwrap();
3625+ store.delete_file(&file.id).await.unwrap();
3626+ let before = stamp(OffsetDateTime::now_utc() + Duration::days(31)).unwrap();
3627+ let conn = store.conn.lock().await;
3628+ let (files, folders) = select_expired(&conn, &before).await.unwrap();
3629+ drop(conn);
3630+ assert_eq!(files, vec![(file.id.clone(), user.id.clone())]);
3631+ assert!(folders.is_empty());
3632+ store.restore_file(&file.id).await.unwrap();
3633+ let (deleted_files, deleted_folders) = commit_trash_purge(
3634+ &store,
3635+ files,
3636+ folders,
3637+ &TrashGuard::Expired { before: &before },
3638+ )
3639+ .await
3640+ .unwrap();
3641+ assert!(deleted_files.is_empty());
3642+ assert!(deleted_folders.is_empty());
3643+ let live = store.file(&file.id).await.unwrap().unwrap();
3644+ assert!(live.deleted_at.is_none());
3645+ assert!(storage.join(FILES_DIR).join(&file.id).is_file());
3646+
3647+ // The empty_trash window, same interleave.
3648+ store.delete_file(&file.id).await.unwrap();
3649+ let conn = store.conn.lock().await;
3650+ let (files, folders) = select_trash(&conn, &user.id).await.unwrap();
3651+ drop(conn);
3652+ assert_eq!(files, vec![file.id.clone()]);
3653+ assert!(folders.is_empty());
3654+ store.restore_file(&file.id).await.unwrap();
3655+ let (deleted_files, deleted_folders) = commit_trash_purge(
3656+ &store,
3657+ files
3658+ .into_iter()
3659+ .map(|id| (id, user.id.clone()))
3660+ .collect::<Vec<_>>(),
3661+ folders
3662+ .into_iter()
3663+ .map(|(id, parent)| (id, user.id.clone(), parent))
3664+ .collect::<Vec<_>>(),
3665+ &TrashGuard::Trashed,
3666+ )
3667+ .await
3668+ .unwrap();
3669+ assert!(deleted_files.is_empty());
3670+ assert!(deleted_folders.is_empty());
3671+ assert!(store.file(&file.id).await.unwrap().unwrap().deleted_at.is_none());
3672+ assert!(storage.join(FILES_DIR).join(&file.id).is_file());
3673+
3674+ // The guards refuse only the resurrected: real trash still purges
3675+ // through the public paths, rows then bytes.
3676+ store.delete_file(&file.id).await.unwrap();
3677+ assert_eq!(store.empty_trash(&user.id).await.unwrap(), 1);
3678+ assert!(store.file(&file.id).await.unwrap().is_none());
3679+ assert!(!storage.join(FILES_DIR).join(&file.id).is_file());
3680+
3681+ let other = store
3682+ .insert_file(&user.id, None, "also-doomed.txt", b"precious")
3683+ .await
3684+ .unwrap();
3685+ store.delete_file(&other.id).await.unwrap();
3686+ assert_eq!(
3687+ store
3688+ .purge_expired(OffsetDateTime::now_utc() + Duration::days(31))
3689+ .await
3690+ .unwrap(),
3691+ 1
3692+ );
3693+ assert!(store.file(&other.id).await.unwrap().is_none());
3694+ assert!(!storage.join(FILES_DIR).join(&other.id).is_file());
3695+ }
3696+
3697+ #[tokio::test]
3698+ async fn a_purge_file_refuses_what_a_restore_brought_back() {
3699+ let dir = tempfile::tempdir().unwrap();
3700+ let storage = dir.path().join("storage");
3701+ let store = TursoStore::open(
3702+ dir.path().join("in.db").to_str().unwrap(),
3703+ Some(&storage),
3704+ )
3705+ .await
3706+ .unwrap();
3707+ let user = store
3708+ .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024)
3709+ .await
3710+ .unwrap();
3711+ let file = store
3712+ .insert_file(&user.id, None, "back.txt", b"precious")
3713+ .await
3714+ .unwrap();
3715+ store.delete_file(&file.id).await.unwrap();
3716+ store.restore_file(&file.id).await.unwrap();
3717+ // The restore won the window: the purge answers false for a live
3718+ // file and leaves row and bytes alone.
3719+ assert!(!store.purge_file(&file.id).await.unwrap());
3720+ assert!(store.file(&file.id).await.unwrap().unwrap().deleted_at.is_none());
3721+ assert!(storage.join(FILES_DIR).join(&file.id).is_file());
3722+ // Actual trash still purges, rows then bytes.
3723+ store.delete_file(&file.id).await.unwrap();
3724+ assert!(store.purge_file(&file.id).await.unwrap());
3725+ assert!(store.file(&file.id).await.unwrap().is_none());
3726+ assert!(!storage.join(FILES_DIR).join(&file.id).is_file());
3727+ }
3728+
3729+ #[tokio::test]
3730+ async fn a_purge_folder_refuses_what_a_restore_brought_back() {
3731+ let dir = tempfile::tempdir().unwrap();
3732+ let storage = dir.path().join("storage");
3733+ let store = TursoStore::open(
3734+ dir.path().join("in.db").to_str().unwrap(),
3735+ Some(&storage),
3736+ )
3737+ .await
3738+ .unwrap();
3739+ let user = store
3740+ .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024)
3741+ .await
3742+ .unwrap();
3743+ let root = store.create_folder(&user.id, None, "root").await.unwrap();
3744+ let kid = store
3745+ .create_folder(&user.id, Some(&root.id), "kid")
3746+ .await
3747+ .unwrap();
3748+ let file = store
3749+ .insert_file(&user.id, Some(&kid.id), "inside.txt", b"precious")
3750+ .await
3751+ .unwrap();
3752+ store.delete_folder(&root.id).await.unwrap();
3753+ store.restore_folder(&root.id).await.unwrap();
3754+ // The restore won the window: a live folder is never purged, and
3755+ // the refusal is the public face of that — nothing of the subtree
3756+ // goes.
3757+ assert!(matches!(
3758+ store.purge_folder(&root.id).await,
3759+ Err(StoreError::NotFound)
3760+ ));
3761+ assert!(store.folder(&root.id).await.unwrap().unwrap().deleted_at.is_none());
3762+ assert!(store.folder(&kid.id).await.unwrap().unwrap().deleted_at.is_none());
3763+ assert!(store.file(&file.id).await.unwrap().unwrap().deleted_at.is_none());
3764+ assert!(storage.join(FILES_DIR).join(&file.id).is_file());
3765+ // Trashed again, the whole subtree goes, rows then bytes.
3766+ store.delete_folder(&root.id).await.unwrap();
3767+ assert_eq!(store.purge_folder(&root.id).await.unwrap(), 3);
3768+ assert!(store.folder(&root.id).await.unwrap().is_none());
3769+ assert!(store.folder(&kid.id).await.unwrap().is_none());
3770+ assert!(store.file(&file.id).await.unwrap().is_none());
3771+ assert!(!storage.join(FILES_DIR).join(&file.id).is_file());
3772+ }
3773+
3774+ #[tokio::test]
3775+ async fn an_upload_finishes_once_and_never_after_an_abort() {
3776+ let dir = tempfile::tempdir().unwrap();
3777+ let storage = dir.path().join("storage");
3778+ let store = TursoStore::open(
3779+ dir.path().join("in.db").to_str().unwrap(),
3780+ Some(&storage),
3781+ )
3782+ .await
3783+ .unwrap();
3784+ let user = store
3785+ .provision_user("sub-alice", "alice@example.com", "Alice", 1024 * 1024 * 1024)
3786+ .await
3787+ .unwrap();
3788+ let session = store
3789+ .create_upload_session(&user.id, None, "once.bin", 4)
3790+ .await
3791+ .unwrap();
3792+ store.record_chunk(&session.id, 0, b"1234").await.unwrap();
3793+ let file = store.finish_upload(&session.id).await.unwrap();
3794+ assert_eq!(file.name, "once.bin");
3795+ // A racing second finish already assembled its view while the
3796+ // session was active — its chunks sit staged. The finished row
3797+ // itself must refuse it.
3798+ let chunk = chunk_path(&storage, &session.id, 0);
3799+ std::fs::create_dir_all(chunk.parent().unwrap()).unwrap();
3800+ std::fs::write(chunk, b"1234").unwrap();
3801+ assert!(matches!(
3802+ store.finish_upload(&session.id).await,
3803+ Err(StoreError::UploadExpired)
3804+ ));
3805+ let files = store.list_children(&user.id, None).await.unwrap().files.len();
3806+ assert_eq!(files, 1);
3807+ // An aborted session never finishes: no file row, ever.
3808+ let session = store
3809+ .create_upload_session(&user.id, None, "gone.bin", 4)
3810+ .await
3811+ .unwrap();
3812+ store.record_chunk(&session.id, 0, b"1234").await.unwrap();
3813+ store.abort_upload(&session.id).await.unwrap();
3814+ assert!(matches!(
3815+ store.finish_upload(&session.id).await,
3816+ Err(StoreError::UploadExpired)
3817+ ));
3818+ let files = store.list_children(&user.id, None).await.unwrap().files.len();
3819+ assert_eq!(files, 1);
3820+ }
3467 }3821 }