diff --git a/crates/in-core/src/staging.rs b/crates/in-core/src/staging.rs index 80f4853..bc42998 100644 --- a/crates/in-core/src/staging.rs +++ b/crates/in-core/src/staging.rs @@ -3,6 +3,9 @@ //! //! The finished file is handed to a blob store with `BlobStore::put_file`, which moves it into place. //! A file that is never finished stays in `data_dir/tmp` until the sweeper removes it. +//! +//! Chunks of a resumable upload are staged under `data_dir/uploads//` by the same type, +//! and the chunk math (sizes, counts, validated directories) lives here too. use std::fmt::Display; use std::path::{Path, PathBuf}; @@ -14,9 +17,62 @@ use tokio::io::AsyncWriteExt; use crate::error::{Error, Result}; -/// Name of the staging directory inside the data directory. +/// Name of the staging directory inside the data directory, for whole-file intake. pub const TMP_DIR: &str = "tmp"; +/// Name of the directory inside the data directory that holds the chunks of resumable uploads. Each +/// upload has `uploads//` with one file per chunk, named by its index. +pub const UPLOADS_DIR: &str = "uploads"; + +/// Size of one chunk of a resumable upload: 8 MiB. Every chunk but the last is exactly this long. +pub const CHUNK_BYTES: u64 = 8 * 1024 * 1024; + +/// Number of chunks a file of `size` bytes is split into. A zero-byte file has none. +pub fn chunk_count(size: u64, chunk: u64) -> u64 { + size.div_ceil(chunk.max(1)) +} + +/// The exact length chunk `index` must have, or `None` when the index is past the last chunk. Every +/// chunk but the last is `chunk` bytes; the last is the remainder, which is `chunk` when the size divides +/// evenly. +pub fn expected_chunk_len(size: u64, chunk: u64, index: u64) -> Option { + let count = chunk_count(size, chunk); + if index >= count { + return None; + } + if index + 1 == count { + Some(size - index * chunk) + } else { + Some(chunk) + } +} + +/// The staging directory of an upload: `data_dir/uploads/`. The id must be a lower-case ULID, so +/// this path can never leave the uploads directory. Anything else is `Invalid("bad_id")`. +pub fn upload_dir(data_dir: &Path, id: &str) -> Result { + let well_formed = ulid::Ulid::from_string(id).is_ok() && id == id.to_ascii_lowercase(); + if !well_formed { + return Err(Error::Invalid("bad_id".into())); + } + Ok(data_dir.join(UPLOADS_DIR).join(id)) +} + +/// The file that holds chunk `index` inside an upload's staging directory. +pub fn chunk_path(dir: &Path, index: u64) -> PathBuf { + dir.join(index.to_string()) +} + +/// Removes an upload's staging directory and everything in it. A missing directory is not an error. +/// The path is built by [`upload_dir`], so only a validated upload id is ever removed. +pub async fn remove_upload_dir(data_dir: &Path, id: &str) -> Result<()> { + let dir = upload_dir(data_dir, id)?; + match tokio::fs::remove_dir_all(&dir).await { + Ok(()) => Ok(()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e.into()), + } +} + /// A file being written. Create it with [`StagedFile::create`], feed it with [`StagedFile::write`] or /// [`StagedFile::consume`], then call [`StagedFile::finish`]. pub struct StagedFile { @@ -48,6 +104,13 @@ impl StagedFile { .mode(0o700) .create(&dir) .await?; + Self::create_in(&dir, max_size).await + } + + /// Starts a new staged file inside `dir`, which must exist. The file is created with mode 0600 and + /// a fresh ULID name, so it never replaces anything. The directory is not created: a caller that + /// writes into a removed directory fails instead of recreating it. + pub async fn create_in(dir: &Path, max_size: u64) -> Result { let path = dir.join(ulid::Ulid::generate().to_string()); let file = tokio::fs::OpenOptions::new() .write(true) @@ -124,6 +187,37 @@ mod tests { use super::*; use futures_util::stream; + #[test] + fn chunk_lengths_are_full_then_the_remainder() { + // 10 bytes in 4-byte chunks: 4, 4, 2. Index 3 is past the end. + assert_eq!(chunk_count(10, 4), 3); + assert_eq!(expected_chunk_len(10, 4, 0), Some(4)); + assert_eq!(expected_chunk_len(10, 4, 2), Some(2)); + assert_eq!(expected_chunk_len(10, 4, 3), None); + // An exact multiple has no short last chunk; an empty file has no chunks at all. + assert_eq!(expected_chunk_len(8, 4, 1), Some(4)); + assert_eq!(expected_chunk_len(0, 4, 0), None); + } + + #[test] + fn upload_dirs_only_take_lower_case_ulids() { + let data = Path::new("/data"); + let good = ulid::Ulid::generate().to_string().to_ascii_lowercase(); + assert!( + upload_dir(data, &good) + .unwrap() + .starts_with("/data/uploads") + ); + for bad in [ + "../x", + "", + "01h/../../etc", + &ulid::Ulid::generate().to_string(), + ] { + assert!(upload_dir(data, bad).is_err(), "{bad:?} should be refused"); + } + } + #[tokio::test] async fn streams_hash_and_size_and_refuses_oversize() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/in-core/src/store/files.rs b/crates/in-core/src/store/files.rs index e2799ba..5274db0 100644 --- a/crates/in-core/src/store/files.rs +++ b/crates/in-core/src/store/files.rs @@ -144,6 +144,64 @@ fn like_escape(q: &str) -> String { out } +/// Inserts a file row inside the caller's transaction: the folder must be a live folder of the owner, the +/// size must fit the headroom left after `new.staged_claims`, the name gets the first free postfix, and +/// `used_bytes` is raised by the size. Shared by [`Store::insert_file`] and [`Store::finish_upload`], so +/// the quota rule is written once. +pub(crate) async fn insert_file_in(conn: &Connection, new: NewFile) -> Result { + let base = names::display_name(&new.name); + let blob_key = files_blob_key(&new.id); + let now = now_stamp(); + if let Some(f) = new.folder.as_deref() { + live_folder(conn, &new.owner, f).await?; + } + let (quota, used) = fetch_opt( + conn, + "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 room = quota::headroom(quota, used, new.staged_claims.max(0)); + if !quota::fits(new.size, room) { + return Err(Error::Conflict("quota_exceeded".into())); + } + let name = first_free_name( + conn, + "files", + &new.owner, + new.folder.as_deref(), + &base, + true, + ) + .await?; + conn.execute( + "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", + ( + new.id.clone(), + new.owner.clone(), + new.folder.clone(), + name, + new.mime.clone(), + new.size, + new.sha256.clone(), + blob_key, + now.clone(), + ), + ) + .await + .map_err(|e| insert_err(e, "name_taken"))?; + conn.execute( + "UPDATE members SET used_bytes = used_bytes + ?2 WHERE sub = ?1", + (new.owner.clone(), new.size), + ) + .await + .map_err(db_err)?; + file_by_id(conn, &new.id).await?.ok_or(Error::NotFound) +} + impl Store { /// The file with this id, whoever owns it. Authorise the result before showing it. pub async fn file(&self, id: &str) -> Result> { @@ -158,56 +216,9 @@ impl Store { if new.size < 0 { return Err(Error::Invalid("size_negative".into())); } - let base = names::display_name(&new.name); - let blob_key = files_blob_key(&new.id); - 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 room = quota::headroom(quota, used, new.staged_claims.max(0)); - if !quota::fits(new.size, room) { - return Err(Error::Conflict("quota_exceeded".into())); - } - let name = - first_free_name(&tx, "files", &new.owner, new.folder.as_deref(), &base, true) - .await?; - tx.execute( - "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", - ( - new.id.clone(), - new.owner.clone(), - new.folder.clone(), - name, - new.mime.clone(), - new.size, - new.sha256.clone(), - blob_key, - now.clone(), - ), - ) - .await - .map_err(|e| insert_err(e, "name_taken"))?; - tx.execute( - "UPDATE members SET used_bytes = used_bytes + ?2 WHERE sub = ?1", - (new.owner.clone(), new.size), - ) - .await - .map_err(db_err)?; - file_by_id(&tx, &new.id).await?.ok_or(Error::NotFound) - } - .await; + let outcome = insert_file_in(&tx, new).await; finish(tx, outcome).await } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 3356c4d..d2009c9 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -12,6 +12,7 @@ pub mod sessions; pub mod settings; pub mod snapshot; pub mod trash; +pub mod uploads; use std::path::Path; use std::sync::Arc; diff --git a/crates/in-core/src/store/uploads.rs b/crates/in-core/src/store/uploads.rs new file mode 100644 index 0000000..aa95d02 --- /dev/null +++ b/crates/in-core/src/store/uploads.rs @@ -0,0 +1,306 @@ +//! 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; + +/// 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 { + /// 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 + } + + /// 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")`. + 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 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:?}"), + } + } +} diff --git a/crates/in-web/assets/drive.js b/crates/in-web/assets/drive.js new file mode 100644 index 0000000..2020acd --- /dev/null +++ b/crates/in-web/assets/drive.js @@ -0,0 +1,421 @@ +/* + * drive.js: the upload queue of the drive pages. It is loaded only on those pages, and only does anything + * on a page with a `form[data-upload-form]`. Without it, the upload form posts a whole file the old way. + * + * What it does: + * - Files go to `/api/uploads` in chunks (`api/upload.rs`): create, send each chunk with a PUT, then + * finish. Every request carries the session's CSRF token from the form's `data-csrf`. + * - A chunk that fails with a network error or a server error is retried three times, waiting 0.5 s, + * 1 s and 2 s between tries. A refusal the server gave (a 4xx) is not retried. + * - When a chunk still fails, the upload waits and then asks the server which chunks it has, and sends + * only the missing ones. That is the resume after a network error. It gives up after three rounds. + * - A queue panel shows each file with a progress bar, its state and a cancel button. Cancelling an upload + * that has an id removes it on the server too. + * - Dropping files anywhere on the page offers them to the same queue. + * - When a file finishes, `in:refresh` is dispatched on the document; `nav.js` re-reads the page, so the + * new file appears in the listing. + * + * The labels come from data attributes on the form, so the server translates them. Nothing is inserted as + * HTML: names and messages are set with textContent. The file is one IIFE with no globals. + */ +(function () { + "use strict"; + + if (!window.fetch || !window.FormData || !window.XMLHttpRequest || !window.Blob) { + return; + } + + /** Pauses before the retry of a chunk, in milliseconds. One entry per retry. */ + const BACKOFF_MS = [500, 1000, 2000]; + /** Most rounds of "ask what is there, send what is missing" before an upload gives up. */ + const RESUME_ROUNDS = 3; + /** Pause before a resume round, in milliseconds. */ + const RESUME_PAUSE_MS = 2000; + + /** The uploads waiting for their turn, in the order they were added. */ + const waiting = []; + /** True while one upload runs. Uploads go one at a time, so a slow link is not split between them. */ + let running = false; + /** The queue panel, created on first use and kept outside `
`, so a page refresh does not drop it. */ + let panel = null; + /** How many dragged-in events are still open. The overlay goes when it reaches zero. */ + let dragDepth = 0; + /** The drop overlay, created on first use. */ + let overlay = null; + + /** A refusal or failure of an API call. `status` is the HTTP status, `word` the server's fixed word. */ + class ApiError extends Error { + constructor(status, word) { + super(word); + this.status = status; + this.word = word; + } + + /** A 4xx is the server's answer and repeating it will not change it. */ + get retryable() { + return this.status === 0 || this.status >= 500; + } + } + + /** The form the drop and the picker use: the first upload form of the page, if there is one. */ + function uploadForm() { + return document.querySelector("form[data-upload-form]"); + } + + /** Reads the labels, the folder and the CSRF token of a form now, so a later page refresh cannot change them. */ + function settingsOf(form) { + return { + csrf: form.dataset.csrf || "", + folder: form.dataset.folder || "", + labels: { + uploading: form.dataset.labelUploading || "", + done: form.dataset.labelDone || "", + failed: form.dataset.labelFailed || "", + canceled: form.dataset.labelCanceled || "", + cancel: form.dataset.labelCancel || "", + drop: form.dataset.labelDrop || "", + }, + }; + } + + /** Makes a job for one file and puts it in the queue. */ + function enqueue(form, files) { + const settings = settingsOf(form); + for (const file of files) { + const job = { + file, + csrf: settings.csrf, + folder: settings.folder, + labels: settings.labels, + uploadId: "", + state: "waiting", + cancelled: false, + doneBytes: 0, + xhr: null, + row: null, + }; + render(job); + waiting.push(job); + } + pump(); + } + + /** Runs the next waiting upload, then the one after it, until the queue is empty. */ + async function pump() { + if (running) { + return; + } + running = true; + while (waiting.length > 0) { + const job = waiting.shift(); + if (job.state === "waiting") { + await run(job); + } + } + running = false; + } + + /** The whole upload of one file: create, send what is missing, finish. Ends with the job's state set. */ + async function run(job) { + setState(job, "uploading", job.labels.uploading); + try { + const created = await api(job, "POST", "/api/uploads", { + folder_id: job.folder || null, + name: job.file.name, + size: job.file.size, + }); + job.uploadId = created.id; + const chunk = created.chunk_size; + const size = job.file.size; + const count = Math.ceil(size / chunk); + let rounds = 0; + for (;;) { + const status = await api(job, "GET", `/api/uploads/${job.uploadId}`); + const have = new Set(status.received); + job.doneBytes = 0; + const missing = []; + for (let index = 0; index < count; index += 1) { + const length = Math.min(size, (index + 1) * chunk) - index * chunk; + if (have.has(index)) { + job.doneBytes += length; + } else { + missing.push(index); + } + } + setProgress(job, job.doneBytes); + if (missing.length === 0) { + break; + } + rounds += 1; + try { + for (const index of missing) { + await sendChunk(job, index, chunk, size); + } + } catch (error) { + // Only a network error or a server error is worth another round. A refusal of the server is final. + const resumable = + !job.cancelled && + rounds < RESUME_ROUNDS && + (error instanceof TypeError || (error instanceof ApiError && error.retryable)); + if (!resumable) { + throw error; + } + // A network error ends the round. Wait, then ask the server what it has and go on from there. + await delay(RESUME_PAUSE_MS); + } + } + await api(job, "POST", `/api/uploads/${job.uploadId}/finish`); + job.uploadId = ""; + setProgress(job, size); + setState(job, "done", job.labels.done); + job.row.cancel.remove(); + document.dispatchEvent(new CustomEvent("in:refresh")); + } catch (error) { + if (job.cancelled) { + return; + } + const word = error instanceof ApiError ? error.word : "network"; + setState(job, "failed", `${job.labels.failed} (${word})`); + job.row.cancel.remove(); + } + } + + /** Sends one chunk, retrying the retryable failures with the backoff. */ + async function sendChunk(job, index, chunk, size) { + const start = index * chunk; + const blob = job.file.slice(start, Math.min(size, start + chunk)); + for (let attempt = 0; ; attempt += 1) { + try { + await putChunk(job, index, blob); + return; + } catch (error) { + const retryable = + !job.cancelled && (error instanceof TypeError || (error instanceof ApiError && error.retryable)); + if (!retryable || attempt >= BACKOFF_MS.length) { + throw error; + } + await delay(BACKOFF_MS[attempt]); + } + } + } + + /** PUTs one chunk. The progress of the file counts the bytes sent so far, not only whole chunks. */ + function putChunk(job, index, blob) { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + job.xhr = xhr; + xhr.open("PUT", `/api/uploads/${job.uploadId}/${index}`); + xhr.setRequestHeader("X-CSRF-Token", job.csrf); + xhr.setRequestHeader("Content-Type", "application/octet-stream"); + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) { + setProgress(job, job.doneBytes + event.loaded); + } + }; + xhr.onload = () => { + job.xhr = null; + if (xhr.status >= 200 && xhr.status < 300) { + job.doneBytes += blob.size; + setProgress(job, job.doneBytes); + resolve(); + } else { + reject(answerError(xhr.status, xhr.responseText)); + } + }; + xhr.onerror = () => { + job.xhr = null; + reject(new TypeError("network")); + }; + xhr.onabort = () => { + job.xhr = null; + reject(new TypeError("aborted")); + }; + xhr.send(blob); + }); + } + + /** A JSON call to the upload API. A failed status becomes an `ApiError` with the server's word. */ + async function api(job, method, path, body) { + const headers = { "X-CSRF-Token": job.csrf }; + if (body !== undefined) { + headers["Content-Type"] = "application/json"; + } + let response; + try { + response = await fetch(path, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + credentials: "same-origin", + cache: "no-store", + }); + } catch (error) { + throw new TypeError("network"); + } + const text = await response.text(); + if (!response.ok) { + throw answerError(response.status, text); + } + return text ? JSON.parse(text) : {}; + } + + /** The error of a failed answer: its status and the `error` word of its JSON body. */ + function answerError(status, text) { + let word = "server"; + try { + const data = JSON.parse(text); + if (data && typeof data.error === "string") { + word = data.error; + } + } catch (error) { + // Not JSON: the status alone says what happened. + } + return new ApiError(status, word); + } + + /** Stops an upload. A started upload is also removed on the server. */ + function cancel(job) { + if (job.state === "done" || job.state === "failed" || job.state === "canceled") { + return; + } + job.cancelled = true; + if (job.xhr) { + job.xhr.abort(); + } + if (job.uploadId) { + fetch(`/api/uploads/${job.uploadId}`, { + method: "DELETE", + headers: { "X-CSRF-Token": job.csrf }, + credentials: "same-origin", + }).catch(() => {}); + job.uploadId = ""; + } + setState(job, "canceled", job.labels.canceled); + job.row.cancel.remove(); + } + + /** The queue panel, made on first use and appended to the body. */ + function queuePanel() { + if (!panel) { + panel = document.createElement("section"); + panel.className = "upload-queue"; + panel.setAttribute("aria-live", "polite"); + const list = document.createElement("ul"); + list.className = "upload-list"; + panel.append(list); + document.body.append(panel); + } + return panel.querySelector(".upload-list"); + } + + /** Adds the queue row of a job: name, progress, state and cancel. */ + function render(job) { + const item = document.createElement("li"); + item.className = "upload-item"; + const name = document.createElement("span"); + name.className = "upload-name"; + name.textContent = job.file.name; + const bar = document.createElement("progress"); + bar.max = Math.max(job.file.size, 1); + bar.value = 0; + const status = document.createElement("span"); + status.className = "upload-status"; + status.textContent = job.labels.uploading; + const cancelButton = document.createElement("button"); + cancelButton.type = "button"; + cancelButton.className = "button ghost"; + cancelButton.textContent = job.labels.cancel; + cancelButton.addEventListener("click", () => cancel(job)); + item.append(name, bar, status, cancelButton); + queuePanel().append(item); + job.row = { item, bar, status, cancel: cancelButton }; + } + + /** Sets the state word of a job and the matching `data-state` of its row. */ + function setState(job, state, text) { + job.state = state; + job.row.item.dataset.state = state; + job.row.status.textContent = text; + } + + /** Moves the progress bar of a job. */ + function setProgress(job, bytes) { + job.row.bar.value = Math.min(bytes, job.row.bar.max); + } + + /** Resolves after `ms` milliseconds. */ + function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); + } + + /** Whether a drag carries files, as opposed to text or a link. */ + function carriesFiles(event) { + const types = event.dataTransfer && event.dataTransfer.types; + return !!types && Array.prototype.indexOf.call(types, "Files") !== -1; + } + + /** Shows or hides the drop overlay. Its text is the form's drop label. */ + function showOverlay(show, form) { + if (!overlay) { + overlay = document.createElement("div"); + overlay.className = "drop-overlay"; + overlay.setAttribute("aria-hidden", "true"); + document.body.append(overlay); + } + if (show && form) { + overlay.textContent = form.dataset.labelDrop || ""; + } + overlay.classList.toggle("drop-overlay-show", show); + } + + document.addEventListener("submit", (event) => { + const form = event.target; + if (!(form instanceof HTMLFormElement) || !form.matches("form[data-upload-form]")) { + return; + } + const input = form.querySelector("input[type=file]"); + const files = input && input.files ? Array.from(input.files) : []; + if (files.length === 0) { + return; + } + event.preventDefault(); + enqueue(form, files); + input.value = ""; + }); + + document.addEventListener("dragenter", (event) => { + if (!uploadForm() || !carriesFiles(event)) { + return; + } + event.preventDefault(); + dragDepth += 1; + showOverlay(true, uploadForm()); + }); + + document.addEventListener("dragover", (event) => { + if (uploadForm() && carriesFiles(event)) { + event.preventDefault(); + } + }); + + document.addEventListener("dragleave", () => { + if (!uploadForm()) { + return; + } + dragDepth = Math.max(0, dragDepth - 1); + if (dragDepth === 0) { + showOverlay(false, null); + } + }); + + document.addEventListener("drop", (event) => { + dragDepth = 0; + showOverlay(false, null); + const form = uploadForm(); + if (!form || !event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) { + return; + } + event.preventDefault(); + enqueue(form, Array.from(event.dataTransfer.files)); + }); +})(); diff --git a/crates/in-web/assets/nav.js b/crates/in-web/assets/nav.js index 0eaddc3..a7cee1d 100644 --- a/crates/in-web/assets/nav.js +++ b/crates/in-web/assets/nav.js @@ -224,6 +224,10 @@ }, REFRESH_DEBOUNCE_MS); } + // drive.js dispatches `in:refresh` when an upload finishes. The page re-reads itself, as it does on a + // `changed` event from the server, so the new file shows up in the listing. + document.addEventListener("in:refresh", () => scheduleRefresh()); + // --------------------------------------------------------------------------------------------- // Form fields and focus, kept across a live refresh. diff --git a/crates/in-web/build.rs b/crates/in-web/build.rs index eda65c8..59b5d02 100644 --- a/crates/in-web/build.rs +++ b/crates/in-web/build.rs @@ -1,6 +1,6 @@ //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it //! emits the build identity and the content hashes that the page links use as cache-busting -//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V` and `IN_BUILD_SHA`. +//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V` and `IN_BUILD_SHA`. //! //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles @@ -45,6 +45,7 @@ fn main() { for (var, file) in [ ("IN_NAV_JS_V", "assets/nav.js"), ("IN_PAGES_JS_V", "assets/pages.js"), + ("IN_DRIVE_JS_V", "assets/drive.js"), ] { let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); println!("cargo:rustc-env={var}={}", content_version(&bytes)); diff --git a/crates/in-web/src/api/mod.rs b/crates/in-web/src/api/mod.rs new file mode 100644 index 0000000..f2339b6 --- /dev/null +++ b/crates/in-web/src/api/mod.rs @@ -0,0 +1,4 @@ +//! The JSON APIs of the app: the chunked upload (`upload.rs`, architecture 4.2). The machine object API +//! comes later (contracts.md 5). Every route here answers JSON, including its refusals, and never +//! redirects to sign-in: a script that lost its session gets `401`. +pub mod upload; diff --git a/crates/in-web/src/api/upload.rs b/crates/in-web/src/api/upload.rs new file mode 100644 index 0000000..e3d3748 --- /dev/null +++ b/crates/in-web/src/api/upload.rs @@ -0,0 +1,717 @@ +//! The chunked upload API (architecture 4.2). A file is sent in chunks of 8 MiB, each to its own URL, and +//! the server joins them when the client finishes. Every route needs the session cookie and the +//! `X-CSRF-Token` header; a missing or wrong token is `403`, a missing session is `401`, both as JSON. +//! +//! The routes: +//! - `POST /api/uploads` `{folder_id?, name, size}` starts an upload → `201 {id, chunk_size}`. The size is +//! reserved against the quota in the same transaction that creates the row, so two creates cannot +//! together promise more than the headroom. +//! - `GET /api/uploads/{id}` → `{id, state, size, chunk_size, received}`, where `received` lists the chunk +//! indexes on disk. A client that lost its connection asks this, then sends only what is missing. +//! - `PUT /api/uploads/{id}/{index}` sends one chunk as the raw body. The index must be a chunk of the +//! upload, and the body must be exactly the length that chunk has: `chunk_size` for every chunk but the +//! last, which is the remainder. A longer body is `413` and a shorter one `400`; the bytes are read with a +//! hard limit, so a client cannot make the server store more than the declared size. Sending a chunk that +//! is already there replaces it with the same bytes. +//! - `POST /api/uploads/{id}/finish` joins the chunks into a blob, inserts the file row and marks the upload +//! done → `{file_id}`. Missing chunks are `409` with their indexes. The quota is checked again in the +//! insert transaction, against the other open uploads. +//! - `DELETE /api/uploads/{id}` cancels an open upload and removes its staging directory. +//! +//! An upload that is not finished within 24 hours of its last chunk expires; the sweeper removes it. +//! Another member's upload id is `404`, the same as a missing one. + +use std::path::Path; + +use futures_util::StreamExt; +use http::header::{CACHE_CONTROL, CONTENT_TYPE}; +use http::{HeaderValue, StatusCode}; +use in_core::error::Error as CoreError; +use in_core::names::upload_name; +use in_core::sniff::sniff; +use in_core::staging::{ + CHUNK_BYTES, Staged, StagedFile, chunk_count, chunk_path, expected_chunk_len, + remove_upload_dir, upload_dir, +}; +use in_core::store::files::{NewFile, files_blob_key}; +use in_core::store::new_id; +use in_core::store::uploads::{NewUpload, Upload}; +use in_core::time::{now_stamp, stamp_after}; +use serde::Deserialize; +use serde_json::{Value, json}; +use tokio::io::AsyncReadExt; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::request::headers; +use topcoat::router::response::Response; +use topcoat::router::{Body, path_param_segment, route, to_bytes}; + +use crate::auth::{Viewer, csrf_matches, current_member}; +use crate::pages::drive::{changed, optional_folder}; +use crate::state::AppState; + +/// The header that carries the session's CSRF token. +const CSRF_HEADER: &str = "x-csrf-token"; + +/// How long an open upload may wait for its next chunk: 24 hours. Every chunk restarts the count. +pub const UPLOAD_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60); + +/// The default largest upload: 50 GiB. The `max_upload_bytes` setting overrides it. +pub const DEFAULT_MAX_UPLOAD: u64 = 50 * 1024 * 1024 * 1024; + +/// The settings key of the largest upload, in bytes. +pub const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; + +/// Largest body the create route reads. Its JSON is a few hundred bytes. +const CREATE_BODY_LIMIT: usize = 4096; + +/// How many bytes a chunk is copied with when the chunks are joined. +const COPY_BUFFER: usize = 64 * 1024; + +/// How many leading bytes of the file the sniffer reads. +const SNIFF_BYTES: usize = 8192; + +/// A refused call: the status and the fixed word the client gets as `{"error": word}`. +#[derive(Debug, Clone, Copy)] +struct Refusal { + status: StatusCode, + word: &'static str, +} + +impl Refusal { + /// The JSON answer of this refusal. + fn answer(self) -> Response { + json_answer(self.status, json!({ "error": self.word })) + } +} + +/// Shorthand for a [`Refusal`]. +const fn refuse(status: StatusCode, word: &'static str) -> Refusal { + Refusal { status, word } +} + +/// A JSON response with the given status. Upload answers are never cached. +fn json_answer(status: StatusCode, value: Value) -> Response { + let body = serde_json::to_vec(&value).unwrap_or_default(); + http::Response::builder() + .status(status) + .header(CONTENT_TYPE, HeaderValue::from_static("application/json")) + .header(CACHE_CONTROL, HeaderValue::from_static("no-store")) + .body(Body::from(body)) + .unwrap_or_else(|_| http::Response::new(Body::empty())) +} + +/// The signed-in viewer, when the request carries the session cookie and a matching CSRF header. The +/// outer `Result` is a server failure; the inner one is the refusal to send. +async fn api_viewer(cx: &Cx) -> Result> { + let Some(viewer) = current_member(cx).await? else { + return Ok(Err(refuse(StatusCode::UNAUTHORIZED, "signed_out"))); + }; + let submitted = headers(cx) + .get(CSRF_HEADER) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !csrf_matches(&viewer.session, submitted) { + return Ok(Err(refuse(StatusCode::FORBIDDEN, "csrf"))); + } + Ok(Ok(viewer)) +} + +/// The viewer's upload by id, which must still be open. Another member's or a missing id is `404`; an +/// upload that already finished or was cancelled is `409`; one past its expiry is `410`. +async fn open_upload( + state: &AppState, + viewer: &Viewer, + id: &str, +) -> Result> { + let Some(upload) = state.store.upload(&viewer.member.sub, id).await? else { + return Ok(Err(refuse(StatusCode::NOT_FOUND, "not_found"))); + }; + if upload.state != "active" { + return Ok(Err(refuse(StatusCode::CONFLICT, "not_active"))); + } + if !upload.is_open(&now_stamp()) { + return Ok(Err(refuse(StatusCode::GONE, "expired"))); + } + Ok(Ok(upload)) +} + +/// The largest upload the settings allow, in bytes. A stored value that is not a number is ignored. +pub async fn max_upload_bytes(state: &AppState) -> Result { + let limit = state + .store + .get_setting(MAX_UPLOAD_SETTING) + .await? + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(DEFAULT_MAX_UPLOAD) + .clamp(1, i64::MAX as u64); + Ok(i64::try_from(limit).unwrap_or(i64::MAX)) +} + +/// The indexes of the chunks that are on disk. A missing directory has none. +async fn received_chunks(dir: &Path) -> Result> { + let mut found = Vec::new(); + let mut entries = match tokio::fs::read_dir(dir).await { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(found), + Err(error) => return Err(CoreError::from(error).into()), + }; + while let Some(entry) = entries.next_entry().await.map_err(CoreError::from)? { + // Chunk files are named by their index. Temporary files have ULID names, which never parse. + if let Some(index) = entry + .file_name() + .to_str() + .and_then(|n| n.parse::().ok()) + { + found.push(index); + } + } + found.sort_unstable(); + Ok(found) +} + +/// The body of `POST /api/uploads`. +#[derive(Debug, Deserialize)] +struct CreateRequest { + /// Destination folder, or absent for the top level. + #[serde(default)] + folder_id: Option, + /// The file name as the client has it. It is cleaned, not refused. + name: String, + /// Declared size in bytes. + size: u64, +} + +/// `POST /api/uploads`: starts an upload. +#[route(POST "/api/uploads")] +async fn create_upload(cx: &Cx, body: Body) -> Result { + let state = app_context::(cx); + let viewer = match api_viewer(cx).await? { + Ok(viewer) => viewer, + Err(refusal) => return Ok(refusal.answer()), + }; + let Ok(bytes) = to_bytes(body, CREATE_BODY_LIMIT).await else { + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); + }; + let Ok(request) = serde_json::from_slice::(&bytes) else { + return Ok(refuse(StatusCode::BAD_REQUEST, "bad_request").answer()); + }; + let Ok(size) = i64::try_from(request.size) else { + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); + }; + let folder = + optional_folder(state, &viewer, request.folder_id.as_deref().unwrap_or("")).await?; + let max = max_upload_bytes(state).await?; + let id = new_id(); + let new = NewUpload { + id: id.clone(), + owner: viewer.member.sub.clone(), + folder, + name: upload_name(&request.name), + size, + chunk_size: i64::try_from(CHUNK_BYTES).unwrap_or(i64::MAX), + expires_at: stamp_after(UPLOAD_TTL), + }; + let upload = match state.store.create_upload(new, max).await { + Ok(upload) => upload, + Err(CoreError::Invalid(word)) if word == "too_large" => { + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "too_large").answer()); + } + Err(CoreError::Conflict(word)) if word == "quota_exceeded" => { + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()); + } + Err(error) => return Err(error.into()), + }; + // The directory is made after the row commits. A crash in between leaves a row with no directory, which + // the sweeper expires; the other order could leave a directory no row names. + let dir = upload_dir(&state.config.data_dir, &upload.id)?; + tokio::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&dir) + .await + .map_err(CoreError::from)?; + Ok(json_answer( + StatusCode::CREATED, + json!({ "id": upload.id, "chunk_size": CHUNK_BYTES }), + )) +} + +/// `GET /api/uploads/{id}`: the state of an upload and the chunks it has. +#[route(GET "/api/uploads/{id}")] +async fn upload_status(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = match api_viewer(cx).await? { + Ok(viewer) => viewer, + Err(refusal) => return Ok(refusal.answer()), + }; + let id = path_param_segment(cx, "id").to_owned(); + let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); + }; + let dir = upload_dir(&state.config.data_dir, &upload.id)?; + let received = received_chunks(&dir).await?; + let word = if upload.state == "active" && !upload.is_open(&now_stamp()) { + "expired" + } else { + upload.state.as_str() + }; + Ok(json_answer( + StatusCode::OK, + json!({ + "id": upload.id, + "state": word, + "size": upload.size, + "chunk_size": upload.chunk_size, + "received": received, + }), + )) +} + +/// `PUT /api/uploads/{id}/{index}`: stores one chunk. +#[route(PUT "/api/uploads/{id}/{index}")] +async fn put_chunk(cx: &Cx, body: Body) -> Result { + let state = app_context::(cx); + let viewer = match api_viewer(cx).await? { + Ok(viewer) => viewer, + Err(refusal) => return Ok(refusal.answer()), + }; + let id = path_param_segment(cx, "id").to_owned(); + let raw_index = path_param_segment(cx, "index").to_owned(); + let upload = match open_upload(state, &viewer, &id).await? { + Ok(upload) => upload, + Err(refusal) => return Ok(refusal.answer()), + }; + let Ok(index) = raw_index.parse::() else { + return Ok(refuse(StatusCode::BAD_REQUEST, "bad_index").answer()); + }; + let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); + let Some(expected) = expected_chunk_len(size, chunk, index) else { + return Ok(refuse(StatusCode::BAD_REQUEST, "index_out_of_range").answer()); + }; + let dir = upload_dir(&state.config.data_dir, &upload.id)?; + // The bytes go to a temporary file in the staging directory, which is then renamed onto the index. A + // reader sees either the old chunk or the new one, never a partial write. + let mut staged = match StagedFile::create_in(&dir, expected).await { + Ok(staged) => staged, + Err(CoreError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); + } + Err(error) => return Err(error.into()), + }; + let mut frames = body.into_data_stream(); + let mut received: u64 = 0; + while let Some(frame) = frames.next().await { + let Ok(bytes) = frame else { + staged.abort().await; + return Ok(refuse(StatusCode::BAD_REQUEST, "body_read").answer()); + }; + let len = bytes.len() as u64; + if received + len > expected { + staged.abort().await; + return Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "chunk_too_large").answer()); + } + if let Err(error) = staged.write(&bytes).await { + staged.abort().await; + return Err(error.into()); + } + received += len; + } + if received != expected { + staged.abort().await; + return Ok(refuse(StatusCode::BAD_REQUEST, "chunk_length").answer()); + } + let Staged { path, .. } = staged.finish().await?; + let target = chunk_path(&dir, index); + if let Err(error) = tokio::fs::rename(&path, &target).await { + let _ = tokio::fs::remove_file(&path).await; + return Err(CoreError::from(error).into()); + } + // The rename is durable only once the directory entry is: fsync the directory, as the blob store does. + tokio::fs::File::open(&dir) + .await + .map_err(CoreError::from)? + .sync_all() + .await + .map_err(CoreError::from)?; + if !state + .store + .touch_upload(&viewer.member.sub, &upload.id, &stamp_after(UPLOAD_TTL)) + .await? + { + // The upload was finished or cancelled after the check above. Its directory is removed by that + // request or by the sweeper, so this chunk does not outlive it. + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); + } + Ok(json_answer(StatusCode::OK, json!({ "index": index }))) +} + +/// Joins the chunks of `dir` into `staged`, in index order, and keeps the first bytes for the sniffer. +async fn join_chunks( + dir: &Path, + count: u64, + staged: &mut StagedFile, + prefix: &mut Vec, +) -> std::result::Result<(), CoreError> { + let mut buffer = vec![0u8; COPY_BUFFER]; + for index in 0..count { + let mut part = tokio::fs::File::open(chunk_path(dir, index)).await?; + loop { + let read = part.read(&mut buffer).await?; + if read == 0 { + break; + } + if prefix.len() < SNIFF_BYTES { + let take = (SNIFF_BYTES - prefix.len()).min(read); + prefix.extend_from_slice(&buffer[..take]); + } + staged.write(&buffer[..read]).await?; + } + } + Ok(()) +} + +/// `POST /api/uploads/{id}/finish`: joins the chunks into the file. +#[route(POST "/api/uploads/{id}/finish")] +async fn finish_upload(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = match api_viewer(cx).await? { + Ok(viewer) => viewer, + Err(refusal) => return Ok(refusal.answer()), + }; + let id = path_param_segment(cx, "id").to_owned(); + let upload = match open_upload(state, &viewer, &id).await? { + Ok(upload) => upload, + Err(refusal) => return Ok(refusal.answer()), + }; + let data_dir = state.config.data_dir.clone(); + let dir = upload_dir(&data_dir, &upload.id)?; + let (size, chunk) = (upload.size as u64, upload.chunk_size as u64); + let count = chunk_count(size, chunk); + let received = received_chunks(&dir).await?; + let missing: Vec = (0..count) + .filter(|index| received.binary_search(index).is_err()) + .collect(); + if !missing.is_empty() { + return Ok(json_answer( + StatusCode::CONFLICT, + json!({ "error": "chunks_missing", "missing": missing }), + )); + } + + let mut staged = StagedFile::create(&data_dir, size).await?; + let mut prefix = Vec::with_capacity(SNIFF_BYTES); + if let Err(error) = join_chunks(&dir, count, &mut staged, &mut prefix).await { + staged.abort().await; + return Err(error.into()); + } + let Staged { path, sha256, .. } = staged.finish().await?; + + // The bytes are durable at their key before the row that names them commits (architecture 3). + let file_id = new_id(); + let key = files_blob_key(&file_id); + if let Err(error) = state.blobs.put_file(&key, &path).await { + let _ = tokio::fs::remove_file(&path).await; + return Err(error.into()); + } + let new = NewFile { + id: file_id, + owner: viewer.member.sub.clone(), + folder: upload.folder_id.clone(), + name: upload.name.clone(), + mime: sniff(&prefix), + size: upload.size, + sha256, + staged_claims: 0, + }; + match state + .store + .finish_upload(&viewer.member.sub, &upload.id, new) + .await + { + Ok(file) => { + if let Err(error) = remove_upload_dir(&data_dir, &upload.id).await { + tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); + } + changed(state, &viewer.member.sub); + Ok(json_answer(StatusCode::OK, json!({ "file_id": file.id }))) + } + Err(error) => { + // No row names these bytes now, so they go. + let _ = state.blobs.delete(&key).await; + match error { + CoreError::Conflict(word) if word == "quota_exceeded" => { + Ok(refuse(StatusCode::PAYLOAD_TOO_LARGE, "quota_exceeded").answer()) + } + CoreError::Conflict(word) if word == "upload_not_active" => { + Ok(refuse(StatusCode::CONFLICT, "not_active").answer()) + } + CoreError::Invalid(word) if word == "size_mismatch" => { + Ok(refuse(StatusCode::CONFLICT, "size_mismatch").answer()) + } + CoreError::NotFound => Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()), + other => Err(other.into()), + } + } + } +} + +/// `DELETE /api/uploads/{id}`: cancels an open upload and removes what it staged. +#[route(DELETE "/api/uploads/{id}")] +async fn cancel_upload(cx: &Cx) -> Result { + let state = app_context::(cx); + let viewer = match api_viewer(cx).await? { + Ok(viewer) => viewer, + Err(refusal) => return Ok(refusal.answer()), + }; + let id = path_param_segment(cx, "id").to_owned(); + let Some(upload) = state.store.upload(&viewer.member.sub, &id).await? else { + return Ok(refuse(StatusCode::NOT_FOUND, "not_found").answer()); + }; + if !state + .store + .abort_upload(&viewer.member.sub, &upload.id) + .await? + { + return Ok(refuse(StatusCode::CONFLICT, "not_active").answer()); + } + if let Err(error) = remove_upload_dir(&state.config.data_dir, &upload.id).await { + tracing::warn!(upload = %upload.id, error = %error, "upload: staging directory not removed"); + } + Ok(json_answer(StatusCode::OK, json!({ "state": "aborted" }))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::SESSION_COOKIE; + use crate::auth::test_support::signed_in; + use crate::boot::{router, test_state}; + use http::Request; + use http::header::COOKIE; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use topcoat::router::{Body, to_bytes}; + + /// One call to the API as the session `token`, with the CSRF header `csrf` when given. Returns the + /// status and the JSON body. + async fn call( + state: &AppState, + method: &str, + path: &str, + token: &str, + csrf: Option<&str>, + body: Vec, + ) -> (StatusCode, Value) { + let mut request = Request::builder() + .method(method) + .uri(path) + .header(COOKIE, format!("{SESSION_COOKIE}={token}")); + if let Some(csrf) = csrf { + request = request.header(CSRF_HEADER, csrf); + } + let request = request.body(Body::from(body)).expect("request"); + let response = router(state.clone()).handle(request).await; + let status = response.status(); + let bytes = to_bytes(response.into_body(), 64 * 1024) + .await + .expect("body"); + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) + } + + /// Starts an upload of `size` bytes as `ann`, and returns its id. + async fn start(state: &AppState, token: &str, size: u64) -> String { + let body = json!({ "name": "clip.bin", "size": size }).to_string(); + let (status, value) = call( + state, + "POST", + "/api/uploads", + token, + Some("csrf-ann"), + body.into_bytes(), + ) + .await; + assert_eq!(status, StatusCode::CREATED); + value["id"].as_str().expect("an id").to_owned() + } + + #[tokio::test] + async fn chunk_bounds_are_enforced() { + let (_dir, state) = test_state().await; + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let id = start(&state, &token, 10).await; + let put = |index: u64| format!("/api/uploads/{id}/{index}"); + + // One chunk of ten bytes: index 1 does not exist. + let (status, value) = call( + &state, + "PUT", + &put(1), + &token, + Some("csrf-ann"), + vec![0; 10], + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(value["error"], "index_out_of_range"); + + // The last chunk must be exactly the remainder: longer is refused as too large, shorter as bad. + let (status, value) = call( + &state, + "PUT", + &put(0), + &token, + Some("csrf-ann"), + vec![0; 11], + ) + .await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(value["error"], "chunk_too_large"); + let (status, value) = + call(&state, "PUT", &put(0), &token, Some("csrf-ann"), vec![0; 9]).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(value["error"], "chunk_length"); + } + + #[tokio::test] + async fn a_whole_upload_becomes_a_file_that_can_be_downloaded() { + let (_dir, state) = test_state().await; + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let id = start(&state, &token, 10).await; + let (status, _) = call( + &state, + "PUT", + &format!("/api/uploads/{id}/0"), + &token, + Some("csrf-ann"), + b"0123456789".to_vec(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, value) = call( + &state, + "POST", + &format!("/api/uploads/{id}/finish"), + &token, + Some("csrf-ann"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + let file_id = value["file_id"].as_str().expect("a file id").to_owned(); + + let request = Request::get(format!("/file/{file_id}?dl=1")) + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) + .body(Body::empty()) + .expect("request"); + let response = router(state.clone()).handle(request).await; + assert_eq!(response.status(), StatusCode::OK); + let bytes = to_bytes(response.into_body(), 64 * 1024) + .await + .expect("body"); + assert_eq!(&bytes[..], b"0123456789"); + } + + #[tokio::test] + async fn finishing_with_a_missing_chunk_is_a_conflict() { + let (_dir, state) = test_state().await; + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + // Two chunks: the first is 8 MiB, so the test sends only the one-byte last chunk. + let id = start(&state, &token, CHUNK_BYTES + 1).await; + let (status, _) = call( + &state, + "PUT", + &format!("/api/uploads/{id}/1"), + &token, + Some("csrf-ann"), + vec![7], + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, value) = call( + &state, + "POST", + &format!("/api/uploads/{id}/finish"), + &token, + Some("csrf-ann"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + assert_eq!(value["error"], "chunks_missing"); + assert_eq!(value["missing"], json!([0])); + } + + #[tokio::test] + async fn another_members_upload_is_not_found_and_a_bad_csrf_token_is_forbidden() { + let (_dir, state) = test_state().await; + let ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; + let id = start(&state, &ann, 10).await; + + let (status, _) = call( + &state, + "GET", + &format!("/api/uploads/{id}"), + &bob, + Some("csrf-bob"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = call( + &state, + "PUT", + &format!("/api/uploads/{id}/0"), + &bob, + Some("csrf-bob"), + vec![0; 10], + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = call( + &state, + "POST", + &format!("/api/uploads/{id}/finish"), + &bob, + Some("csrf-bob"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _) = call( + &state, + "DELETE", + &format!("/api/uploads/{id}"), + &bob, + Some("csrf-bob"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let (status, value) = call( + &state, + "GET", + &format!("/api/uploads/{id}"), + &ann, + Some("csrf-wrong"), + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(value["error"], "csrf"); + let (status, _) = call( + &state, + "GET", + &format!("/api/uploads/{id}"), + &ann, + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + } +} diff --git a/crates/in-web/src/assets.rs b/crates/in-web/src/assets.rs index 2584c3f..ed911c1 100644 --- a/crates/in-web/src/assets.rs +++ b/crates/in-web/src/assets.rs @@ -18,9 +18,13 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IN_NAV_JS_V")); /// Link to the script of individual pages. pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); +/// Link to the upload queue of the drive pages. Only those pages load it. +pub const DRIVE_JS_HREF: &str = concat!("/assets/drive.js?v=", env!("IN_DRIVE_JS_V")); + const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); const NAV_JS: &str = include_str!("../assets/nav.js"); const PAGES_JS: &str = include_str!("../assets/pages.js"); +const DRIVE_JS: &str = include_str!("../assets/drive.js"); const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); const SW_JS: &str = include_str!("../assets/sw.js"); @@ -59,6 +63,12 @@ async fn pages_js() -> Result { Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, PAGES_JS)) } +/// `GET /assets/drive.js`. +#[route(GET "/assets/drive.js")] +async fn drive_js() -> Result { + Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, DRIVE_JS)) +} + /// `GET /assets/offline.html`. Also precached by the service worker. #[route(GET "/assets/offline.html")] async fn offline_html() -> Result { diff --git a/crates/in-web/src/auth.rs b/crates/in-web/src/auth.rs index 909bd04..ebcc43e 100644 --- a/crates/in-web/src/auth.rs +++ b/crates/in-web/src/auth.rs @@ -227,3 +227,54 @@ mod tests { assert_eq!(safe_next(&format!("{longest}a")), None); } } + +/// Helpers for the in-process router tests: a member with a live session. +#[cfg(test)] +pub(crate) mod test_support { + use super::*; + use in_core::quota::DEFAULT_MEMBER_QUOTA; + use in_core::store::members::MemberFields; + use in_core::store::new_id; + use in_core::store::sessions::NewSession; + use in_core::time::stamp_after; + use in_core::token::{generate_token, hash_token}; + + /// Makes `sub` a member with `quota` bytes and a live session. Returns the session cookie value; the + /// session's CSRF token is `csrf-`. + pub async fn signed_in(state: &AppState, sub: &str, quota: i64) -> String { + state + .store + .upsert_member_from_claims( + &MemberFields { + sub: sub.into(), + email: format!("{sub}@example.test"), + name: sub.into(), + is_admin: false, + locale: "en".into(), + zoneinfo: "UTC".into(), + picture_version: 0, + im_updated_at: String::new(), + }, + DEFAULT_MEMBER_QUOTA, + ) + .await + .expect("member"); + state.store.set_quota(sub, quota).await.expect("quota"); + let token = generate_token(); + state + .store + .create_session(NewSession { + sub: sub.into(), + token_hash: hash_token(&token), + csrf_token: format!("csrf-{sub}"), + im_sid: format!("im-{sub}-{}", new_id()), + expires_at: stamp_after(SESSION_TTL), + ip: None, + user_agent: None, + id_token_sealed: None, + }) + .await + .expect("session"); + token + } +} diff --git a/crates/in-web/src/boot.rs b/crates/in-web/src/boot.rs index f6200ff..b287de9 100644 --- a/crates/in-web/src/boot.rs +++ b/crates/in-web/src/boot.rs @@ -30,6 +30,7 @@ use crate::pages::files; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; use crate::state::AppState; +use crate::sweeper; /// Name of the instance key file inside the data directory. const KEY_FILE: &str = "in.key"; @@ -47,6 +48,7 @@ pub async fn serve(config_path: &Path) -> Result<()> { if state.oidc.is_some() { tokio::spawn(directory::run(state.clone(), stop_rx.clone())); } + tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); let listener = TcpListener::bind(listen).await.map_err(|error| { std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) diff --git a/crates/in-web/src/i18n/drive.rs b/crates/in-web/src/i18n/drive.rs index c054d17..ba12ffc 100644 --- a/crates/in-web/src/i18n/drive.rs +++ b/crates/in-web/src/i18n/drive.rs @@ -80,14 +80,20 @@ pub enum DK { PickHint, /// Cancel a form and go back. Back, - /// Field label: the place the file is in. - Location, /// Field label: the MIME type. MimeType, - /// Field label: when it was uploaded. - Uploaded, - /// Field label: how many times it was downloaded. - Downloads, + /// Drop overlay text on a drive page. + UploadDrop, + /// Queue row: an upload in progress. + UploadUploading, + /// Queue row: an upload that finished. + UploadDone, + /// Queue row: an upload that failed. The server's word follows it. + UploadFailed, + /// Queue row: an upload that was cancelled. + UploadCanceled, + /// Queue row: the button that cancels an upload. + UploadCancel, /// Link to view the bytes in the browser. OpenRaw, /// Accessible name of the breadcrumb trail. @@ -213,14 +219,20 @@ pub fn d(lang: Lang, key: DK) -> &'static str { (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", (DK::Back, Lang::En) => "Back", (DK::Back, Lang::Tr) => "Geri", - (DK::Location, Lang::En) => "Location", - (DK::Location, Lang::Tr) => "Konum", (DK::MimeType, Lang::En) => "Type", (DK::MimeType, Lang::Tr) => "Tür", - (DK::Uploaded, Lang::En) => "Uploaded", - (DK::Uploaded, Lang::Tr) => "Yüklendi", - (DK::Downloads, Lang::En) => "Downloads", - (DK::Downloads, Lang::Tr) => "İndirme", + (DK::UploadDrop, Lang::En) => "Drop files anywhere on this page to upload them.", + (DK::UploadDrop, Lang::Tr) => "Yüklemek için dosyaları bu sayfaya bırakın.", + (DK::UploadUploading, Lang::En) => "Uploading", + (DK::UploadUploading, Lang::Tr) => "Yükleniyor", + (DK::UploadDone, Lang::En) => "Uploaded", + (DK::UploadDone, Lang::Tr) => "Yüklendi", + (DK::UploadFailed, Lang::En) => "Upload failed", + (DK::UploadFailed, Lang::Tr) => "Yükleme başarısız", + (DK::UploadCanceled, Lang::En) => "Cancelled", + (DK::UploadCanceled, Lang::Tr) => "İptal edildi", + (DK::UploadCancel, Lang::En) => "Cancel", + (DK::UploadCancel, Lang::Tr) => "İptal", (DK::OpenRaw, Lang::En) => "Open in the browser", (DK::OpenRaw, Lang::Tr) => "Tarayıcıda aç", (DK::Location2, Lang::En) => "Location", diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index b301206..f23d533 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -4,6 +4,7 @@ //! operator command line, which is not built yet. The configuration file is the `--config` path, //! then `IN_CONFIG`, then `config/in.toml`. Exit status 0 is success, 1 a failure, 2 a usage error. +mod api; mod assets; mod auth; mod boot; @@ -16,6 +17,7 @@ mod pages; mod security; mod serve_bytes; mod state; +mod sweeper; mod views; use std::path::{Path, PathBuf}; diff --git a/crates/in-web/src/pages/drive.rs b/crates/in-web/src/pages/drive.rs index efeab45..dca4b76 100644 --- a/crates/in-web/src/pages/drive.rs +++ b/crates/in-web/src/pages/drive.rs @@ -1,6 +1,7 @@ -//! The drive's listing pages: the root (`/`), a folder (`/f/{id}`), search (`/search`), the live stream -//! that refreshes an open listing, the folder writes (create, rename, move, trash) and the folder move -//! picker. The file pages live in `files.rs`, the trash in `trash.rs`. +//! The drive's listing pages: the root (`/drive`, which also answers search with `?q=`), a folder +//! (`/drive/{folder_id}`), the live stream that refreshes an open listing, the folder writes (create, +//! rename, move, trash) and the folder move picker. The file bytes live in `files.rs`, the viewer in +//! `view.rs`, the trash in `trash.rs`. //! //! Authorization: each item is loaded by id and passed to `authz::authorize`. A refusal to see the item //! is `404`, so a foreign or missing id looks the same as no item at all. A refusal to change an item the @@ -38,6 +39,9 @@ use crate::views::{ViewerInfo, empty_state, shell}; /// How many search hits each kind shows. const SEARCH_LIMIT: usize = 100; +/// The drive's root listing. `/` sends a signed-in person here, and forms return here by default. +pub const DRIVE_HOME: &str = "/drive"; + /// The query of a listing page. Every field is optional; unknown ones are ignored. #[derive(Debug, Default, Deserialize)] #[serde(default)] @@ -46,7 +50,7 @@ pub struct ListQuery { pub sort: String, /// `asc` (default) or `desc`. pub dir: String, - /// The search text, on `/search` only. + /// The search text, on `/drive` only. pub q: String, /// A notice word from a finished action. pub notice: String, @@ -305,11 +309,15 @@ pub async fn folder_board( let descending = query.dir == "desc"; sort_listing(&mut listing, sort, descending); let (base, live, back) = match folder.as_deref() { - None => ("/?".to_owned(), "/live/drive".to_owned(), "/".to_owned()), + None => ( + format!("{DRIVE_HOME}?"), + "/live/drive".to_owned(), + DRIVE_HOME.to_owned(), + ), Some(id) => ( - format!("/f/{id}?"), + format!("/drive/{id}?"), format!("/live/drive?folder={id}"), - format!("/f/{id}"), + format!("/drive/{id}"), ), }; Ok(Board { @@ -356,24 +364,14 @@ pub async fn search_board( sort, descending, csrf: viewer.session.csrf_token.clone(), - back: format!("/search?q={enc}"), + back: format!("{DRIVE_HOME}?q={enc}"), notice: query.notice.clone(), refusal: query.refusal.clone(), live: None, - base: format!("/search?q={enc}&"), + base: format!("{DRIVE_HOME}?q={enc}&"), }) } -/// The drive root's listing for a signed-in viewer. The start page uses it. -pub async fn root_board( - state: &AppState, - viewer: &Viewer, - query: &ListQuery, - lang: Lang, -) -> Result { - folder_board(state, viewer, None, query, lang).await -} - /// The main content of a listing page: the heading, the trail, the flash line, the forms that create /// and upload, and the table. Used by the drive pages and by the start page for a signed-in viewer. #[component] @@ -390,7 +388,7 @@ pub async fn drive_board(lang: Lang, board: &Board) -> Result { } flash(lang: lang, notice: board.notice.as_str(), refusal: board.refusal.as_str())
-