the boot sweep reclaims only what is older than the database: the store outlives any one copy of the database now that the bytes sit in a shared bucket, so an unknown object goes only when it is no newer than the newest moment the rows know — a crash orphan ages past the next upload and goes on a later boot, while uploads a stale database never heard of are always newer and are kept and said out loud; an empty database reclaims nothing. A database three days behind the bucket cost four real uploads tonight
Browse files at this commitcfa2ba1f13cf9a8eb5f8b73c69aa914e58fe93a4Parent: 8ec00d25 changed files +249 -39
- config/in.toml +6 -0
- crates/in-core/src/store/blobs.rs +38 -8
- crates/in-core/src/store/r2.rs +12 -5
- crates/in-core/src/store/turso_store.rs +107 -19
- crates/in-core/tests/store.rs +86 -7
config/in.tomlmodified+6 -0
| @@ -67,6 +67,12 @@ client_secret = "in-dev-secret" | |||
| 67 | # Absence is meaningful: no table, no bucket, local bytes. Nothing here is | 67 | # Absence is meaningful: no table, no bucket, local bytes. Nothing here is |
| 68 | # ever completed into the file for you. | 68 | # ever completed into the file for you. |
| 69 | # | 69 | # |
| 70 | +# A bucket outlives any one copy of the database, so the boot sweep reclaims | ||
| 71 | +# an object no row names only when it is older than the newest moment the | ||
| 72 | +# database knows. Booting against a database that is behind the bucket keeps | ||
| 73 | +# every newer object and says so, one log line each; an empty database | ||
| 74 | +# deletes nothing at all. | ||
| 75 | +# | ||
| 70 | # Migrating an existing deployment's bytes into the bucket — database and | 76 | # Migrating an existing deployment's bytes into the bucket — database and |
| 71 | # storage tree stay where they are; run once with the server stopped: | 77 | # storage tree stay where they are; run once with the server stopped: |
| 72 | # rclone copy <storage>/files ":s3,provider=Cloudflare,access_key_id=<key id>,secret_access_key=<secret>,region=auto,endpoint=https://<account_id>.r2.cloudflarestorage.com:<bucket>/files" | 78 | # rclone copy <storage>/files ":s3,provider=Cloudflare,access_key_id=<key id>,secret_access_key=<secret>,region=auto,endpoint=https://<account_id>.r2.cloudflarestorage.com:<bucket>/files" |
crates/in-core/src/store/blobs.rsmodified+38 -8
| @@ -18,6 +18,7 @@ | |||
| 18 | 18 | ||
| 19 | use std::path::{Path, PathBuf}; | 19 | use std::path::{Path, PathBuf}; |
| 20 | 20 | ||
| 21 | +use time::OffsetDateTime; | ||
| 21 | use ulid::Ulid; | 22 | use ulid::Ulid; |
| 22 | 23 | ||
| 23 | use super::FileSpan; | 24 | use super::FileSpan; |
| @@ -76,10 +77,34 @@ pub trait Blobs: Send + Sync + 'static { | |||
| 76 | /// not an error. | 77 | /// not an error. |
| 77 | async fn delete(&self, keys: &[&str]) -> Result<(), BlobError>; | 78 | async fn delete(&self, keys: &[&str]) -> Result<(), BlobError>; |
| 78 | 79 | ||
| 79 | - /// The names under one directory of the key space (`"files"` or | 80 | + /// What one directory of the key space (`"files"` or `"thumbs"`) holds, |
| 80 | - /// `"thumbs"`), temp files included — the orphan sweep's eyes. A | 81 | + /// temp files included — the orphan sweep's eyes, with the moment each |
| 81 | - /// listing is a walk of one directory, never of the whole tree. | 82 | + /// object last changed, because the sweep only reclaims what is older |
| 82 | - async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError>; | 83 | + /// than the newest row the database knows. A listing is a walk of one |
| 84 | + /// directory, never of the whole tree. | ||
| 85 | + async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError>; | ||
| 86 | + | ||
| 87 | + /// The names alone, for callers that do not weigh ages. | ||
| 88 | + async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> { | ||
| 89 | + Ok(self | ||
| 90 | + .list_with_times(dir) | ||
| 91 | + .await? | ||
| 92 | + .into_iter() | ||
| 93 | + .map(|entry| entry.name) | ||
| 94 | + .collect()) | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// One object in a directory of the key space: its name, and when its bytes | ||
| 99 | +/// last changed. `modified` is `None` when the backend will not say — an | ||
| 100 | +/// object whose age is unknown is never reclaimed, because the sweep cannot | ||
| 101 | +/// prove it predates the database. | ||
| 102 | +#[derive(Debug, Clone)] | ||
| 103 | +pub struct BlobEntry { | ||
| 104 | + /// The name under the directory, the way a row would name it. | ||
| 105 | + pub name: String, | ||
| 106 | + /// When the object last changed, as the backend reports it. | ||
| 107 | + pub modified: Option<OffsetDateTime>, | ||
| 83 | } | 108 | } |
| 84 | 109 | ||
| 85 | /// The blob tree on the local filesystem: `root/files/<id>` and | 110 | /// The blob tree on the local filesystem: `root/files/<id>` and |
| @@ -194,7 +219,7 @@ impl Blobs for LocalBlobs { | |||
| 194 | Ok(()) | 219 | Ok(()) |
| 195 | } | 220 | } |
| 196 | 221 | ||
| 197 | - async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> { | 222 | + async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError> { |
| 198 | let entries = match std::fs::read_dir(self.root.join(dir)) { | 223 | let entries = match std::fs::read_dir(self.root.join(dir)) { |
| 199 | Ok(entries) => entries, | 224 | Ok(entries) => entries, |
| 200 | // A half of the tree that does not exist yet lists empty: a | 225 | // A half of the tree that does not exist yet lists empty: a |
| @@ -202,7 +227,7 @@ impl Blobs for LocalBlobs { | |||
| 202 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), | 227 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 203 | Err(e) => return Err(e.into()), | 228 | Err(e) => return Err(e.into()), |
| 204 | }; | 229 | }; |
| 205 | - let mut names = Vec::new(); | 230 | + let mut out = Vec::new(); |
| 206 | for entry in entries { | 231 | for entry in entries { |
| 207 | let entry = entry?; | 232 | let entry = entry?; |
| 208 | // Files only: the sweep reads this as "what the tree holds", | 233 | // Files only: the sweep reads this as "what the tree holds", |
| @@ -211,9 +236,14 @@ impl Blobs for LocalBlobs { | |||
| 211 | continue; | 236 | continue; |
| 212 | } | 237 | } |
| 213 | if let Ok(name) = entry.file_name().into_string() { | 238 | if let Ok(name) = entry.file_name().into_string() { |
| 214 | - names.push(name); | 239 | + let modified = entry |
| 240 | + .metadata() | ||
| 241 | + .and_then(|meta| meta.modified()) | ||
| 242 | + .ok() | ||
| 243 | + .map(OffsetDateTime::from); | ||
| 244 | + out.push(BlobEntry { name, modified }); | ||
| 215 | } | 245 | } |
| 216 | } | 246 | } |
| 217 | - Ok(names) | 247 | + Ok(out) |
| 218 | } | 248 | } |
| 219 | } | 249 | } |
crates/in-core/src/store/r2.rsmodified+12 -5
| @@ -27,7 +27,7 @@ use object_store::{ | |||
| 27 | }; | 27 | }; |
| 28 | 28 | ||
| 29 | use super::FileSpan; | 29 | use super::FileSpan; |
| 30 | -use super::blobs::{BlobError, Blobs}; | 30 | +use super::blobs::{BlobEntry, BlobError, Blobs}; |
| 31 | 31 | ||
| 32 | /// The part size [`R2Blobs::adopt`] streams up in: 8 MiB, the chunk size the | 32 | /// The part size [`R2Blobs::adopt`] streams up in: 8 MiB, the chunk size the |
| 33 | /// server fixes for uploads, so the staging side and the bucket side speak | 33 | /// server fixes for uploads, so the staging side and the bucket side speak |
| @@ -236,10 +236,10 @@ impl Blobs for R2Blobs { | |||
| 236 | Ok(()) | 236 | Ok(()) |
| 237 | } | 237 | } |
| 238 | 238 | ||
| 239 | - async fn list(&self, dir: &str) -> Result<Vec<String>, BlobError> { | 239 | + async fn list_with_times(&self, dir: &str) -> Result<Vec<BlobEntry>, BlobError> { |
| 240 | let separator = format!("{dir}/"); | 240 | let separator = format!("{dir}/"); |
| 241 | let prefix = ObjectPath::from(separator.clone()); | 241 | let prefix = ObjectPath::from(separator.clone()); |
| 242 | - let mut names = Vec::new(); | 242 | + let mut out = Vec::new(); |
| 243 | let mut listing = self.store.list(Some(&prefix)); | 243 | let mut listing = self.store.list(Some(&prefix)); |
| 244 | while let Some(entry) = listing.next().await { | 244 | while let Some(entry) = listing.next().await { |
| 245 | let meta = entry?; | 245 | let meta = entry?; |
| @@ -247,8 +247,15 @@ impl Blobs for R2Blobs { | |||
| 247 | // sweep compares these names against rows, and a nested name | 247 | // sweep compares these names against rows, and a nested name |
| 248 | // that lost its directory would lie about what it names. | 248 | // that lost its directory would lie about what it names. |
| 249 | let full = meta.location.to_string(); | 249 | let full = meta.location.to_string(); |
| 250 | - names.push(full.strip_prefix(&separator).unwrap_or(&full).to_string()); | 250 | + // `last_modified` is chrono's; the crate's own clock is `time`, |
| 251 | + // and a unix second crosses between them without a dependency. | ||
| 252 | + let modified = time::OffsetDateTime::from_unix_timestamp(meta.last_modified.timestamp()) | ||
| 253 | + .ok(); | ||
| 254 | + out.push(BlobEntry { | ||
| 255 | + name: full.strip_prefix(&separator).unwrap_or(&full).to_string(), | ||
| 256 | + modified, | ||
| 257 | + }); | ||
| 251 | } | 258 | } |
| 252 | - Ok(names) | 259 | + Ok(out) |
| 253 | } | 260 | } |
| 254 | } | 261 | } |
crates/in-core/src/store/turso_store.rsmodified+107 -19
| @@ -220,6 +220,18 @@ impl TursoStore { | |||
| 220 | /// whose file is gone is only said out loud and otherwise kept, because | 220 | /// whose file is gone is only said out loud and otherwise kept, because |
| 221 | /// deleting the row would turn a lost file into a lost fact — the row is | 221 | /// deleting the row would turn a lost file into a lost fact — the row is |
| 222 | /// still what screens list, and a re-upload replaces it cleanly. | 222 | /// still what screens list, and a re-upload replaces it cleanly. |
| 223 | + /// | ||
| 224 | + /// The store outlives any one copy of the database now that the bytes | ||
| 225 | + /// sit in a shared bucket, so an unknown object is reclaimed ONLY when | ||
| 226 | + /// it is no newer than the newest moment the database knows (the latest | ||
| 227 | + /// `file.created_at` / `file.updated_at` / `upload_session.created_at`); | ||
| 228 | + /// anything newer is kept and said out loud. A crash orphan is older | ||
| 229 | + /// than the next successful upload and goes on a later boot, while | ||
| 230 | + /// uploads a stale database never heard of are always newer than its | ||
| 231 | + /// newest row and are never touched — a database three days behind the | ||
| 232 | + /// bucket once cost four real uploads here. An empty database knows no | ||
| 233 | + /// moment at all, which is the stale case at its worst: it deletes | ||
| 234 | + /// nothing. | ||
| 223 | async fn sweep_orphan_files(&self) -> Result<()> { | 235 | async fn sweep_orphan_files(&self) -> Result<()> { |
| 224 | // The whole pass — the id reads and the directory walks — holds the | 236 | // The whole pass — the id reads and the directory walks — holds the |
| 225 | // database's write lock. A writer lands a new file while holding | 237 | // database's write lock. A writer lands a new file while holding |
| @@ -244,39 +256,67 @@ impl TursoStore { | |||
| 244 | "SELECT id FROM upload_session WHERE state = 'active'", | 256 | "SELECT id FROM upload_session WHERE state = 'active'", |
| 245 | ) | 257 | ) |
| 246 | .await?; | 258 | .await?; |
| 259 | + // The watermark: the newest moment any row carries. Read under the | ||
| 260 | + // same lock as the ids, so a writer that commits mid-sweep either | ||
| 261 | + // is in both sets or in neither. | ||
| 262 | + let watermark = newest_known(&tx).await?; | ||
| 263 | + let mut kept = 0usize; | ||
| 264 | + // Whether an unknown object may be reclaimed: only one no newer | ||
| 265 | + // than the database's newest moment. An age the backend will not | ||
| 266 | + // report, and an empty database, both answer no. | ||
| 267 | + let reclaimable = |modified: Option<OffsetDateTime>| match (watermark, modified) { | ||
| 268 | + (Some(newest), Some(at)) => at <= newest, | ||
| 269 | + _ => false, | ||
| 270 | + }; | ||
| 247 | for (dir, known, kind) in [ | 271 | for (dir, known, kind) in [ |
| 248 | (FILES_DIR, &files, "file"), | 272 | (FILES_DIR, &files, "file"), |
| 249 | (THUMBS_DIR, &thumbs, "thumbnail"), | 273 | (THUMBS_DIR, &thumbs, "thumbnail"), |
| 250 | ] { | 274 | ] { |
| 251 | // One listing per half: the names the tree holds, temp files | 275 | // One listing per half: the names the tree holds, temp files |
| 252 | - // included — a `.tmp` is an orphan like any other. | 276 | + // included — a `.tmp` is an orphan like any other — each with |
| 253 | - let names: std::collections::HashSet<String> = self | 277 | + // the moment it last changed. |
| 278 | + let entries = self | ||
| 254 | .blobs | 279 | .blobs |
| 255 | - .list(dir) | 280 | + .list_with_times(dir) |
| 256 | .await | 281 | .await |
| 257 | - .map_err(|e| StoreError::Backend(e.to_string()))? | 282 | + .map_err(|e| StoreError::Backend(e.to_string()))?; |
| 258 | - .into_iter() | 283 | + let names: std::collections::HashSet<&str> = |
| 259 | - .collect(); | 284 | + entries.iter().map(|entry| entry.name.as_str()).collect(); |
| 260 | for id in known.iter() { | 285 | for id in known.iter() { |
| 261 | - if !names.contains(id) { | 286 | + if !names.contains(id.as_str()) { |
| 262 | eprintln!("{kind} {id} names a file that is not there"); | 287 | eprintln!("{kind} {id} names a file that is not there"); |
| 263 | } | 288 | } |
| 264 | } | 289 | } |
| 265 | - for name in names { | 290 | + for entry in &entries { |
| 266 | - if !known.contains(&name) { | 291 | + if known.contains(&entry.name) { |
| 267 | - if let Err(e) = self.blobs.delete(&[&format!("{dir}/{name}")]).await { | 292 | + continue; |
| 268 | - eprintln!("could not delete orphaned storage file {dir}/{name}: {e}"); | 293 | + } |
| 269 | - } | 294 | + if !reclaimable(entry.modified) { |
| 295 | + kept += 1; | ||
| 296 | + eprintln!( | ||
| 297 | + "{kind} {} is newer than anything the database knows and was kept — \ | ||
| 298 | + the database may be behind the store", | ||
| 299 | + entry.name | ||
| 300 | + ); | ||
| 301 | + continue; | ||
| 302 | + } | ||
| 303 | + if let Err(e) = self.blobs.delete(&[&format!("{dir}/{}", entry.name)]).await { | ||
| 304 | + eprintln!("could not delete orphaned storage file {dir}/{}: {e}", entry.name); | ||
| 270 | } | 305 | } |
| 271 | } | 306 | } |
| 272 | } | 307 | } |
| 273 | // A staged-chunk directory outlives its session only through a crash | 308 | // A staged-chunk directory outlives its session only through a crash |
| 274 | // between the session write and the first chunk, or a removed session | 309 | // between the session write and the first chunk, or a removed session |
| 275 | - // row — either way nothing will ever finish it, so it goes. | 310 | + // row — either way nothing will ever finish it, so it goes, under the |
| 311 | + // same watermark rule and with the directory's own mtime as its age. | ||
| 276 | let uploads = self.storage.join(UPLOADS_DIR); | 312 | let uploads = self.storage.join(UPLOADS_DIR); |
| 277 | let entries = match std::fs::read_dir(&uploads) { | 313 | let entries = match std::fs::read_dir(&uploads) { |
| 278 | Ok(entries) => entries, | 314 | Ok(entries) => entries, |
| 279 | - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), | 315 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 316 | + report_kept(kept); | ||
| 317 | + tx.commit().await.map_err(backend)?; | ||
| 318 | + return Ok(()); | ||
| 319 | + } | ||
| 280 | Err(e) => return Err(backend(e)), | 320 | Err(e) => return Err(backend(e)), |
| 281 | }; | 321 | }; |
| 282 | for entry in entries { | 322 | for entry in entries { |
| @@ -285,17 +325,31 @@ impl TursoStore { | |||
| 285 | if !path.is_dir() { | 325 | if !path.is_dir() { |
| 286 | continue; | 326 | continue; |
| 287 | } | 327 | } |
| 288 | - let named = entry | 328 | + let name = entry.file_name().to_string_lossy().into_owned(); |
| 289 | - .file_name() | 329 | + if sessions.contains(&name) { |
| 290 | - .to_str() | 330 | + continue; |
| 291 | - .is_some_and(|n| sessions.contains(n)); | 331 | + } |
| 292 | - if !named && let Err(e) = std::fs::remove_dir_all(&path) { | 332 | + let modified = entry |
| 333 | + .metadata() | ||
| 334 | + .and_then(|meta| meta.modified()) | ||
| 335 | + .ok() | ||
| 336 | + .map(OffsetDateTime::from); | ||
| 337 | + if !reclaimable(modified) { | ||
| 338 | + kept += 1; | ||
| 339 | + eprintln!( | ||
| 340 | + "staged upload {name} is newer than anything the database knows and was kept — \ | ||
| 341 | + the database may be behind the store" | ||
| 342 | + ); | ||
| 343 | + continue; | ||
| 344 | + } | ||
| 345 | + if let Err(e) = std::fs::remove_dir_all(&path) { | ||
| 293 | eprintln!( | 346 | eprintln!( |
| 294 | "could not delete orphaned upload directory {}: {e}", | 347 | "could not delete orphaned upload directory {}: {e}", |
| 295 | path.display() | 348 | path.display() |
| 296 | ); | 349 | ); |
| 297 | } | 350 | } |
| 298 | } | 351 | } |
| 352 | + report_kept(kept); | ||
| 299 | // Nothing was written through the transaction: it exists to hold | 353 | // Nothing was written through the transaction: it exists to hold |
| 300 | // the write lock across the walk, and committing it ends the pass. | 354 | // the write lock across the walk, and committing it ends the pass. |
| 301 | tx.commit().await.map_err(backend)?; | 355 | tx.commit().await.map_err(backend)?; |
| @@ -811,6 +865,40 @@ async fn known_ids(conn: &Connection, sql: &str) -> Result<std::collections::Has | |||
| 811 | Ok(out) | 865 | Ok(out) |
| 812 | } | 866 | } |
| 813 | 867 | ||
| 868 | +/// The newest moment the database knows: the latest of the file rows' | ||
| 869 | +/// stamps and the upload sessions'. `None` for a database with no rows at | ||
| 870 | +/// all, which is what tells the sweep it may reclaim nothing. | ||
| 871 | +async fn newest_known(conn: &Connection) -> Result<Option<OffsetDateTime>> { | ||
| 872 | + let mut newest: Option<OffsetDateTime> = None; | ||
| 873 | + for sql in [ | ||
| 874 | + "SELECT MAX(created_at) FROM file", | ||
| 875 | + "SELECT MAX(updated_at) FROM file", | ||
| 876 | + "SELECT MAX(created_at) FROM upload_session", | ||
| 877 | + ] { | ||
| 878 | + let mut rows = conn.query(sql, ()).await.map_err(backend)?; | ||
| 879 | + if let Some(row) = rows.next().await.map_err(backend)? | ||
| 880 | + && let Some(raw) = row.get::<Option<String>>(0).map_err(backend)? | ||
| 881 | + { | ||
| 882 | + let at = parse_stamp(&raw)?; | ||
| 883 | + if newest.is_none_or(|seen| at > seen) { | ||
| 884 | + newest = Some(at); | ||
| 885 | + } | ||
| 886 | + } | ||
| 887 | + } | ||
| 888 | + Ok(newest) | ||
| 889 | +} | ||
| 890 | + | ||
| 891 | +/// The one summary line a sweep that kept something owes the log; a sweep | ||
| 892 | +/// that kept nothing says nothing. | ||
| 893 | +fn report_kept(kept: usize) { | ||
| 894 | + if kept > 0 { | ||
| 895 | + eprintln!( | ||
| 896 | + "boot sweep kept {kept} unknown object(s) newer than the database — \ | ||
| 897 | + this database may be behind the store" | ||
| 898 | + ); | ||
| 899 | + } | ||
| 900 | +} | ||
| 901 | + | ||
| 814 | /// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main | 902 | /// A database sidecar (`in.db-wal`, `in.db-shm`): the file beside the main |
| 815 | /// one, wearing the same name plus the suffix. | 903 | /// one, wearing the same name plus the suffix. |
| 816 | fn sibling(path: &str, suffix: &str) -> std::path::PathBuf { | 904 | fn sibling(path: &str, suffix: &str) -> std::path::PathBuf { |
crates/in-core/tests/store.rsmodified+86 -7
| @@ -1095,19 +1095,95 @@ async fn search_finds_live_names_and_nothing_else() { | |||
| 1095 | assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty()); | 1095 | assert!(scratch.store.search(&user.id, " ", 50).await.unwrap().files.is_empty()); |
| 1096 | } | 1096 | } |
| 1097 | 1097 | ||
| 1098 | +/// Moves the database's watermark — the newest moment any row carries — to | ||
| 1099 | +/// `stamp`, so a test decides which side of it the planted junk falls on | ||
| 1100 | +/// rather than the clock. `insert_file` writes "now"; a far-future stamp | ||
| 1101 | +/// makes everything on disk older than the database, a far-past one makes | ||
| 1102 | +/// everything newer. | ||
| 1103 | +async fn restamp_files(scratch: &Scratch, stamp: &str) { | ||
| 1104 | + let conn = raw_conn(scratch).await; | ||
| 1105 | + conn.execute( | ||
| 1106 | + "UPDATE file SET created_at = ?1, updated_at = ?1", | ||
| 1107 | + turso::params![stamp], | ||
| 1108 | + ) | ||
| 1109 | + .await | ||
| 1110 | + .unwrap(); | ||
| 1111 | +} | ||
| 1112 | + | ||
| 1098 | #[tokio::test] | 1113 | #[tokio::test] |
| 1099 | async fn the_boot_sweep_deletes_files_no_row_names() { | 1114 | async fn the_boot_sweep_deletes_files_no_row_names() { |
| 1100 | let mut scratch = Scratch::open().await; | 1115 | let mut scratch = Scratch::open().await; |
| 1116 | + let user = alice(&scratch.store).await; | ||
| 1117 | + scratch.store.insert_file(&user.id, None, "kept", b"data").await.unwrap(); | ||
| 1101 | let stray = scratch.storage.join("files").join("stray"); | 1118 | let stray = scratch.storage.join("files").join("stray"); |
| 1102 | std::fs::write(&stray, b"orphan").unwrap(); | 1119 | std::fs::write(&stray, b"orphan").unwrap(); |
| 1103 | let ghost = scratch.storage.join("uploads").join("ghost"); | 1120 | let ghost = scratch.storage.join("uploads").join("ghost"); |
| 1104 | std::fs::create_dir_all(&ghost).unwrap(); | 1121 | std::fs::create_dir_all(&ghost).unwrap(); |
| 1105 | std::fs::write(ghost.join("0"), b"chunk").unwrap(); | 1122 | std::fs::write(ghost.join("0"), b"chunk").unwrap(); |
| 1123 | + // Both are older than what the database knows, which is the only case | ||
| 1124 | + // in which the sweep may reclaim them. | ||
| 1125 | + restamp_files(&scratch, "2099-01-01T00:00:00Z").await; | ||
| 1106 | scratch.reopen().await; | 1126 | scratch.reopen().await; |
| 1107 | assert!(!stray.exists()); | 1127 | assert!(!stray.exists()); |
| 1108 | assert!(!ghost.exists()); | 1128 | assert!(!ghost.exists()); |
| 1109 | } | 1129 | } |
| 1110 | 1130 | ||
| 1131 | +/// The incident this rule exists for: a database three days behind the | ||
| 1132 | +/// shared bucket deleted four real uploads. An object newer than the newest | ||
| 1133 | +/// row is an upload the database has not heard of yet, never an orphan. | ||
| 1134 | +#[tokio::test] | ||
| 1135 | +async fn the_boot_sweep_keeps_what_is_newer_than_the_database() { | ||
| 1136 | + let mut scratch = Scratch::open().await; | ||
| 1137 | + let user = alice(&scratch.store).await; | ||
| 1138 | + scratch.store.insert_file(&user.id, None, "old", b"data").await.unwrap(); | ||
| 1139 | + // The database is behind the store: its rows are ancient, the objects | ||
| 1140 | + // beside them arrived since. | ||
| 1141 | + restamp_files(&scratch, "2000-01-01T00:00:00Z").await; | ||
| 1142 | + let unknown = scratch.storage.join("files").join("uploaded-elsewhere"); | ||
| 1143 | + std::fs::write(&unknown, b"a real upload").unwrap(); | ||
| 1144 | + let staged = scratch.storage.join("uploads").join("live-session"); | ||
| 1145 | + std::fs::create_dir_all(&staged).unwrap(); | ||
| 1146 | + scratch.reopen().await; | ||
| 1147 | + assert!(unknown.exists()); | ||
| 1148 | + assert!(staged.exists()); | ||
| 1149 | +} | ||
| 1150 | + | ||
| 1151 | +/// A fresh database against a populated bucket is the stale case at its | ||
| 1152 | +/// worst: it knows no moment at all, so it may reclaim nothing. | ||
| 1153 | +#[tokio::test] | ||
| 1154 | +async fn the_boot_sweep_keeps_everything_when_the_database_is_empty() { | ||
| 1155 | + let mut scratch = Scratch::open().await; | ||
| 1156 | + let stray = scratch.storage.join("files").join("stray"); | ||
| 1157 | + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); | ||
| 1158 | + std::fs::write(&stray, b"someone else's upload").unwrap(); | ||
| 1159 | + let ghost = scratch.storage.join("uploads").join("ghost"); | ||
| 1160 | + std::fs::create_dir_all(&ghost).unwrap(); | ||
| 1161 | + scratch.reopen().await; | ||
| 1162 | + assert!(stray.exists()); | ||
| 1163 | + assert!(ghost.exists()); | ||
| 1164 | +} | ||
| 1165 | + | ||
| 1166 | +/// Thumbnails follow the files' rule, both ways. | ||
| 1167 | +#[tokio::test] | ||
| 1168 | +async fn the_boot_sweep_weighs_thumbnails_by_the_same_watermark() { | ||
| 1169 | + let mut scratch = Scratch::open().await; | ||
| 1170 | + let user = alice(&scratch.store).await; | ||
| 1171 | + scratch.store.insert_file(&user.id, None, "row", b"data").await.unwrap(); | ||
| 1172 | + let thumbs = scratch.storage.join("thumbs"); | ||
| 1173 | + std::fs::create_dir_all(&thumbs).unwrap(); | ||
| 1174 | + let old = thumbs.join("stale-thumb"); | ||
| 1175 | + std::fs::write(&old, b"orphan").unwrap(); | ||
| 1176 | + restamp_files(&scratch, "2099-01-01T00:00:00Z").await; | ||
| 1177 | + scratch.reopen().await; | ||
| 1178 | + assert!(!old.exists()); | ||
| 1179 | + | ||
| 1180 | + let new = thumbs.join("fresh-thumb"); | ||
| 1181 | + std::fs::write(&new, b"newer than the database").unwrap(); | ||
| 1182 | + restamp_files(&scratch, "2000-01-01T00:00:00Z").await; | ||
| 1183 | + scratch.reopen().await; | ||
| 1184 | + assert!(new.exists()); | ||
| 1185 | +} | ||
| 1186 | + | ||
| 1111 | #[tokio::test] | 1187 | #[tokio::test] |
| 1112 | async fn a_row_whose_file_is_missing_is_kept() { | 1188 | async fn a_row_whose_file_is_missing_is_kept() { |
| 1113 | let mut scratch = Scratch::open().await; | 1189 | let mut scratch = Scratch::open().await; |
| @@ -1174,7 +1250,7 @@ async fn the_sweep_waits_for_a_writer_instead_of_deleting_its_file() { | |||
| 1174 | "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ | 1250 | "INSERT INTO file (id, owner_id, folder_id, name, mime, size_bytes, \ |
| 1175 | thumb_state, created_at, updated_at, deleted_at, download_count) \ | 1251 | thumb_state, created_at, updated_at, deleted_at, download_count) \ |
| 1176 | VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \ | 1252 | VALUES ('midwrite', ?1, NULL, 'midwrite.txt', 'text/plain', 8, 'none', \ |
| 1177 | - '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', NULL, 0)", | 1253 | + '2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z', NULL, 0)", |
| 1178 | turso::params![user.id.as_str()], | 1254 | turso::params![user.id.as_str()], |
| 1179 | ) | 1255 | ) |
| 1180 | .await | 1256 | .await |
| @@ -1916,18 +1992,21 @@ async fn r2_purge_takes_the_key_and_the_bucket_forgets_it() { | |||
| 1916 | async fn r2_the_sweep_takes_orphans_and_leaves_known_keys() { | 1992 | async fn r2_the_sweep_takes_orphans_and_leaves_known_keys() { |
| 1917 | let scratch = R2Scratch::open().await; | 1993 | let scratch = R2Scratch::open().await; |
| 1918 | let alice = alice(&scratch.store).await; | 1994 | let alice = alice(&scratch.store).await; |
| 1919 | - let file = scratch | ||
| 1920 | - .store | ||
| 1921 | - .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes") | ||
| 1922 | - .await | ||
| 1923 | - .unwrap(); | ||
| 1924 | // A client-side PUT with no row behind it — the exact shape the boot | 1995 | // A client-side PUT with no row behind it — the exact shape the boot |
| 1925 | - // sweep's orphan pass exists to clean. | 1996 | + // sweep's orphan pass exists to clean. It lands BEFORE the row below, |
| 1997 | + // which is what makes it older than the database's newest moment and so | ||
| 1998 | + // reclaimable; an object newer than that is an upload the database has | ||
| 1999 | + // not heard of and is kept. | ||
| 1926 | scratch | 2000 | scratch |
| 1927 | .blobs | 2001 | .blobs |
| 1928 | .put("files/orphaned-by-crash", b"stray") | 2002 | .put("files/orphaned-by-crash", b"stray") |
| 1929 | .await | 2003 | .await |
| 1930 | .unwrap(); | 2004 | .unwrap(); |
| 2005 | + let file = scratch | ||
| 2006 | + .store | ||
| 2007 | + .insert_file(alice.id.as_str(), None, "kept.bin", b"kept bytes") | ||
| 2008 | + .await | ||
| 2009 | + .unwrap(); | ||
| 1931 | // `boot_sweeps` runs the orphan sweep over the bucket, exactly as the | 2010 | // `boot_sweeps` runs the orphan sweep over the bucket, exactly as the |
| 1932 | // server does in its background task. | 2011 | // server does in its background task. |
| 1933 | scratch.store.boot_sweeps().await.unwrap(); | 2012 | scratch.store.boot_sweeps().await.unwrap(); |