//! The object store's rows (contracts.md 5): services, which are namespaces with a quota, and the objects //! each service keeps under its own ids. //! //! Namespace: every function takes the service key from the caller's verified token (`svc`). Nothing a //! request says picks the namespace, so the same `external_id` in two services is two rows. //! //! Blobs: an object's bytes live at `objects//`, so objects of one service with the same //! bytes share one blob. A blob is removed only by [`Store::retire_blob`], and only when no row names it //! and no write is in the middle of storing it. [`Store::hold_blob`] is that write's claim on the key, taken //! before the bytes are put and released after the row commits. //! //! Quota: `services.used_bytes` is the sum of the sizes of the service's objects. A put checks the new total //! inside its write transaction, which the single writer serialises, so two parallel puts cannot both pass. use std::collections::HashMap; use std::sync::{Arc, Mutex as StdMutex, PoisonError}; use turso::{Connection, Row}; use crate::blob::BlobStore; use crate::error::{Error, Result}; use crate::store::{ Inner, Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, missing_row, }; use crate::time::now_stamp; /// Quota of a service that has none yet: 10 GiB. Used when a service first makes an authorised call. pub const DEFAULT_SERVICE_QUOTA: i64 = 10 * 1024 * 1024 * 1024; /// The settings key of the quota a new service gets. It is read when the service row is created. pub const SERVICE_QUOTA_SETTING: &str = "default_service_quota_bytes"; /// Longest `external_id` the contracts allow. pub const MAX_EXTERNAL_ID: usize = 128; /// Checks an `external_id` against contracts.md 5: 1 to 128 characters of `[A-Za-z0-9._-]`. The id is /// never part of a path (blobs are named by hash), so the charset only has to keep ids printable and /// unambiguous. pub fn check_external_id(id: &str) -> Result<()> { let allowed = id .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')); if id.is_empty() || id.len() > MAX_EXTERNAL_ID || !allowed { return Err(Error::Invalid("bad_external_id".into())); } Ok(()) } /// The blob key of an object's bytes: `objects//`. The hash is lower-case hex. pub fn object_blob_key(service: &str, sha256: &str) -> String { format!("objects/{service}/{sha256}") } /// Column list for [`map_service`]. Keep the two in step. const SERVICE_COLS: &str = "key, quota_bytes, used_bytes, created_at"; /// Column list for [`map_object`]. Keep the two in step. const OBJECT_COLS: &str = "service, external_id, size, sha256, content_type, name, blob_key, created_at, updated_at"; /// A service: a namespace of objects with its own quota. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Service { /// The family key the token's `svc` named, such as `iz`. pub key: String, /// The most bytes the service may store. pub quota_bytes: i64, /// The bytes its objects use, counted once per object (shared blobs count twice). pub used_bytes: i64, /// When the service first made a call. pub created_at: String, } /// One object of a service. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Object { /// The service that owns the object. pub service: String, /// The id the service chose. pub external_id: String, /// Length in bytes. pub size: i64, /// Lower-case hex SHA-256 of the bytes. pub sha256: String, /// The `Content-Type` the service sent, stored as given. pub content_type: String, /// The `X-Object-Name` the service sent, if any. pub name: Option, /// The blob that holds the bytes. pub blob_key: String, /// When the object was first stored. pub created_at: String, /// When the object was last replaced. pub updated_at: String, } /// A service's usage, as `GET /api/v1/usage` reports it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Usage { /// The service quota. pub quota_bytes: i64, /// Bytes used by its objects. pub used_bytes: i64, /// Number of objects. pub objects: i64, } /// What a put stores. The bytes are already at `blob_key`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NewObject { /// The namespace, from the verified token. pub service: String, /// The id the service chose. Already checked by [`check_external_id`]. pub external_id: String, /// Length in bytes. pub size: i64, /// Lower-case hex SHA-256 of the bytes. pub sha256: String, /// The stored `Content-Type`. pub content_type: String, /// The cleaned `X-Object-Name`, if any. pub name: Option, /// When true, a put over an existing object is refused (`If-None-Match: *`). pub create_only: bool, } /// What a put did. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PutOutcome { /// The row is stored. `replaced_blob` is the blob the old bytes lived at, when that blob is not the new /// one. The caller retires it with [`Store::retire_blob`]. Stored { /// The object as stored. Boxed, so the refusal variants stay small. object: Box, /// `true` when the id was new, `false` when an existing object was replaced. created: bool, /// The blob the replaced bytes used, when it differs from the new one. replaced_blob: Option, }, /// The new total would exceed the service quota. Nothing changed. QuotaExceeded, /// `create_only` was set and the id is taken. Nothing changed. Exists, } /// The claim a write holds on a blob key between putting the bytes and committing the row. While it is /// held, [`Store::retire_blob`] leaves the key alone. pub struct BlobHold { inner: Arc, key: String, } impl Drop for BlobHold { fn drop(&mut self) { let mut held = self .inner .blobs .held .lock() .unwrap_or_else(PoisonError::into_inner); if let Some(count) = held.get_mut(&self.key) { *count -= 1; if *count == 0 { held.remove(&self.key); } } } } /// The gate that orders blob writes against blob removal. `retire` is held while a removal decides and /// deletes, and while a write registers its claim, so a removal and a write of the same key never overlap. /// `held` counts the open claims per key. Both are in-process, which is right for one `in` process. #[derive(Default)] pub(crate) struct BlobGate { retire: tokio::sync::Mutex<()>, held: StdMutex>, } /// Column `i` of a row selected with [`SERVICE_COLS`]. fn map_service(row: &Row) -> Result { Ok(Service { key: col_text(row, 0)?, quota_bytes: col_int(row, 1)?, used_bytes: col_int(row, 2)?, created_at: col_text(row, 3)?, }) } /// Maps a row selected with [`OBJECT_COLS`]. fn map_object(row: &Row) -> Result { Ok(Object { service: col_text(row, 0)?, external_id: col_text(row, 1)?, size: col_int(row, 2)?, sha256: col_text(row, 3)?, content_type: col_text(row, 4)?, name: col_opt_text(row, 5)?, blob_key: col_text(row, 6)?, created_at: col_text(row, 7)?, updated_at: col_text(row, 8)?, }) } /// A service row by key. async fn service_row(conn: &Connection, key: &str) -> Result> { fetch_opt( conn, &format!("SELECT {SERVICE_COLS} FROM services WHERE key = ?1"), (key.to_owned(),), map_service, ) .await } /// An object of a service by its id. Another service's id finds nothing. async fn object_row(conn: &Connection, service: &str, id: &str) -> Result> { fetch_opt( conn, &format!("SELECT {OBJECT_COLS} FROM objects WHERE service = ?1 AND external_id = ?2"), (service.to_owned(), id.to_owned()), map_object, ) .await } impl Store { /// The service with this key, if it has made a call before. pub async fn service(&self, key: &str) -> Result> { let conn = self.read_conn().await; service_row(&conn, key).await } /// Every service, by key. For the admin page. pub async fn services(&self) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, &format!("SELECT {SERVICE_COLS} FROM services ORDER BY key"), (), map_service, ) .await } /// The service with this key, created with `default_quota` when it is new. Called on every /// authorised machine call, so the common case is a read. pub async fn ensure_service(&self, key: &str, default_quota: i64) -> Result { if let Some(service) = self.service(key).await? { return Ok(service); } { let conn = self.inner.conn.lock().await; // `OR IGNORE` keeps a concurrent first call from failing on the primary key. conn.execute( "INSERT OR IGNORE INTO services (key, quota_bytes, used_bytes, created_at) \ VALUES (?1, ?2, 0, ?3)", (key.to_owned(), default_quota, now_stamp()), ) .await .map_err(db_err)?; } self.service(key).await?.ok_or_else(missing_row) } /// Sets a service's quota in bytes. Lowering it below the current use is allowed: the service then /// cannot store more until it frees space. pub async fn set_service_quota(&self, key: &str, bytes: i64) -> Result<()> { if bytes < 0 { return Err(Error::Invalid("quota_negative".into())); } let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE services SET quota_bytes = ?2 WHERE key = ?1", (key.to_owned(), bytes), ) .await .map_err(db_err)?; if changed == 0 { return Err(Error::NotFound); } Ok(()) } /// The usage of a service: quota, bytes used and the object count. A service that does not exist has /// none, so the answer is `NotFound`. pub async fn service_usage(&self, service: &str) -> Result { let conn = self.read_conn().await; let row = service_row(&conn, service).await?.ok_or(Error::NotFound)?; let objects = fetch_opt( &conn, "SELECT COUNT(*) FROM objects WHERE service = ?1", (service.to_owned(),), |row| col_int(row, 0), ) .await? .unwrap_or(0); Ok(Usage { quota_bytes: row.quota_bytes, used_bytes: row.used_bytes, objects, }) } /// An object of `service` by its id, or `None`. pub async fn service_object(&self, service: &str, id: &str) -> Result> { let conn = self.read_conn().await; object_row(&conn, service, id).await } /// Stores an object row, replacing the object with the same id in the same service. In one /// transaction: the new total must fit the quota (the old object's bytes are given back first), the row /// is inserted or updated, and `used_bytes` is moved by the difference. A replace keeps the original /// `created_at`. /// /// The bytes must already be at the blob key of `new.sha256`. The old bytes are not removed here: the /// caller retires `replaced_blob` after this returns. pub async fn put_object(&self, new: NewObject) -> Result { let now = now_stamp(); let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let service = service_row(&tx, &new.service) .await? .ok_or(Error::NotFound)?; let old = object_row(&tx, &new.service, &new.external_id).await?; if new.create_only && old.is_some() { return Ok(PutOutcome::Exists); } let old_size = old.as_ref().map_or(0, |object| object.size); let used_after = service.used_bytes - old_size + new.size; if used_after > service.quota_bytes { return Ok(PutOutcome::QuotaExceeded); } let blob_key = object_blob_key(&new.service, &new.sha256); let created = old.is_none(); let created_at = old .as_ref() .map_or_else(|| now.clone(), |object| object.created_at.clone()); if created { tx.execute( "INSERT INTO objects (service, external_id, size, sha256, content_type, name, \ blob_key, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", ( new.service.clone(), new.external_id.clone(), new.size, new.sha256.clone(), new.content_type.clone(), new.name.clone(), blob_key.clone(), created_at, now.clone(), ), ) .await .map_err(db_err)?; } else { tx.execute( "UPDATE objects SET size = ?3, sha256 = ?4, content_type = ?5, name = ?6, \ blob_key = ?7, updated_at = ?8 WHERE service = ?1 AND external_id = ?2", ( new.service.clone(), new.external_id.clone(), new.size, new.sha256.clone(), new.content_type.clone(), new.name.clone(), blob_key.clone(), now.clone(), ), ) .await .map_err(db_err)?; } tx.execute( "UPDATE services SET used_bytes = ?2 WHERE key = ?1", (new.service.clone(), used_after), ) .await .map_err(db_err)?; let object = object_row(&tx, &new.service, &new.external_id) .await? .ok_or_else(missing_row)?; let replaced_blob = old .map(|object| object.blob_key) .filter(|key| *key != blob_key); Ok(PutOutcome::Stored { object: Box::new(object), created, replaced_blob, }) } .await; finish(tx, outcome).await } /// Removes an object of `service` and gives its bytes back to the quota. Returns the removed row, so the /// caller can retire its blob, or `None` when there was no such object (the caller still answers `204`). pub async fn delete_object(&self, service: &str, id: &str) -> Result> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result> = async { let Some(old) = object_row(&tx, service, id).await? else { return Ok(None); }; tx.execute( "DELETE FROM objects WHERE service = ?1 AND external_id = ?2", (service.to_owned(), id.to_owned()), ) .await .map_err(db_err)?; tx.execute( "UPDATE services SET used_bytes = used_bytes - ?2 WHERE key = ?1", (service.to_owned(), old.size), ) .await .map_err(db_err)?; Ok(Some(old)) } .await; finish(tx, outcome).await } /// Claims `key` for a write that is about to put bytes there. Waits for any removal in progress, so /// the bytes cannot be removed between the put and the row. The claim lasts until the returned guard is /// dropped, which the caller does once the row has committed (or the write has been refused). pub async fn hold_blob(&self, key: &str) -> BlobHold { let _gate = self.inner.blobs.retire.lock().await; let mut held = self .inner .blobs .held .lock() .unwrap_or_else(PoisonError::into_inner); *held.entry(key.to_owned()).or_insert(0) += 1; BlobHold { inner: Arc::clone(&self.inner), key: key.to_owned(), } } /// Removes the blob at `key` when it is safe: no open claim holds it and no row names it. Returns /// `true` when the blob was deleted. `false` means it is still in use, or in the middle of a write; the /// sweeper finds it later if it is still unreferenced. pub async fn retire_blob(&self, key: &str, blobs: &dyn BlobStore) -> Result { let _gate = self.inner.blobs.retire.lock().await; let claimed = self .inner .blobs .held .lock() .unwrap_or_else(PoisonError::into_inner) .contains_key(key); if claimed || self.blob_is_named(key).await? { return Ok(false); } blobs.delete(key).await?; Ok(true) } /// Whether an object row names this blob key. async fn blob_is_named(&self, key: &str) -> Result { let conn = self.read_conn().await; Ok(fetch_opt( &conn, "SELECT 1 FROM objects WHERE blob_key = ?1 LIMIT 1", (key.to_owned(),), |_| Ok(()), ) .await? .is_some()) } } #[cfg(test)] mod tests { use super::*; use crate::blob::local::LocalBlobs; use crate::staging::StagedFile; const SERVICE: &str = "iz"; const OTHER: &str = "im"; /// A store with two services (`iz` and `im`) at `quota`, and a blob tree in the same temp dir. async fn setup(quota: i64) -> (tempfile::TempDir, Store, LocalBlobs) { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("in.db")).await.unwrap(); store.ensure_service(SERVICE, quota).await.unwrap(); store.ensure_service(OTHER, quota).await.unwrap(); let blobs = LocalBlobs::new(dir.path().join("blobs")).unwrap(); (dir, store, blobs) } /// Stages `bytes`, puts them at their hash key as the API does, and returns the row input for them. async fn stage( dir: &tempfile::TempDir, blobs: &LocalBlobs, service: &str, id: &str, bytes: &[u8], ) -> NewObject { let mut staged = StagedFile::create(dir.path(), 1 << 20).await.unwrap(); staged.write(bytes).await.unwrap(); let staged = staged.finish().await.unwrap(); let key = object_blob_key(service, &staged.sha256); blobs.put_file(&key, &staged.path).await.unwrap(); NewObject { service: service.into(), external_id: id.into(), size: staged.size as i64, sha256: staged.sha256, content_type: "application/octet-stream".into(), name: None, create_only: false, } } #[test] fn external_ids_follow_the_contract_charset_and_length() { assert!(check_external_id("task-1_a.b").is_ok()); assert!(check_external_id(&"a".repeat(128)).is_ok()); for bad in ["", "../x", "a/b", "a b", "ΓΌ", &"a".repeat(129)] { assert!(check_external_id(bad).is_err(), "{bad:?}"); } } /// The same id in two services is two objects, each with its own bytes. #[tokio::test] async fn the_same_id_in_two_services_is_two_objects() { let (dir, store, blobs) = setup(1 << 20).await; let a = stage(&dir, &blobs, SERVICE, "same", b"alpha").await; let b = stage(&dir, &blobs, OTHER, "same", b"beta!!").await; store.put_object(a).await.unwrap(); store.put_object(b).await.unwrap(); let mine = store .service_object(SERVICE, "same") .await .unwrap() .unwrap(); let theirs = store.service_object(OTHER, "same").await.unwrap().unwrap(); assert_eq!(mine.size, 5); assert_eq!(theirs.size, 6); assert!( store .service_object(SERVICE, "missing") .await .unwrap() .is_none() ); } /// A replace keeps one row, moves the quota by the difference, and names the old blob for retiring. /// Retiring it removes the old bytes, because nothing else names them. #[tokio::test] async fn a_replace_keeps_one_row_and_the_old_bytes_go_when_unreferenced() { let (dir, store, blobs) = setup(1 << 20).await; let first = stage(&dir, &blobs, SERVICE, "doc", b"first version").await; let old_key = object_blob_key(SERVICE, &first.sha256); store.put_object(first).await.unwrap(); let second = stage(&dir, &blobs, SERVICE, "doc", b"second").await; let new_key = object_blob_key(SERVICE, &second.sha256); let PutOutcome::Stored { created, replaced_blob, .. } = store.put_object(second).await.unwrap() else { panic!("the replace must be stored"); }; assert!(!created); assert_eq!(replaced_blob.as_deref(), Some(old_key.as_str())); assert!(store.retire_blob(&old_key, &blobs).await.unwrap()); let usage = store.service_usage(SERVICE).await.unwrap(); assert_eq!(usage.objects, 1); assert_eq!(usage.used_bytes, 6); assert_eq!(blobs.size(&old_key).await.unwrap(), None); assert_eq!(blobs.size(&new_key).await.unwrap(), Some(6)); } /// Two objects with the same bytes share one blob. Deleting one keeps the bytes for the other. #[tokio::test] async fn identical_content_shares_a_blob_until_the_last_object_goes() { let (dir, store, blobs) = setup(1 << 20).await; let a = stage(&dir, &blobs, SERVICE, "a", b"same bytes").await; let b = stage(&dir, &blobs, SERVICE, "b", b"same bytes").await; let key = object_blob_key(SERVICE, &a.sha256); store.put_object(a).await.unwrap(); store.put_object(b).await.unwrap(); let removed = store.delete_object(SERVICE, "a").await.unwrap().unwrap(); assert_eq!(removed.blob_key, key); assert!(!store.retire_blob(&key, &blobs).await.unwrap()); assert_eq!(blobs.size(&key).await.unwrap(), Some(10)); assert!(store.service_object(SERVICE, "b").await.unwrap().is_some()); store.delete_object(SERVICE, "b").await.unwrap(); assert!(store.retire_blob(&key, &blobs).await.unwrap()); assert_eq!(blobs.size(&key).await.unwrap(), None); assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 0); } /// A put that would pass the quota is refused and changes nothing. A replace gives back its old size /// first, so it may grow only as far as the quota allows. #[tokio::test] async fn the_quota_is_checked_inside_the_write() { let (dir, store, blobs) = setup(10).await; store .put_object(stage(&dir, &blobs, SERVICE, "one", b"123456").await) .await .unwrap(); let outcome = store .put_object(stage(&dir, &blobs, SERVICE, "two", b"12345").await) .await .unwrap(); assert_eq!(outcome, PutOutcome::QuotaExceeded); assert!( store .service_object(SERVICE, "two") .await .unwrap() .is_none() ); assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 6); let grow = store .put_object(stage(&dir, &blobs, SERVICE, "one", b"1234567890").await) .await .unwrap(); assert!(matches!(grow, PutOutcome::Stored { created: false, .. })); assert_eq!(store.service_usage(SERVICE).await.unwrap().used_bytes, 10); } /// A blob that a write holds is not removed, even when no row names it yet. #[tokio::test] async fn a_held_blob_is_not_retired() { let (dir, store, blobs) = setup(1 << 20).await; let object = stage(&dir, &blobs, SERVICE, "x", b"pending").await; let key = object_blob_key(SERVICE, &object.sha256); let hold = store.hold_blob(&key).await; assert!(!store.retire_blob(&key, &blobs).await.unwrap()); drop(hold); assert!(store.retire_blob(&key, &blobs).await.unwrap()); } }