//! Resumable uploads: the rows that track an upload from its first request to its finish, and the //! transactions that decide its fate. //! //! The quota is promised, not spent, while an upload is open. Creating an upload checks the headroom //! inside the write transaction, with the declared sizes of the owner's other live uploads counted //! against it, so two creates that would together exceed the quota cannot both succeed. Finishing //! checks again, in the transaction that inserts the file row and marks the upload `done`. Bytes never //! change here: the chunks live on disk (`staging.rs`), and the blob is put before the finish commits. use turso::{Connection, Row}; use crate::error::{Error, Result}; use crate::quota; use crate::store::files::{File, NewFile, insert_file_in}; use crate::store::folders::live_folder; use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; use crate::time::now_stamp; /// Most uploads one person may have open (active and not expired) at once. A create past it is /// `Conflict("too_many_uploads")`, so an account cannot hold thousands of empty uploads at no cost. pub const MAX_OPEN_UPLOADS: i64 = 64; /// Column list for [`map_upload`]. Keep the two in step. pub const UPLOAD_COLS: &str = "id, owner, folder_id, name, size, chunk_size, state, file_id, created_at, expires_at"; /// One row of the `uploads` table. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Upload { /// Upload id (a lower-case ULID). It names the staging directory. pub id: String, /// The person who started the upload. pub owner: String, /// Destination folder, or `None` for the top level. pub folder_id: Option, /// The cleaned file name the finished file gets (a postfix is added at finish if it is taken). pub name: String, /// Declared size in bytes. Every chunk is checked against it. pub size: i64, /// Chunk size in bytes the upload was started with. pub chunk_size: i64, /// `active`, `done` or `aborted`. pub state: String, /// The file the upload became, once it is `done`. pub file_id: Option, /// When the upload was started. pub created_at: String, /// When the upload expires: 24 hours after its last chunk. pub expires_at: String, } impl Upload { /// Whether the upload may still take chunks or finish at `now`: active and not yet expired. pub fn is_open(&self, now: &str) -> bool { self.state == "active" && self.expires_at.as_str() > now } } /// What a new upload needs. The name is already cleaned by the caller. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NewUpload { /// Id, made by the caller with `store::new_id`, so the staging directory can be named first. pub id: String, /// The person who starts the upload. pub owner: String, /// Destination folder, or `None` for the top level. pub folder: Option, /// The cleaned file name. pub name: String, /// Declared size in bytes. pub size: i64, /// Chunk size in bytes. pub chunk_size: i64, /// Expiry stamp: now plus 24 hours. pub expires_at: String, } /// Maps a row selected with [`UPLOAD_COLS`]. pub fn map_upload(row: &Row) -> Result { Ok(Upload { id: col_text(row, 0)?, owner: col_text(row, 1)?, folder_id: col_opt_text(row, 2)?, name: col_text(row, 3)?, size: col_int(row, 4)?, chunk_size: col_int(row, 5)?, state: col_text(row, 6)?, file_id: col_opt_text(row, 7)?, created_at: col_text(row, 8)?, expires_at: col_text(row, 9)?, }) } /// An upload of `owner` by id. Foreign ids find nothing, so they look missing. async fn upload_of(conn: &Connection, owner: &str, id: &str) -> Result> { fetch_opt( conn, &format!("SELECT {UPLOAD_COLS} FROM uploads WHERE id = ?1 AND owner = ?2"), (id.to_string(), owner.to_string()), map_upload, ) .await } /// The bytes the owner's open uploads have declared, except the upload named `except`. Those bytes are /// promised to be written, so a new upload or a finish cannot take them. async fn declared_claims(conn: &Connection, owner: &str, now: &str, except: &str) -> Result { fetch_opt( conn, "SELECT COALESCE(SUM(size), 0) FROM uploads \ WHERE owner = ?1 AND state = 'active' AND expires_at > ?2 AND id <> ?3", (owner.to_string(), now.to_string(), except.to_string()), |row| col_int(row, 0), ) .await .map(|sum| sum.unwrap_or(0)) } impl Store { /// The bytes the owner's open uploads have declared. A new upload or a direct upload must leave them room. pub async fn declared_claims_of(&self, owner: &str) -> Result { let conn = self.read_conn().await; declared_claims(&conn, owner, &now_stamp(), "").await } /// An upload of `owner` by id, or `None` when there is no such upload for that person. pub async fn upload(&self, owner: &str, id: &str) -> Result> { let conn = self.read_conn().await; upload_of(&conn, owner, id).await } /// Whether an upload with this id is still active. The sweeper keeps the staging directory of an active /// upload whatever its age, because the upload may still receive chunks. pub async fn upload_is_open(&self, id: &str) -> Result { let conn = self.read_conn().await; Ok(fetch_opt( &conn, "SELECT 1 FROM uploads WHERE id = ?1 AND state = 'active'", (id.to_string(),), |row| col_int(row, 0), ) .await? .is_some()) } /// Starts an upload. In one transaction: the folder must be a live folder of the owner, the size /// must not be above `max_size`, and it must fit the headroom after the other open uploads' declared /// sizes. A refusal for size is `Invalid("too_large")`, one for quota is `Conflict("quota_exceeded")`, /// and one for too many open uploads ([`MAX_OPEN_UPLOADS`]) is `Conflict("too_many_uploads")`. pub async fn create_upload(&self, new: NewUpload, max_size: i64) -> Result { if new.size < 0 || new.size > max_size { return Err(Error::Invalid("too_large".into())); } 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 { if let Some(f) = new.folder.as_deref() { live_folder(&tx, &new.owner, f).await?; } let (quota, used) = fetch_opt( &tx, "SELECT quota_bytes, used_bytes FROM members WHERE sub = ?1", (new.owner.clone(),), |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), ) .await? .ok_or(Error::NotFound)?; let open: i64 = fetch_opt( &tx, "SELECT COUNT(*) FROM uploads WHERE owner = ?1 AND state = 'active' AND expires_at > ?2", (new.owner.clone(), now.clone()), |row| col_int(row, 0), ) .await? .unwrap_or(0); if open >= MAX_OPEN_UPLOADS { return Err(Error::Conflict("too_many_uploads".into())); } let claims = declared_claims(&tx, &new.owner, &now, "").await?; if !quota::fits(new.size, quota::headroom(quota, used, claims)) { return Err(Error::Conflict("quota_exceeded".into())); } tx.execute( "INSERT INTO uploads (id, owner, folder_id, name, size, chunk_size, state, created_at, \ expires_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'active', ?7, ?8)", ( new.id.clone(), new.owner.clone(), new.folder.clone(), new.name.clone(), new.size, new.chunk_size, now.clone(), new.expires_at.clone(), ), ) .await .map_err(db_err)?; upload_of(&tx, &new.owner, &new.id) .await? .ok_or(Error::NotFound) } .await; finish(tx, outcome).await } /// Moves the expiry of an open upload of `owner` to `expires_at`. Returns `false` when the upload is /// not open for that person any more. pub async fn touch_upload(&self, owner: &str, id: &str, expires_at: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE uploads SET expires_at = ?3 WHERE id = ?1 AND owner = ?2 AND state = 'active'", (id.to_string(), owner.to_string(), expires_at.to_string()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Cancels an open upload of `owner`. Returns `false` when it was not open (already finished, /// already cancelled, or not theirs). The staging directory is the caller's to remove. pub async fn abort_upload(&self, owner: &str, id: &str) -> Result { let conn = self.inner.conn.lock().await; let changed = conn .execute( "UPDATE uploads SET state = 'aborted' WHERE id = ?1 AND owner = ?2 AND state = 'active'", (id.to_string(), owner.to_string()), ) .await .map_err(db_err)?; Ok(changed == 1) } /// Turns an open upload into a file. The blob must already be stored under the key of `file.id`. /// In one transaction: the upload must still be open, `file.size` must equal the declared size, the /// quota is checked against the owner's other open uploads, the row is inserted with the upload's own /// folder and name, and the upload becomes `done`. A refused finish leaves the upload open. /// `file.folder`, `file.name` and `file.staged_claims` are ignored: the upload row decides them. pub async fn finish_upload(&self, owner: &str, id: &str, file: NewFile) -> 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 upload = upload_of(&tx, owner, id).await?.ok_or(Error::NotFound)?; if !upload.is_open(&now) { return Err(Error::Conflict("upload_not_active".into())); } if file.size != upload.size { return Err(Error::Invalid("size_mismatch".into())); } let claims = declared_claims(&tx, owner, &now, id).await?; let row = insert_file_in( &tx, NewFile { folder: upload.folder_id.clone(), name: upload.name.clone(), staged_claims: claims, owner: owner.to_owned(), ..file }, ) .await?; tx.execute( "UPDATE uploads SET state = 'done', file_id = ?2 WHERE id = ?1", (id.to_string(), row.id.clone()), ) .await .map_err(db_err)?; Ok(row) } .await; finish(tx, outcome).await } /// Deletes the upload rows that expired at or before `now`, in one transaction, and returns their /// ids so the caller can remove their staging directories. The rows go in the same transaction that /// reads the ids, so an upload that was extended in between is not removed. pub async fn expire_uploads(&self, now: &str) -> Result> { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result> = async { let ids = fetch_all( &tx, "SELECT id FROM uploads WHERE expires_at <= ?1", (now.to_string(),), |row| col_text(row, 0), ) .await?; tx.execute( "DELETE FROM uploads WHERE expires_at <= ?1", (now.to_string(),), ) .await .map_err(db_err)?; Ok(ids) } .await; finish(tx, outcome).await } } #[cfg(test)] mod tests { use super::*; use crate::store::new_id; use crate::store::test_support::store_with_member; use crate::time::stamp_after; use std::time::Duration; fn new_upload(size: i64) -> NewUpload { NewUpload { id: new_id(), owner: "ann".into(), folder: None, name: "big.bin".into(), size, chunk_size: 8, expires_at: stamp_after(Duration::from_secs(24 * 3600)), } } #[tokio::test] async fn parallel_creates_cannot_together_exceed_the_quota() { let (_dir, store) = store_with_member("ann").await; store.set_quota("ann", 100).await.unwrap(); let (first, second) = tokio::join!( store.create_upload(new_upload(60), 1000), store.create_upload(new_upload(60), 1000), ); let refused: Vec<&Result> = [&first, &second] .into_iter() .filter(|outcome| outcome.is_err()) .collect(); assert_eq!(refused.len(), 1, "exactly one of the two may be accepted"); match refused[0] { Err(Error::Conflict(word)) => assert_eq!(word, "quota_exceeded"), other => panic!("expected quota_exceeded, got {other:?}"), } } }