diff --git a/crates/tinystoragedrivers-blob/src/mongodb.rs b/crates/tinystoragedrivers-blob/src/mongodb.rs index 3995cb2d..0f846251 100644 --- a/crates/tinystoragedrivers-blob/src/mongodb.rs +++ b/crates/tinystoragedrivers-blob/src/mongodb.rs @@ -34,6 +34,8 @@ pub struct MongoBlobStore { connection: MongoConnection, scope: Scope, indexes_ready: Arc>, + #[cfg(test)] + sweep_pause: Option<(Arc, Arc)>, } impl MongoBlobStore { @@ -44,9 +46,22 @@ impl MongoBlobStore { connection, scope, indexes_ready: Arc::new(AsyncMutex::new(false)), + #[cfg(test)] + sweep_pause: None, } } + /// Pause `sweep_expired` between its two passes. + #[cfg(test)] + pub(crate) fn pause_sweep_for_test( + mut self, + started: Arc, + resume: Arc, + ) -> Self { + self.sweep_pause = Some((started, resume)); + self + } + async fn bucket(&self) -> Result { let mut indexes_ready = self.indexes_ready.lock().await; if !*indexes_ready { @@ -549,15 +564,28 @@ impl BlobStore for MongoBlobStore { let expired = self .files(doc! {"metadata.expires_at_ms": {"$lte": to_i64((self.connection.clock())())}}) .await?; - let mut keys = BTreeMap::new(); + // The newest expired version of each key. `files` sorts `_id` + // descending within a filename, so the first one seen is it. + let mut newest_expired = BTreeMap::new(); for file in expired { if let Some(key) = file.filename { - keys.insert(key, ()); + newest_expired.entry(key).or_insert(file.id); } } + #[cfg(test)] + if let Some((started, resume)) = &self.sweep_pause { + started.notify_one(); + resume.notified().await; + } let mut count = 0_u64; - for key in keys.into_keys() { - for file in self.files(doc! {"filename": &key}).await? { + for (key, bound) in newest_expired { + // Only versions up to that one: a version written since this sweep + // began is newer and stays. Older versions go first, so a failure + // partway never leaves a superseded version as the newest. + let versions = self + .files(doc! {"filename": &key, "_id": {"$lte": bound}}) + .await?; + for file in versions.into_iter().rev() { self.delete_id(file.id).await?; count += 1; } diff --git a/crates/tinystoragedrivers-blob/src/mongodb_tests.rs b/crates/tinystoragedrivers-blob/src/mongodb_tests.rs index b4992abd..fa34c222 100644 --- a/crates/tinystoragedrivers-blob/src/mongodb_tests.rs +++ b/crates/tinystoragedrivers-blob/src/mongodb_tests.rs @@ -86,6 +86,128 @@ async fn mongodb_blob_streams_scoped_ttl_and_paged_listing() { connection.database().drop().await.unwrap(); } +#[tokio::test] +async fn mongodb_sweep_reclaims_only_up_to_the_newest_expired_version() { + let Ok(url) = std::env::var("TSD_MONGO_URL") else { + eprintln!( + "mongodb_sweep_reclaims_only_up_to_the_newest_expired_version: TSD_MONGO_URL is not set; skipping" + ); + return; + }; + let database = format!("tsd_blob_sweep_{}_{}", std::process::id(), ObjectId::new()); + let now = Arc::new(AtomicU64::new(10_000)); + let clock = Arc::clone(&now); + let connection = MongoConnection::connect(&url, &database) + .await + .unwrap() + .with_clock(Arc::new(move || clock.load(Ordering::SeqCst))); + let store = MongoBlobStore::new(connection.clone(), Scope::new("local").unwrap()); + + // An expired newest version over an older live one: the sweep takes both, + // so the key stays absent instead of falling back to superseded bytes. + raw_version(&store, "shadowed", b"old", None).await; + raw_version(&store, "shadowed", b"expired", Some(10_005)).await; + // A version newer than the expired one, as a writer racing the sweep + // leaves it, is past the sweep's bound and survives. + raw_version(&store, "rewritten", b"expired", Some(10_005)).await; + raw_version(&store, "rewritten", b"fresh", None).await; + now.store(10_010, Ordering::SeqCst); + + assert!(store.get("shadowed").await.unwrap().is_none()); + assert_eq!(store.sweep_expired().await.unwrap(), 3); + assert!(store.get("shadowed").await.unwrap().is_none()); + assert!( + store + .files(doc! {"filename": "shadowed"}) + .await + .unwrap() + .is_empty() + ); + assert_eq!( + store.get("rewritten").await.unwrap().unwrap().bytes, + b"fresh" + ); + assert_eq!( + store + .files(doc! {"filename": "rewritten"}) + .await + .unwrap() + .len(), + 1 + ); + + connection.database().drop().await.unwrap(); +} + +#[tokio::test] +async fn mongodb_sweep_keeps_a_blob_rewritten_between_its_passes() { + let Ok(url) = std::env::var("TSD_MONGO_URL") else { + eprintln!( + "mongodb_sweep_keeps_a_blob_rewritten_between_its_passes: TSD_MONGO_URL is not set; skipping" + ); + return; + }; + let database = format!( + "tsd_blob_resweep_{}_{}", + std::process::id(), + ObjectId::new() + ); + let now = Arc::new(AtomicU64::new(10_000)); + let clock = Arc::clone(&now); + let connection = MongoConnection::connect(&url, &database) + .await + .unwrap() + .with_clock(Arc::new(move || clock.load(Ordering::SeqCst))); + let started = Arc::new(tokio::sync::Notify::new()); + let resume = Arc::new(tokio::sync::Notify::new()); + let store = MongoBlobStore::new(connection.clone(), Scope::new("local").unwrap()) + .pause_sweep_for_test(Arc::clone(&started), Arc::clone(&resume)); + store + .put_expiring( + "session", + b"stale".to_vec(), + None, + Duration::from_millis(10), + ) + .await + .unwrap(); + now.store(10_010, Ordering::SeqCst); + + // The sweep has found `session` expired; the key is written again before + // the sweep deletes anything. + let sweeping = { + let store = store.clone(); + tokio::spawn(async move { store.sweep_expired().await }) + }; + started.notified().await; + store.put("session", b"fresh".to_vec(), None).await.unwrap(); + resume.notify_one(); + sweeping.await.unwrap().unwrap(); + + assert_eq!( + store.get("session").await.unwrap().unwrap().bytes, + b"fresh", + "the version written between the sweep's passes survives" + ); + connection.database().drop().await.unwrap(); +} + +/// Writes one GridFS version of `key` without `upload`'s cleanup of older +/// versions: the state a failed cleanup or a racing writer leaves behind. +async fn raw_version(store: &MongoBlobStore, key: &str, bytes: &[u8], expiry: Option) { + let written = (store.connection.clock())(); + let mut upload = store + .bucket() + .await + .unwrap() + .open_upload_stream(key) + .metadata(store.metadata(None, expiry, written)) + .await + .unwrap(); + upload.write_all(bytes).await.unwrap(); + upload.close().await.unwrap(); +} + async fn assert_mongo_sealed_blob_visibility(store: &MongoBlobStore, other_scope: &MongoBlobStore) { let sealed_key = "_tsd/sealed/events/g0"; assert!(store.supports_sealed_blobs()); diff --git a/docs/specs/storage-bus.md b/docs/specs/storage-bus.md index c25b01e8..3bc0a5d5 100644 --- a/docs/specs/storage-bus.md +++ b/docs/specs/storage-bus.md @@ -172,11 +172,15 @@ as absent; a zero lifetime is expired on arrival; a plain `put` of the key clears the lifetime; reclaiming the storage is the driver's business. The memory, SQLite, file, MongoDB and S3 drivers provide it (S3 as `x-amz-meta-` user metadata, so `list` already pays one HEAD per object; MongoDB as -`metadata.expires_at_ms` on the GridFS file). Reclaiming is each driver's -business: file and MongoDB reclaim the lapsed blob on the read that notices it -(and expose `sweep_expired_blobs` / `sweep_expired_blobs_generation` for a -sweeper), S3 only reclaims through `S3Blobs::sweep_expired` because object -deletes cannot be conditional. The conformance suite asserts expiry on every +`metadata.expires_at_ms` on the GridFS file). No driver reclaims storage on +the read that notices a lapsed blob: reads only treat it as absent, and the +storage is freed by `BlobStore::sweep_expired` or an explicit delete. The +memory and SQLite sweeps check expiry and delete under one lock or +transaction. MongoDB deletes only the versions of a key up to its newest +expired one, oldest first: a version written during the sweep keeps its new +value, and a sweep that fails partway never leaves a superseded version as the +newest. The file and S3 sweeps check, then delete (S3 object deletes cannot be +conditional), so a key re-put between the two can still be removed. The conformance suite asserts expiry on every driver that claims the capability. On the wire `PutBlobRequest` and `PutBlobStreamRequest` gain an optional `ttl_ms` and `BlobCapabilities` gains `ttl`; adding them made the contract version 3. A