From 5346e822a5234e2e6aaa558b4d8711562d3d173d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 28 Oct 2026 11:04:39 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20attachment=20storage=20in?= =?UTF-8?q?=20in:=20object=20client,=20mover=20with=20migration=20both=20w?= =?UTF-8?q?ays,=20proxied=20reads,=20idempotent=20deletes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/iz.example.toml | 4 +- .../0005_blob_deletions_by_place.sql | 17 + crates/iz-core/src/config.rs | 30 +- crates/iz-core/src/store/attachments.rs | 175 ++++++- crates/iz-core/src/store/migrate.rs | 4 + crates/iz-core/src/store/mod.rs | 2 +- crates/iz-web/src/attachments.rs | 169 +++++- crates/iz-web/src/boot.rs | 14 + crates/iz-web/src/family.rs | 2 + crates/iz-web/src/i18n/shell.rs | 12 + crates/iz-web/src/i18n/structure.rs | 35 ++ crates/iz-web/src/in_store.rs | 493 ++++++++++++++++++ crates/iz-web/src/main.rs | 2 + crates/iz-web/src/mover.rs | 418 +++++++++++++++ crates/iz-web/src/oidc.rs | 26 +- crates/iz-web/src/pages/admin.rs | 1 + crates/iz-web/src/pages/files.rs | 55 +- crates/iz-web/src/pages/settings.rs | 84 ++- crates/iz-web/src/serve.rs | 325 +++++++++--- crates/iz-web/src/state.rs | 7 + crates/iz-web/src/sweeper.rs | 42 +- crates/iz-web/src/views/admin.rs | 5 +- crates/iz-web/src/views/structure.rs | 68 +++ 23 files changed, 1835 insertions(+), 155 deletions(-) create mode 100644 crates/iz-core/migrations/0005_blob_deletions_by_place.sql create mode 100644 crates/iz-web/src/in_store.rs create mode 100644 crates/iz-web/src/mover.rs diff --git a/config/iz.example.toml b/config/iz.example.toml index 203f89b..9b2e39e 100644 --- a/config/iz.example.toml +++ b/config/iz.example.toml @@ -19,9 +19,11 @@ trusted_proxies = [] # client_id = "iz" # client_secret_file = "data/oidc_client_secret" -# Attachments in the external Files service instead of local disk. +# The external Files service (`in`) that may hold attachments. The storage choice is made in /settings. +# It needs sign-in (the [oidc] section), because `in` is reached with a token from `im`. [in_store] enabled = false +# url = "https://in.example.com" # Scheduled backups. Uncomment to enable. # [backup] diff --git a/crates/iz-core/migrations/0005_blob_deletions_by_place.sql b/crates/iz-core/migrations/0005_blob_deletions_by_place.sql new file mode 100644 index 0000000..8be595b --- /dev/null +++ b/crates/iz-core/migrations/0005_blob_deletions_by_place.sql @@ -0,0 +1,17 @@ +-- 0005: a deletion records the copy it still owes per place, so a row that was moving can owe bytes in both +-- places. The key becomes (attachment_id, location). Rows of 0003 carry over unchanged. A record's location +-- says which copy the deleter removes: 'local' is a file under data_dir/attachments, 'in' is an object at +-- the Files service. +CREATE TABLE blob_deletions_by_place ( + attachment_id TEXT NOT NULL CHECK (length(attachment_id) = 26), + location TEXT NOT NULL CHECK (location IN ('local', 'in')), + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0), + next_attempt_at TEXT NOT NULL, + created_at TEXT NOT NULL, + PRIMARY KEY (attachment_id, location) +); +INSERT INTO blob_deletions_by_place (attachment_id, location, attempts, next_attempt_at, created_at) + SELECT attachment_id, location, attempts, next_attempt_at, created_at FROM blob_deletions; +DROP TABLE blob_deletions; +ALTER TABLE blob_deletions_by_place RENAME TO blob_deletions; +CREATE INDEX blob_deletions_due ON blob_deletions(next_attempt_at); diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index f1db72b..19212b1 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -56,13 +56,18 @@ pub struct OidcConfig { pub client_secret_file: PathBuf, } -/// Switch for storing attachments in the external Files service. +/// The external Files service (`in`) that may hold attachments. The storage choice itself is the admin's +/// setting; this section says whether `in` may be chosen at all and where it is. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields)] pub struct InStoreConfig { - /// Whether the Files service is enabled. Defaults to off. + /// Whether the Files service may be used for attachments. Defaults to off. #[serde(default)] pub enabled: bool, + /// Public origin of `in`, for example `https://in.example.com`. No trailing slash. Required when + /// `enabled` is set. Must be https, or http on loopback. + #[serde(default)] + pub url: Option, } /// Scheduled backup policy. @@ -182,6 +187,12 @@ impl Config { )); } } + if self.in_store.enabled { + let url = self.in_store.url.as_deref().ok_or_else(|| { + Error::Config("in_store.url is required when in_store.enabled is set".into()) + })?; + validate_in_url(url)?; + } if let Some(backup) = &self.backup { if backup.dir.as_os_str().is_empty() { return Err(Error::Config("backup.dir must not be empty".into())); @@ -206,6 +217,21 @@ impl Config { } } +/// The origin of `in` must be https, or http on loopback, with no trailing slash. +fn validate_in_url(url: &str) -> Result<()> { + if url.ends_with('/') { + return Err(Error::Config("in_store.url must not end with /".into())); + } + let loopback = url.starts_with("http://127.0.0.1") || url.starts_with("http://localhost"); + if url.starts_with("https://") || loopback { + Ok(()) + } else { + Err(Error::Config( + "in_store.url must be an https URL (http only for loopback)".into(), + )) + } +} + /// An issuer must be https. Plain http is allowed only for loopback, which is how a local /// identity provider is reached in development. fn validate_issuer(issuer: &str) -> Result<()> { diff --git a/crates/iz-core/src/store/attachments.rs b/crates/iz-core/src/store/attachments.rs index 5e0e374..964b3e2 100644 --- a/crates/iz-core/src/store/attachments.rs +++ b/crates/iz-core/src/store/attachments.rs @@ -25,6 +25,14 @@ use std::time::Duration; pub const SETTING_LIMIT_MIB: &str = "attachment_limit_mib"; /// The setting that holds the allowed extensions, separated by spaces or commas. pub const SETTING_EXTENSIONS: &str = "attachment_extensions"; +/// The setting that holds where new and existing attachments belong: `local` (default) or `in`. +pub const SETTING_LOCATION: &str = "attachment_location"; +/// Where the bytes of an attachment are, as its row says: this disk, the Files service, or in between. +pub const LOCATION_LOCAL: &str = "local"; +/// See [`LOCATION_LOCAL`]. +pub const LOCATION_IN: &str = "in"; +/// A move between the two places is under way. Only the mover sets and clears it. +pub const LOCATION_MOVING: &str = "moving"; /// The extensions allowed when the setting is unset. Reason: office documents, images, audio, video, text. pub const DEFAULT_EXTENSIONS: &[&str] = &[ "pdf", "png", "jpg", "jpeg", "gif", "webp", "heic", "txt", "md", "csv", "xlsx", "ods", "pptx", @@ -61,6 +69,8 @@ pub struct Attachment { pub uploaded_by: String, /// UTC stamp of the upload. pub created_at: String, + /// Where the bytes are: `local`, `in` or `moving` (see [`LOCATION_LOCAL`]). + pub location: String, } /// What an upload stores. The task and the board are given separately, by the caller's checks. @@ -82,7 +92,7 @@ pub struct NewAttachment { /// Columns of an attachment, prefixed for the joins that filter by task. const ATTACHMENT_COLS: &str = - "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at"; + "a.id, a.task_id, a.name, a.mime, a.size, a.sha256, a.uploaded_by, a.created_at, a.location"; fn map_attachment(row: &turso::Row) -> Result { Ok(Attachment { @@ -94,6 +104,7 @@ fn map_attachment(row: &turso::Row) -> Result { sha256: col_text(row, 5)?, uploaded_by: col_text(row, 6)?, created_at: col_text(row, 7)?, + location: col_text(row, 8)?, }) } @@ -187,6 +198,7 @@ impl Store { sha256: new.sha256.clone(), uploaded_by: new.uploaded_by.clone(), created_at: created_at.clone(), + location: LOCATION_LOCAL.to_owned(), }; let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; @@ -324,13 +336,21 @@ impl Store { ) .await .map_err(db_err)?; - tx.execute( - "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ - VALUES (?1, 'local', 0, ?2, ?3)", - (attachment_id.to_owned(), now.clone(), now), - ) - .await - .map_err(db_err)?; + // A moving row may have a copy in each place, so both are owed. A settled row has one copy. + let owed: &[&str] = match current.location.as_str() { + LOCATION_LOCAL => &[LOCATION_LOCAL], + LOCATION_IN => &[LOCATION_IN], + _ => &[LOCATION_LOCAL, LOCATION_IN], + }; + for place in owed { + tx.execute( + "INSERT INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ + VALUES (?1, ?2, 0, ?3, ?4)", + (attachment_id.to_owned(), (*place).to_owned(), now.clone(), now.clone()), + ) + .await + .map_err(db_err)?; + } activity::record( &tx, NewActivity { @@ -348,25 +368,26 @@ impl Store { finish(tx, outcome).await } - /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, attempts so far)`. - pub async fn due_blob_deletions(&self, limit: i64) -> Result> { + /// Bytes owed to deletion whose next attempt is due, oldest first: `(attachment id, location, attempts so + /// far)`. The location names the copy to remove: `local` or `in`. + pub async fn due_blob_deletions(&self, limit: i64) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, - "SELECT attachment_id, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \ - ORDER BY next_attempt_at, attachment_id LIMIT ?2", + "SELECT attachment_id, location, attempts FROM blob_deletions WHERE next_attempt_at <= ?1 \ + ORDER BY next_attempt_at, attachment_id, location LIMIT ?2", (now_stamp(), limit), - |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + |row| Ok((col_text(row, 0)?, col_text(row, 1)?, col_int(row, 2)?)), ) .await } /// Clears a deletion once its bytes are confirmed gone. - pub async fn finish_blob_deletion(&self, attachment_id: &str) -> Result<()> { + pub async fn finish_blob_deletion(&self, attachment_id: &str, location: &str) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( - "DELETE FROM blob_deletions WHERE attachment_id = ?1", - (attachment_id.to_owned(),), + "DELETE FROM blob_deletions WHERE attachment_id = ?1 AND location = ?2", + (attachment_id.to_owned(), location.to_owned()), ) .await .map_err(db_err)?; @@ -377,18 +398,136 @@ impl Store { pub async fn defer_blob_deletion( &self, attachment_id: &str, + location: &str, attempts: i64, delay: Duration, ) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( - "UPDATE blob_deletions SET attempts = ?2, next_attempt_at = ?3 WHERE attachment_id = ?1", - (attachment_id.to_owned(), attempts + 1, stamp_after(delay)), + "UPDATE blob_deletions SET attempts = ?3, next_attempt_at = ?4 \ + WHERE attachment_id = ?1 AND location = ?2", + ( + attachment_id.to_owned(), + location.to_owned(), + attempts + 1, + stamp_after(delay), + ), ) .await .map_err(db_err)?; Ok(()) } + + /// Sets the next attempt of a deletion `delay` from now, without counting a failure (the copy is busy, + /// not broken). + pub async fn postpone_blob_deletion( + &self, + attachment_id: &str, + location: &str, + delay: Duration, + ) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "UPDATE blob_deletions SET next_attempt_at = ?3 WHERE attachment_id = ?1 AND location = ?2", + (attachment_id.to_owned(), location.to_owned(), stamp_after(delay)), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Owes the deleter a copy of attachment `attachment_id` in `location`. Recording it twice is harmless. + pub async fn owe_blob_deletion(&self, attachment_id: &str, location: &str) -> Result<()> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT OR IGNORE INTO blob_deletions (attachment_id, location, attempts, next_attempt_at, created_at) \ + VALUES (?1, ?2, 0, ?3, ?3)", + (attachment_id.to_owned(), location.to_owned(), now), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// The location of an attachment row, or `None` when the row is gone. Used by the mover and the deleter, + /// which work on ids and need no task. + pub async fn attachment_location(&self, attachment_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT location FROM attachments WHERE id = ?1", + (attachment_id.to_owned(),), + |row| col_text(row, 0), + ) + .await + } + + /// Rows in `location`, oldest first: the candidates the mover picks from. + pub async fn attachments_in_location( + &self, + location: &str, + limit: i64, + ) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {ATTACHMENT_COLS} FROM attachments a WHERE a.location = ?1 \ + ORDER BY a.created_at, a.id LIMIT ?2" + ), + (location.to_owned(), limit), + map_attachment, + ) + .await + } + + /// Moves a row from `from` to `to` only if it is still in `from`. `true` when this call did it. The mover + /// claims a row this way (`from` to `moving`) and settles it the same way, so two movers never pick the + /// same row, and a row deleted meanwhile is simply not found. + pub async fn set_location_if(&self, attachment_id: &str, from: &str, to: &str) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn + .execute( + "UPDATE attachments SET location = ?3 WHERE id = ?1 AND location = ?2", + (attachment_id.to_owned(), from.to_owned(), to.to_owned()), + ) + .await + .map_err(db_err)?; + Ok(changed > 0) + } + + /// The ids of rows left in `moving` by a crash. Read once at boot. + pub async fn moving_attachment_ids(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT id FROM attachments WHERE location = 'moving'", + (), + |row| col_text(row, 0), + ) + .await + } + + /// How many rows are in each location, as `(location, count)`. Shows the progress of a migration. + pub async fn attachment_location_counts(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT location, COUNT(*) FROM attachments GROUP BY location", + (), + |row| Ok((col_text(row, 0)?, col_int(row, 1)?)), + ) + .await + } + + /// Where attachments belong: the `attachment_location` setting, `local` when unset or unknown. + pub async fn attachment_target(&self) -> Result { + Ok(match self.get_setting(SETTING_LOCATION).await?.as_deref() { + Some(LOCATION_IN) => LOCATION_IN.to_owned(), + _ => LOCATION_LOCAL.to_owned(), + }) + } } /// A live attachment of a live task of `board_id`, read on the writer so it is part of the transaction. diff --git a/crates/iz-core/src/store/migrate.rs b/crates/iz-core/src/store/migrate.rs index 908c6ed..c3660d3 100644 --- a/crates/iz-core/src/store/migrate.rs +++ b/crates/iz-core/src/store/migrate.rs @@ -16,6 +16,10 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ ), (3, include_str!("../../migrations/0003_blob_deletions.sql")), (4, include_str!("../../migrations/0004_mail_events.sql")), + ( + 5, + include_str!("../../migrations/0005_blob_deletions_by_place.sql"), + ), ]; fn migration_err(e: turso::Error) -> Error { diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 5da4c14..c64f555 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -403,7 +403,7 @@ mod tests { }) .await .unwrap(); - assert_eq!(versions, vec![1, 2, 3, 4]); + assert_eq!(versions, vec![1, 2, 3, 4, 5]); } #[tokio::test] diff --git a/crates/iz-web/src/attachments.rs b/crates/iz-web/src/attachments.rs index 6f900c6..5aa3c0e 100644 --- a/crates/iz-web/src/attachments.rs +++ b/crates/iz-web/src/attachments.rs @@ -1,14 +1,23 @@ -//! The attachments' disk work that runs outside a request: the deleter. A deleted attachment's row is gone at -//! once (the transaction in `iz-core` records the bytes in `blob_deletions`); this worker removes the bytes -//! afterwards and retries with a backoff until they are gone, then clears the record. It runs until the stop -//! flag is set, like every worker (`docs/architecture.md` section 8). +//! The deleter: the attachments' disk and Files-service work that runs outside a request. A deleted +//! attachment's row is gone at once (the transaction in `iz-core` records the copies it owes in +//! `blob_deletions`, one record per place); this worker removes them and retries with a backoff until they are +//! gone, then clears the record. It runs until the stop flag is set, like every worker +//! (`docs/architecture.md` section 8). //! -//! The bytes are only ever removed through `iz_core::staging::remove_blob`, which builds the path from the -//! validated attachment id. +//! The rules that keep a live copy safe are the same ones the mover follows (`mover.rs`). Every step that +//! touches a copy, or the row that says where the bytes are, holds `AppState::blob_lock`. Under that lock, a +//! record is judged against the row as it is then: +//! - the row is `moving`: a move is under way, so the record waits; +//! - the row is in the record's own place: the record is stale, and the copy is the live one, so nothing is removed; +//! - the row is gone, or is in the other place: the owed copy is removed. +//! +//! Local copies are removed only through `iz_core::staging::remove_blob`, which builds the path from the validated +//! attachment id. Files-service copies are removed with `DELETE`, which counts a missing object as done. use std::time::Duration; use iz_core::staging::remove_blob; +use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING}; use tokio::sync::watch; use crate::state::AppState; @@ -22,7 +31,7 @@ const SWEEP_EVERY: Duration = Duration::from_secs(5); const SWEEP_BATCH: i64 = 50; /// The first retry delay, in seconds. Doubles with each failed attempt. const RETRY_BASE_SECS: u64 = 5; -/// The longest retry delay, in seconds. Reason: a file that cannot be removed is looked at every ten minutes. +/// The longest retry delay, in seconds. Reason: a copy that cannot be removed is looked at every ten minutes. const RETRY_CAP_SECS: u64 = 600; /// The delay before the next attempt after `attempts` failures. @@ -45,8 +54,19 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver) { }); } -/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. -async fn sweep(state: &AppState) { +/// What one owed copy came to on this pass. +enum Step { + /// The copy is gone, or was never needed. The record is cleared. + Done, + /// A move is under way for this row. Looked at again soon, without a failed attempt counted. + Later, + /// The removal failed. The record is retried with the backoff. + Failed(String), +} + +/// One pass over the due deletions. A failure is logged and retried later; it never stops the worker. Also +/// run by the sweeper as a backstop. +pub async fn sweep(state: &AppState) { let due = match state.store.due_blob_deletions(SWEEP_BATCH).await { Ok(due) => due, Err(error) => { @@ -54,18 +74,37 @@ async fn sweep(state: &AppState) { return; } }; - for (id, attempts) in due { - match remove_blob(&state.config.data_dir, &id).await { - Ok(()) => { - if let Err(error) = state.store.finish_blob_deletion(&id).await { + // Once a Files-service call fails, the rest of this pass leaves the Files copies for the next one: each call + // may wait for the connection, and the blob lock is held meanwhile. + let mut files_down = false; + for (id, location, attempts) in due { + if files_down && location == LOCATION_IN { + continue; + } + let step = remove_owed(state, &id, &location).await; + if matches!(step, Step::Failed(_)) && location == LOCATION_IN { + files_down = true; + } + match step { + Step::Done => { + if let Err(error) = state.store.finish_blob_deletion(&id, &location).await { tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); } } - Err(error) => { - tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); + Step::Later => { if let Err(error) = state .store - .defer_blob_deletion(&id, attempts, retry_delay(attempts)) + .postpone_blob_deletion(&id, &location, Duration::from_secs(RETRY_BASE_SECS)) + .await + { + tracing::warn!(error = %error, "postponing an attachment deletion failed"); + } + } + Step::Failed(reason) => { + tracing::warn!(attempts, location = %location, reason, "removing an attachment copy failed; retrying"); + if let Err(error) = state + .store + .defer_blob_deletion(&id, &location, attempts, retry_delay(attempts)) .await { tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); @@ -75,6 +114,36 @@ async fn sweep(state: &AppState) { } } +/// Removes one owed copy, judged against the row under the blob lock (see the module comment). +async fn remove_owed(state: &AppState, id: &str, location: &str) -> Step { + let _guard = state.blob_lock.lock().await; + let here = match state.store.attachment_location(id).await { + Ok(here) => here, + Err(error) => return Step::Failed(error.to_string()), + }; + match here.as_deref() { + Some(LOCATION_MOVING) => return Step::Later, + Some(current) if current == location => return Step::Done, + _ => {} + } + if location == LOCATION_LOCAL { + return match remove_blob(&state.config.data_dir, id).await { + Ok(()) => Step::Done, + Err(error) => Step::Failed(error.to_string()), + }; + } + if location != LOCATION_IN { + return Step::Failed(format!("unknown location {location}")); + } + let Some(in_store) = state.in_store.as_ref() else { + return Step::Failed("the Files service is not configured".into()); + }; + match in_store.delete(id).await { + Ok(()) => Step::Done, + Err(error) => Step::Failed(error.to_string()), + } +} + #[cfg(test)] mod tests { use super::*; @@ -88,3 +157,71 @@ mod tests { assert_eq!(retry_delay(-3), Duration::from_secs(5)); } } + +#[cfg(test)] +mod delete_tests { + use std::sync::Arc; + + use iz_core::authz::{Actor, Role}; + use iz_core::staging::blob_path; + use iz_core::store::attachments::{LOCATION_IN, LOCATION_LOCAL}; + + use super::*; + use crate::boot::test_state; + use crate::in_store::InStore; + use crate::in_store::test_support::{fake_in, reply, seed_attachment}; + + /// A DELETE that the Files service answers `404` for is already done: the record is cleared, not retried. + #[tokio::test] + async fn a_404_at_the_files_service_counts_as_deleted() { + let (_dir, mut state) = test_state().await; + let base = fake_in(|req| { + if req.method == "DELETE" { + reply(404, b"{}") + } else { + reply(405, b"") + } + }) + .await; + state.in_store = Some(Arc::new(InStore::for_tests(&base))); + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; + // The row has moved: its bytes are at the Files service and the local copy is gone. + assert!( + state + .store + .set_location_if(&row.id, LOCATION_LOCAL, LOCATION_IN) + .await + .expect("move") + ); + std::fs::remove_file(blob_path(&state.config.data_dir, &row.id).expect("path")) + .expect("local copy removed"); + let board = state.store.ensure_board("IZ").await.expect("board"); + let uploader = Actor::Member { + sub: "bo".into(), + role: Role::Member, + im_admin: false, + disabled: false, + }; + state + .store + .delete_attachment(&board.id, &row.id, &uploader) + .await + .expect("delete"); + assert_eq!( + state.store.due_blob_deletions(10).await.expect("due").len(), + 1 + ); + + sweep(&state).await; + + assert!( + state + .store + .due_blob_deletions(10) + .await + .expect("due") + .is_empty(), + "a 404 counts as deleted" + ); + } +} diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index 63a6ff3..ff5ccf8 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -20,7 +20,9 @@ use topcoat::router::{BodyLimit, Router, RouterBuilderDiscoverExt, RouterService use crate::attachments; use crate::directory; +use crate::in_store::InStore; use crate::live::LiveHub; +use crate::mover; use crate::oidc; use crate::pages::not_found::NotFoundLayer; use crate::security::{self, SecurityHeaders}; @@ -55,6 +57,7 @@ pub async fn serve(config_path: &Path) -> iz_core::Result<()> { let (stop_tx, stop_rx) = watch::channel(false); directory::spawn(state.clone(), stop_rx.clone()); attachments::spawn(state.clone(), stop_rx.clone()); + mover::spawn(state.clone(), stop_rx.clone()); crate::mail::spawn(state.clone(), stop_rx.clone()); crate::family::spawn(state.clone(), stop_rx.clone()); crate::backup::spawn(state.clone(), stop_rx.clone()); @@ -104,6 +107,13 @@ async fn open_state(config: Config) -> iz_core::Result { } None => None, }; + let in_store = match (&config.in_store, &oidc) { + (in_config, Some(client)) if in_config.enabled => match &in_config.url { + Some(url) => Some(Arc::new(InStore::new(url, client.clone())?)), + None => None, + }, + _ => None, + }; Ok(AppState { config: Arc::new(config), store, @@ -111,6 +121,8 @@ async fn open_state(config: Config) -> iz_core::Result { live: Arc::new(LiveHub::default()), oidc, family: Arc::default(), + in_store, + blob_lock: Arc::default(), }) } @@ -188,6 +200,8 @@ mod tests { live: Arc::new(LiveHub::default()), oidc: None, family: Arc::default(), + in_store: None, + blob_lock: Arc::default(), }; (dir, state) } diff --git a/crates/iz-web/src/family.rs b/crates/iz-web/src/family.rs index 5be58c3..e960d3a 100644 --- a/crates/iz-web/src/family.rs +++ b/crates/iz-web/src/family.rs @@ -235,6 +235,8 @@ mod tests { live: std::sync::Arc::default(), oidc: None, family: std::sync::Arc::default(), + in_store: None, + blob_lock: std::sync::Arc::default(), }; let request = http::Request::get("/no/such/page") .header(http::header::ACCEPT, "text/html") diff --git a/crates/iz-web/src/i18n/shell.rs b/crates/iz-web/src/i18n/shell.rs index 4421b23..f92ce1f 100644 --- a/crates/iz-web/src/i18n/shell.rs +++ b/crates/iz-web/src/i18n/shell.rs @@ -28,6 +28,10 @@ pub enum K { SignInUnavailableTitle, /// The sentence under that title. SignInUnavailableBody, + /// The title of the page that says a file cannot be sent right now. + FilesUnavailableTitle, + /// The sentence under that title. + FilesUnavailableBody, /// The title of the 404 page. NotFoundTitle, /// The sentence on the signed-out start page. @@ -68,6 +72,14 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::SignInUnavailableBody, Lang::Tr) => { "Hesap servisine şu anda ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." } + (K::FilesUnavailableTitle, Lang::En) => "The file cannot be opened right now", + (K::FilesUnavailableTitle, Lang::Tr) => "Dosya şu an açılamıyor", + (K::FilesUnavailableBody, Lang::En) => { + "The file is kept in the Files service, which cannot be reached right now. Try again in a few minutes." + } + (K::FilesUnavailableBody, Lang::Tr) => { + "Bu dosya dış dosya hizmetinde saklanıyor ve şu anda o hizmete ulaşılamıyor. Birkaç dakika sonra tekrar deneyin." + } (K::NoAccessTitle, Lang::En) => "No access to this board", (K::NoAccessTitle, Lang::Tr) => "Bu panoya erişiminiz yok", (K::NoAccessBody, Lang::En) => { diff --git a/crates/iz-web/src/i18n/structure.rs b/crates/iz-web/src/i18n/structure.rs index db8ab2a..b5fd652 100644 --- a/crates/iz-web/src/i18n/structure.rs +++ b/crates/iz-web/src/i18n/structure.rs @@ -120,6 +120,15 @@ pub enum K { LimitExtensions, /// Button that saves the limits. LimitsSave, + StorageHeading, + StorageHelp, + StorageCounts, + StorageMigrating, + StorageLocalOption, + StorageInOption, + StorageInUnavailable, + StorageSave, + NoticeStorageSaved, /// Settings section: server information. ServerHeading, /// Help text of the server section. @@ -304,6 +313,32 @@ pub fn t(lang: Lang, key: K) -> &'static str { (K::LimitMib, Tr) => "Ek boyutu sınırı (MiB)", (K::LimitExtensions, En) => "Allowed extensions", (K::LimitExtensions, Tr) => "İzin verilen uzantılar", + (K::StorageHeading, En) => "Attachment storage", + (K::StorageHeading, Tr) => "Ek depolama", + (K::StorageHelp, En) => { + "New attachments are written here first. With the Files service chosen, they move there in the background; with this server chosen, they move back. A move resumes after a restart." + } + (K::StorageHelp, Tr) => { + "Yeni ekler önce burada yazılır. Dosya hizmeti seçiliyse arka planda oraya taşınır; bu sunucu seçiliyse geri taşınır. Taşıma yeniden başlatmadan sonra kaldığı yerden sürer." + } + (K::StorageCounts, En) => "{} on this server, {} in the Files service, {} moving.", + (K::StorageCounts, Tr) => "Bu sunucuda {}, dosya hizmetinde {}, taşınan {}.", + (K::StorageMigrating, En) => "{} files are waiting to move to {}.", + (K::StorageMigrating, Tr) => "{} dosya {} taşınmayı bekliyor.", + (K::StorageLocalOption, En) => "Keep attachments on this server", + (K::StorageLocalOption, Tr) => "Ekleri bu sunucuda tut", + (K::StorageInOption, En) => "Keep attachments in the Files service", + (K::StorageInOption, Tr) => "Ekleri dosya hizmetinde tut", + (K::StorageInUnavailable, En) => { + "The Files service is not set up on this server. It needs [in_store] enabled with a url in the config file, and sign-in with im." + } + (K::StorageInUnavailable, Tr) => { + "Dosya hizmeti bu sunucuda kurulu değil. Yapılandırma dosyasında [in_store] etkin ve bir url ile tanımlanmalı, im ile oturum açılabilmeli." + } + (K::StorageSave, En) => "Save storage", + (K::StorageSave, Tr) => "Depolamayı kaydet", + (K::NoticeStorageSaved, En) => "Attachment storage saved. Files move in the background.", + (K::NoticeStorageSaved, Tr) => "Ek depolama kaydedildi. Dosyalar arka planda taşınır.", (K::LimitsSave, En) => "Save limits", (K::LimitsSave, Tr) => "Sınırları kaydet", (K::ServerHeading, En) => "Server", diff --git a/crates/iz-web/src/in_store.rs b/crates/iz-web/src/in_store.rs new file mode 100644 index 0000000..ff38de3 --- /dev/null +++ b/crates/iz-web/src/in_store.rs @@ -0,0 +1,493 @@ +//! The client of `in`'s object API (contracts.md 5): the attachments that live at the Files service. +//! +//! Every call carries a client-credentials token for `aud = in` and scope `files.service`. It comes from the +//! same `im` client as the sign-in, cached under its own key (`OidcClient::client_token`), so it never +//! replaces the directory token. +//! +//! Two HTTP clients. Uploads and deletes are bounded by [`WRITE_TIMEOUT`] for the whole call. Reads have +//! no whole-call bound, because a large download is streamed and may take longer; they have a stall bound +//! ([`READ_STALL`]) instead. Neither client follows +//! redirects: a redirect would carry the bearer token to another host. +//! +//! The answers are checked here and never trusted blindly. A `PUT` must answer with the size and digest +//! the caller sent; a `GET` must answer the status the range asked for. + +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use bytes::Bytes; +use futures_util::Stream; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, RANGE}; +use serde_json::Value; +use tokio::io::AsyncReadExt; + +use crate::oidc::OidcClient; + +/// The audience of every object call: the family key of `in`. +pub const IN_AUDIENCE: &str = "in"; +/// The scope that stores and reads a family service's own objects at `in`. +pub const FILES_SCOPE: &str = "files.service"; +/// The longest an upload or a delete may take, end to end. Reason: the spec for this client; a slow link +/// retries with backoff instead of holding the mover. +pub const WRITE_TIMEOUT: Duration = Duration::from_secs(60); +/// The longest a connection may take to open. Applies to every call. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +/// The longest a read may stall: between two chunks of a download, or before the answer's first byte. Reason: +/// a download may be long, but a stalled one must not hold a request or the mover forever. +const READ_STALL: Duration = Duration::from_secs(30); +/// Bytes read from a local file per upload frame. +const UPLOAD_FRAME: usize = 64 * 1024; +/// The longest `X-Object-Name` sent, in bytes. `in` refuses longer names. +const NAME_MAX_BYTES: usize = 255; +/// The largest JSON answer of a PUT that is read. +const PUT_ANSWER_MAX: u64 = 4096; + +/// Why a call to `in` did not give its answer. +#[derive(Debug, thiserror::Error)] +pub enum InError { + /// `in` or the token service could not be reached, or did not answer in time. + #[error("the Files service cannot be reached: {0}")] + Unavailable(String), + /// `in` answered with a status that is not a success for this call. + #[error("the Files service answered {0}")] + Refused(u16), + /// `in` answered, but not in the form the contract gives, or with other bytes than were sent. + #[error("the Files service answered in an unexpected way: {0}")] + BadResponse(String), + /// A local file could not be read to be sent. + #[error("a local file could not be read: {0}")] + Local(#[from] std::io::Error), +} + +/// The result of a call to `in`. +pub type InResult = std::result::Result; + +/// What `in` says it stored after a PUT (contracts.md 5). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stored { + /// Length in bytes. + pub size: u64, + /// Lowercase hex SHA-256. + pub sha256: String, +} + +/// Where the bearer token comes from: the `im` client in production. +enum Tokens { + Oidc(Arc), + #[cfg(test)] + Fixed(String), +} + +/// The Files service of this instance: its origin and the way to reach it. +pub struct InStore { + base: String, + write_http: reqwest::Client, + read_http: reqwest::Client, + tokens: Tokens, +} + +impl InStore { + /// Builds the client for the origin `base_url` (no trailing slash), with tokens from `oidc`. + pub fn new(base_url: &str, oidc: Arc) -> iz_core::Result { + Ok(Self { + base: base_url.trim_end_matches('/').to_owned(), + write_http: clients(true)?, + read_http: clients(false)?, + tokens: Tokens::Oidc(oidc), + }) + } + + /// The URL of object `id` at `in`. + fn object_url(&self, id: &str) -> String { + format!("{}/api/v1/objects/{id}", self.base) + } + + /// The bearer token for an object call. + async fn token(&self) -> InResult { + match &self.tokens { + Tokens::Oidc(oidc) => oidc + .client_token(IN_AUDIENCE, FILES_SCOPE) + .await + .map_err(|error| InError::Unavailable(error.to_string())), + #[cfg(test)] + Tokens::Fixed(token) => Ok(token.clone()), + } + } + + /// Stores the file at `path` as object `id`, with the stored `mime` and the display `name`. The file is + /// streamed from disk. The answer must carry the same size and digest the caller sent, or the call fails. + pub async fn put( + &self, + id: &str, + path: &Path, + size: u64, + mime: &str, + name: &str, + sha256: &str, + ) -> InResult { + let token = self.token().await?; + let file = tokio::fs::File::open(path).await?; + let response = self + .write_http + .put(self.object_url(id)) + .bearer_auth(token) + .header(CONTENT_TYPE, mime) + .header(CONTENT_LENGTH, size) + .header("X-Object-Name", encode_name(name)) + .body(reqwest::Body::wrap_stream(file_frames(file))) + .send() + .await + .map_err(transport)?; + let status = response.status().as_u16(); + if status != 200 && status != 201 { + return Err(InError::Refused(status)); + } + let text = response.bytes().await.map_err(transport)?; + if u64::try_from(text.len()).unwrap_or(u64::MAX) > PUT_ANSWER_MAX { + return Err(InError::BadResponse("the PUT answer is too large".into())); + } + let answer: Value = serde_json::from_slice(&text) + .map_err(|error| InError::BadResponse(format!("the PUT answer: {error}")))?; + let stored = Stored { + size: answer + .get("size") + .and_then(Value::as_u64) + .unwrap_or(u64::MAX), + sha256: answer + .get("sha256") + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned(), + }; + if stored.size != size || stored.sha256 != sha256 { + return Err(InError::BadResponse( + "the stored size or digest is not the one sent".into(), + )); + } + Ok(stored) + } + + /// Reads object `id`, or the bytes of `range` (`first` and `last`, both inclusive) when one is given. The + /// response is returned unread: the caller streams it. Only `200` (whole) or `206` (range) are accepted. + pub async fn get(&self, id: &str, range: Option<(u64, u64)>) -> InResult { + let token = self.token().await?; + let mut request = self.read_http.get(self.object_url(id)).bearer_auth(token); + if let Some((first, last)) = range { + request = request.header(RANGE, format!("bytes={first}-{last}")); + } + let response = request.send().await.map_err(transport)?; + let status = response.status().as_u16(); + if status == 200 || status == 206 { + Ok(response) + } else { + Err(InError::Refused(status)) + } + } + + /// Deletes object `id`. An object that is already gone counts as deleted (contracts.md 5). + pub async fn delete(&self, id: &str) -> InResult<()> { + let token = self.token().await?; + let response = self + .write_http + .delete(self.object_url(id)) + .bearer_auth(token) + .send() + .await + .map_err(transport)?; + let status = response.status().as_u16(); + if (200..300).contains(&status) || status == 404 { + Ok(()) + } else { + Err(InError::Refused(status)) + } + } +} + +/// A client with the bounds of its kind: writes have the whole-call timeout, reads only the connect bound. +fn clients(write: bool) -> iz_core::Result { + let mut builder = reqwest::Client::builder() + .connect_timeout(CONNECT_TIMEOUT) + .read_timeout(READ_STALL) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("iz/", env!("CARGO_PKG_VERSION"))); + if write { + builder = builder.timeout(WRITE_TIMEOUT); + } + builder + .build() + .map_err(|error| iz_core::Error::Config(format!("cannot build the Files client: {error}"))) +} + +/// A connection-level failure as an [`InError`]. +fn transport(error: reqwest::Error) -> InError { + InError::Unavailable(error.to_string()) +} + +/// The file as a stream of frames, read in [`UPLOAD_FRAME`] pieces, so a large upload is never held whole. +fn file_frames( + file: tokio::fs::File, +) -> impl Stream> + Send + 'static { + futures_util::stream::try_unfold(file, |mut file| async move { + let mut buf = vec![0u8; UPLOAD_FRAME]; + let read = file.read(&mut buf).await?; + if read == 0 { + return Ok(None); + } + buf.truncate(read); + Ok(Some((Bytes::from(buf), file))) + }) +} + +/// The `X-Object-Name` value: the name cut to [`NAME_MAX_BYTES`] at a character boundary, then percent-encoded +/// as UTF-8 (every byte outside the unreserved set is escaped, so `+` and `%` cannot be misread). +pub fn encode_name(name: &str) -> String { + let mut end = name.len().min(NAME_MAX_BYTES); + while !name.is_char_boundary(end) { + end -= 1; + } + let mut out = String::with_capacity(end); + for &byte in &name.as_bytes()[..end] { + if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { + out.push(char::from(byte)); + } else { + out.push_str(&format!("%{byte:02X}")); + } + } + out +} + +#[cfg(test)] +impl InStore { + /// A client for `base` with a fixed token, for the tests that run a fake `in`. + pub fn for_tests(base: &str) -> Self { + Self { + base: base.trim_end_matches('/').to_owned(), + write_http: clients(true).expect("client"), + read_http: clients(false).expect("client"), + tokens: Tokens::Fixed("test-token".into()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_escaped_and_cut_to_the_limit() { + assert_eq!(encode_name("a b+c.pdf"), "a%20b%2Bc.pdf"); + assert_eq!(encode_name("ü.txt"), "%C3%BC.txt"); + let long = "é".repeat(200); + assert!(encode_name(&long).len() <= NAME_MAX_BYTES * 3); + let plain = "x".repeat(300); + assert_eq!(encode_name(&plain).len(), NAME_MAX_BYTES); + } +} + +/// A fake `in` for the tests: a loopback listener that answers each request with a closure, and a seeder that +/// writes a local attachment through the store's own calls. +#[cfg(test)] +pub(crate) mod test_support { + use std::sync::Arc; + + use iz_core::authz::Role; + use iz_core::staging::blob_path; + use iz_core::store::attachments::{Attachment, NewAttachment, new_attachment_id}; + use iz_core::store::members::DirectoryMember; + use iz_core::store::tasks::NewTask; + use sha2::{Digest, Sha256}; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio::net::{TcpListener, TcpStream}; + + use crate::state::AppState; + + /// A request the fake received. + #[derive(Debug, Clone)] + pub struct Req { + /// The method, as sent. + pub method: String, + /// The headers, names as sent. + pub headers: Vec<(String, String)>, + /// The body, cut to its `Content-Length`. + pub body: Vec, + } + + impl Req { + /// The first value of a header, compared without regard to case. + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + } + } + + /// The fake's answer: status, extra headers, and the body. + #[derive(Debug, Clone)] + pub struct Reply { + /// The status code. + pub status: u16, + /// Extra headers, sent as given. `Content-Length` is added by the fake. + pub headers: Vec<(String, String)>, + /// The body. + pub body: Vec, + } + + /// An answer with `status` and `body` and no extra headers. + pub fn reply(status: u16, body: &[u8]) -> Reply { + Reply { + status, + headers: Vec::new(), + body: body.to_vec(), + } + } + + /// Starts a fake `in` on a free loopback port, answering each request with `handler`. Returns its origin. + pub async fn fake_in(handler: impl Fn(&Req) -> Reply + Send + Sync + 'static) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("address"); + let handler = Arc::new(handler); + tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + let handler = handler.clone(); + tokio::spawn(answer(socket, handler)); + } + }); + format!("http://{addr}") + } + + /// Reads one request from `socket`, answers it, and closes the connection. + async fn answer(mut socket: TcpStream, handler: Arc Reply + Send + Sync>) { + let Some(request) = read_request(&mut socket).await else { + return; + }; + let reply = handler(&request); + let mut head = format!( + "HTTP/1.1 {} Test\r\nContent-Length: {}\r\nConnection: close\r\n", + reply.status, + reply.body.len() + ); + for (name, value) in &reply.headers { + head.push_str(&format!("{name}: {value}\r\n")); + } + head.push_str("\r\n"); + let _ = socket.write_all(head.as_bytes()).await; + let _ = socket.write_all(&reply.body).await; + let _ = socket.shutdown().await; + } + + /// Reads a request head and its `Content-Length` body. + async fn read_request(socket: &mut TcpStream) -> Option { + let mut buf: Vec = Vec::new(); + let head_end = loop { + if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break at + 4; + } + let mut chunk = [0u8; 4096]; + let read = socket.read(&mut chunk).await.ok()?; + if read == 0 { + return None; + } + buf.extend_from_slice(&chunk[..read]); + }; + let head = String::from_utf8_lossy(&buf[..head_end]).into_owned(); + let mut lines = head.split("\r\n"); + let mut parts = lines.next()?.split(' '); + let method = parts.next()?.to_owned(); + let headers: Vec<(String, String)> = lines + .filter_map(|line| line.split_once(':')) + .map(|(name, value)| (name.trim().to_owned(), value.trim().to_owned())) + .collect(); + let length = headers + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .and_then(|(_, value)| value.parse::().ok()) + .unwrap_or(0); + let mut body = buf[head_end..].to_vec(); + while body.len() < length { + let mut chunk = [0u8; 8192]; + let read = socket.read(&mut chunk).await.ok()?; + if read == 0 { + break; + } + body.extend_from_slice(&chunk[..read]); + } + body.truncate(length); + Some(Req { + method, + headers, + body, + }) + } + + /// Seeds two members, a board, a task and one attachment of `bytes` stored locally, all through the store's + /// own calls. The bytes are written where the upload would put them. + pub async fn seed_attachment( + state: &AppState, + name: &str, + mime: &str, + bytes: &[u8], + ) -> Attachment { + let store = &state.store; + for (sub, role) in [("ada", Role::Admin), ("bo", Role::Member)] { + let member = DirectoryMember { + sub: sub.into(), + email: format!("{sub}@example.com"), + name: sub.into(), + im_admin: false, + disabled: false, + locale: None, + zoneinfo: "UTC".into(), + picture_version: 0, + }; + store + .apply_directory_member(&member, role) + .await + .expect("member"); + } + let board = store.ensure_board("IZ").await.expect("board"); + let column = store.columns(&board.id).await.expect("columns")[0] + .id + .clone(); + let tag = store.tags(&board.id).await.expect("tags")[0].id.clone(); + let task = store + .create_task( + &board.id, + NewTask { + title: "Task".into(), + description: String::new(), + column_id: column, + tag_id: tag, + deadline: None, + meeting_at: None, + assignees: Vec::new(), + parent_id: None, + link: None, + }, + "bo", + ) + .await + .expect("task"); + let id = new_attachment_id(); + let path = blob_path(&state.config.data_dir, &id).expect("path"); + std::fs::create_dir_all(path.parent().expect("parent")).expect("attachments dir"); + std::fs::write(&path, bytes).expect("bytes"); + let sha256 = hex::encode(Sha256::digest(bytes)); + store + .add_attachment( + &board.id, + &task.id, + NewAttachment { + id, + name: name.into(), + mime: mime.into(), + size: bytes.len() as u64, + sha256, + uploaded_by: "bo".into(), + }, + ) + .await + .expect("attachment") + } +} diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 3fba85a..024c594 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -17,8 +17,10 @@ mod directory; mod family; mod health; mod i18n; +mod in_store; mod live; mod mail; +mod mover; mod oidc; mod pages; mod security; diff --git a/crates/iz-web/src/mover.rs b/crates/iz-web/src/mover.rs new file mode 100644 index 0000000..35733d7 --- /dev/null +++ b/crates/iz-web/src/mover.rs @@ -0,0 +1,418 @@ +//! The mover: moves attachment bytes between this disk and the Files service (`in`), in both directions. +//! +//! The row says where the bytes are (`local`, `in` or `moving`). Which direction runs is the setting +//! `attachment_location`: with `in`, rows that are `local` go to `in`; with `local`, rows that are `in` come back. +//! So a fresh upload, a switch of the setting and a restart in the middle of a migration are all the same +//! work: the mover looks at the rows and moves what is not where the setting says. Nothing is kept in +//! memory that a restart would lose, except the backoff of a row that failed (a restart retries at once). +//! +//! A move is one row at a time, with at most [`LANES`] rows in flight: +//! 1. claim the row (`from` to `moving`) under the blob lock, so no other lane takes it; +//! 2. copy the bytes, outside the lock (a `PUT` of the local file, or a `GET` into a staged file that is +//! checked against the row's size and digest); +//! 3. flip the row to its new place under the blob lock, and remove the old copy in the same critical section. +//! +//! The old copy is removed only after the row says the new place, so the bytes are never without a copy. A +//! failure before the flip puts the row back where it was and keeps its old copy. A failure after the flip +//! (the old copy's removal, or the Files copy's `DELETE`) is owed to the deleter, so it is retried until done. +//! +//! At boot, rows left `moving` by a crash are settled from the disk: a local file that is there is complete +//! (files are renamed into place only when whole), so the row is `local`; otherwise the bytes are in `in`. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use futures_util::StreamExt; +use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; +use iz_core::store::attachments::{Attachment, LOCATION_IN, LOCATION_LOCAL, LOCATION_MOVING}; +use tokio::sync::{Mutex, watch}; + +use crate::attachments::retry_delay; +use crate::in_store::InStore; +use crate::state::AppState; + +/// Rows moved at the same time. Reason: bounds the load on this disk and on `in`. +pub const LANES: usize = 2; +/// How long a lane waits when it found no row to move. Reason: a new upload should be moved within seconds. +const POLL: Duration = Duration::from_secs(2); +/// Rows fetched per look at the candidates, so a row in backoff does not hide the others. +const CANDIDATES: i64 = 20; + +/// The backoff of a row whose move failed: how many times, and when it may be tried again. +#[derive(Clone, Copy)] +struct Backoff { + attempts: i64, + not_before: Instant, +} + +/// Failures of a move, as text for the log. They never reach a page. +type MoveResult = std::result::Result<(), String>; + +/// Starts the mover: settles rows left moving by a crash, then runs [`LANES`] lanes until the stop flag is set. +pub fn spawn(state: AppState, stop: watch::Receiver) { + tokio::spawn(async move { + recover(&state).await; + let backoff: Arc>> = Arc::default(); + let mut lanes = Vec::with_capacity(LANES); + for _ in 0..LANES { + lanes.push(tokio::spawn(lane( + state.clone(), + stop.clone(), + backoff.clone(), + ))); + } + for lane in lanes { + let _ = lane.await; + } + tracing::info!("attachment mover stopped"); + }); +} + +/// Settles the rows a crash left moving. See the module comment for the rule. The copy that the rule does not +/// keep is owed to the deleter, so a leftover Files object is removed. +async fn recover(state: &AppState) { + let ids = match state.store.moving_attachment_ids().await { + Ok(ids) => ids, + Err(error) => { + tracing::warn!(error = %error, "reading the rows left moving failed"); + return; + } + }; + for id in ids { + let _guard = state.blob_lock.lock().await; + let Ok(path) = blob_path(&state.config.data_dir, &id) else { + continue; + }; + let on_disk = tokio::fs::try_exists(&path).await.unwrap_or(false); + let settled = if on_disk { LOCATION_LOCAL } else { LOCATION_IN }; + match state + .store + .set_location_if(&id, LOCATION_MOVING, settled) + .await + { + Ok(true) => { + tracing::info!(attachment = %id, location = settled, "settled a move left by a crash"); + if on_disk { + owe(state, &id, LOCATION_IN).await; + } + } + Ok(false) => {} + Err(error) => tracing::warn!(error = %error, "settling a move left by a crash failed"), + } + } +} + +/// One lane: move one row, then look again at once; with nothing to move, wait for [`POLL`] or the stop flag. +async fn lane( + state: AppState, + mut stop: watch::Receiver, + backoff: Arc>>, +) { + loop { + if *stop.borrow() { + break; + } + let moved = match step(&state, &backoff).await { + Ok(moved) => moved, + Err(reason) => { + tracing::warn!(reason, "the attachment mover could not look for rows"); + false + } + }; + if moved { + continue; + } + tokio::select! { + () = tokio::time::sleep(POLL) => {} + _ = stop.wait_for(|stopped| *stopped) => break, + } + } +} + +/// Moves one row toward the place the setting names. `Ok(true)` when a row was tried (or another lane took it). +async fn step( + state: &AppState, + backoff: &Mutex>, +) -> std::result::Result { + let Some(in_store) = state.in_store.clone() else { + // Without the Files service nothing can move: `in` cannot be reached, and nothing is copied to it. + return Ok(false); + }; + let target = state + .store + .attachment_target() + .await + .map_err(|e| e.to_string())?; + let (from, to) = if target == LOCATION_IN { + (LOCATION_LOCAL, LOCATION_IN) + } else { + (LOCATION_IN, LOCATION_LOCAL) + }; + let candidates = state + .store + .attachments_in_location(from, CANDIDATES) + .await + .map_err(|e| e.to_string())?; + let now = Instant::now(); + let picked = { + let waiting = backoff.lock().await; + candidates.into_iter().find(|row| { + waiting + .get(&row.id) + .is_none_or(|retry| retry.not_before <= now) + }) + }; + let Some(row) = picked else { + return Ok(false); + }; + if !claim(state, &row.id, from, LOCATION_MOVING) + .await + .map_err(|e| e.to_string())? + { + // Another lane, or a deletion, got there first. + return Ok(true); + } + let result = if to == LOCATION_IN { + move_to_in(state, &in_store, &row).await + } else { + move_to_local(state, &in_store, &row).await + }; + match result { + Ok(()) => { + backoff.lock().await.remove(&row.id); + } + Err(reason) => { + tracing::warn!(attachment = %row.id, reason, "moving an attachment failed; retrying"); + // The move failed before its flip, so the row goes back and keeps its copy. + if let Err(error) = state + .store + .set_location_if(&row.id, LOCATION_MOVING, from) + .await + { + tracing::error!(error = %error, "putting a row back after a failed move failed"); + } + let mut waiting = backoff.lock().await; + let attempts = waiting.get(&row.id).map_or(0, |retry| retry.attempts) + 1; + waiting.insert( + row.id.clone(), + Backoff { + attempts, + not_before: Instant::now() + retry_delay(attempts), + }, + ); + } + } + Ok(true) +} + +/// Flips a row from `from` to `to` under the blob lock. `true` when it did. +async fn claim(state: &AppState, id: &str, from: &str, to: &str) -> iz_core::Result { + let _guard = state.blob_lock.lock().await; + state.store.set_location_if(id, from, to).await +} + +/// Owes the deleter a copy of `id` in `place`. A failure to record it is logged; the copy then stays until +/// the next move or boot settles it, which is the best a broken database allows. +async fn owe(state: &AppState, id: &str, place: &str) { + if let Err(error) = state.store.owe_blob_deletion(id, place).await { + tracing::error!(error = %error, attachment = %id, place, "recording an owed copy failed"); + } +} + +/// Copies a local row to the Files service, then flips it to `in`, then removes the local file. +async fn move_to_in(state: &AppState, in_store: &InStore, row: &Attachment) -> MoveResult { + let path = blob_path(&state.config.data_dir, &row.id).map_err(|e| e.to_string())?; + let put = in_store + .put(&row.id, &path, row.size, &row.mime, &row.name, &row.sha256) + .await; + if let Err(error) = put { + // A PUT that failed may still have stored the object. It is owed, so it does not outlive the row. + owe(state, &row.id, LOCATION_IN).await; + return Err(error.to_string()); + } + let guard = state.blob_lock.lock().await; + let flipped = state + .store + .set_location_if(&row.id, LOCATION_MOVING, LOCATION_IN) + .await + .map_err(|e| e.to_string())?; + if flipped { + if let Err(error) = remove_blob(&state.config.data_dir, &row.id).await { + tracing::warn!(error = %error, attachment = %row.id, "removing the local copy failed; owed"); + owe(state, &row.id, LOCATION_LOCAL).await; + } + } else { + // The row was deleted while its bytes were on their way. The deletion owed the local copy already; + // the object just stored is owed here. + owe(state, &row.id, LOCATION_IN).await; + } + drop(guard); + Ok(()) +} + +/// Copies an `in` row back to this disk, checks it against the row, flips it to `local`, then removes the +/// Files copy. The download is staged and digested before anything is installed. +async fn move_to_local(state: &AppState, in_store: &InStore, row: &Attachment) -> MoveResult { + let data_dir = state.config.data_dir.as_path(); + let staged = StagedFile::create(data_dir, row.size) + .await + .map_err(|e| e.to_string())?; + let done = download(in_store, &row.id, staged).await?; + if done.size != row.size || done.sha256 != row.sha256 { + // The staged copy is left for the sweeper's stale-temp pass; nothing outside attachments/ is removed here. + return Err("the Files copy is not the bytes of the row".into()); + } + let guard = state.blob_lock.lock().await; + if let Err(error) = install_blob(data_dir, &row.id, &done.path).await { + return Err(error.to_string()); + } + let flipped = match state + .store + .set_location_if(&row.id, LOCATION_MOVING, LOCATION_LOCAL) + .await + { + Ok(flipped) => flipped, + Err(error) => { + // The local copy is installed but the row still says `in`: the copy is owed, so it is removed. + owe(state, &row.id, LOCATION_LOCAL).await; + return Err(error.to_string()); + } + }; + if flipped { + // The Files copy goes under the same lock as the flip, so no new move of this id can start in between. + if let Err(error) = in_store.delete(&row.id).await { + tracing::warn!(error = %error, attachment = %row.id, "removing the Files copy failed; owed"); + owe(state, &row.id, LOCATION_IN).await; + } + } else { + // Deleted while downloading: the deletion owed both copies. Remove the local one now, owe the other. + if let Err(error) = remove_blob(data_dir, &row.id).await { + tracing::warn!(error = %error, "removing the local copy of a deleted row failed; owed"); + owe(state, &row.id, LOCATION_LOCAL).await; + } + owe(state, &row.id, LOCATION_IN).await; + } + drop(guard); + Ok(()) +} + +/// Reads the whole object into `staged`. On any failure the staged file is removed and the reason is returned. +async fn download( + in_store: &InStore, + id: &str, + mut staged: StagedFile, +) -> std::result::Result { + let response = match in_store.get(id, None).await { + Ok(response) => response, + Err(error) => { + staged.abort().await; + return Err(error.to_string()); + } + }; + let mut chunks = response.bytes_stream(); + while let Some(chunk) = chunks.next().await { + let written = match chunk { + Ok(bytes) => staged.write(&bytes).await.map_err(|e| e.to_string()), + Err(error) => Err(error.to_string()), + }; + if let Err(reason) = written { + staged.abort().await; + return Err(reason); + } + } + staged.finish().await.map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicBool, Ordering}; + + use iz_core::staging::blob_path; + use iz_core::store::attachments::SETTING_LOCATION; + + use super::*; + use crate::boot::test_state; + use crate::in_store::test_support::{fake_in, reply, seed_attachment}; + + #[tokio::test] + async fn a_failed_put_keeps_the_local_copy_and_the_row_local() { + let (_dir, mut state) = test_state().await; + state + .store + .set_setting(SETTING_LOCATION, LOCATION_IN) + .await + .expect("target"); + let base = fake_in(|_| reply(500, b"")).await; + state.in_store = Some(Arc::new(InStore::for_tests(&base))); + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; + let backoff = Mutex::new(HashMap::new()); + + assert!(step(&state, &backoff).await.expect("a row was tried")); + + let path = blob_path(&state.config.data_dir, &row.id).expect("path"); + assert_eq!(std::fs::read(&path).expect("local copy"), b"pixels"); + assert_eq!( + state + .store + .attachment_location(&row.id) + .await + .expect("row") + .as_deref(), + Some(LOCATION_LOCAL) + ); + assert!( + backoff.lock().await.contains_key(&row.id), + "the failure backs off" + ); + } + + #[tokio::test] + async fn a_move_removes_the_local_copy_after_the_row_says_in() { + let (_dir, mut state) = test_state().await; + state + .store + .set_setting(SETTING_LOCATION, LOCATION_IN) + .await + .expect("target"); + let row = seed_attachment(&state, "a.png", "image/png", b"pixels").await; + let path = blob_path(&state.config.data_dir, &row.id).expect("path"); + let local_then = Arc::new(AtomicBool::new(false)); + let body_ok = Arc::new(AtomicBool::new(false)); + let (local_flag, body_flag) = (local_then.clone(), body_ok.clone()); + let (sha, size, source) = (row.sha256.clone(), row.size, path.clone()); + let base = fake_in(move |req| { + if req.method != "PUT" { + return reply(404, b""); + } + // The local copy is still there while the bytes are sent; the row is changed afterwards. + local_flag.store(source.exists(), Ordering::SeqCst); + body_flag.store(req.body == b"pixels", Ordering::SeqCst); + let answer = format!( + "{{\"external_id\":\"x\",\"size\":{size},\"sha256\":\"{sha}\",\"content_type\":\"image/png\",\"created_at\":\"now\"}}" + ); + reply(201, answer.as_bytes()) + }) + .await; + state.in_store = Some(Arc::new(InStore::for_tests(&base))); + let backoff = Mutex::new(HashMap::new()); + + assert!(step(&state, &backoff).await.expect("a row was moved")); + + assert!( + local_then.load(Ordering::SeqCst), + "the local copy existed during the PUT" + ); + assert!(body_ok.load(Ordering::SeqCst), "the PUT carried the bytes"); + assert_eq!( + state + .store + .attachment_location(&row.id) + .await + .expect("row") + .as_deref(), + Some(LOCATION_IN) + ); + assert!(!path.exists(), "the local copy goes once the row says in"); + } +} diff --git a/crates/iz-web/src/oidc.rs b/crates/iz-web/src/oidc.rs index 49b6698..28372d0 100644 --- a/crates/iz-web/src/oidc.rs +++ b/crates/iz-web/src/oidc.rs @@ -213,7 +213,8 @@ pub struct OidcClient { stream_http: reqwest::Client, discovery: Mutex)>>, keys: Mutex, - service: Mutex>, + /// Client-credentials tokens by `(audience, scope)`. Each target has its own entry. + service: Mutex>, } #[derive(Default)] @@ -255,7 +256,7 @@ impl OidcClient { stream_http, discovery: Mutex::new(None), keys: Mutex::new(KeyCache::default()), - service: Mutex::new(None), + service: Mutex::new(HashMap::new()), }) } @@ -417,11 +418,18 @@ impl OidcClient { self.post_token(&discovery.token_endpoint, &form).await } - /// A client-credentials token for `scope` and `audience`, cached until 60 seconds before it - /// expires (contracts.md 2.6). + /// The client-credentials token for the directory at `im` (`aud = im`, `directory.read`). pub async fn service_token(&self) -> ImResult { - let mut slot = self.service.lock().await; - if let Some((until, token)) = slot.as_ref() + self.client_token(IM_AUDIENCE, DIRECTORY_SCOPE).await + } + + /// A client-credentials token for `scope` at the family service `audience`, cached until 60 seconds + /// before it expires (contracts.md 2.6). Each `(audience, scope)` pair has its own cache entry, so the + /// token for `in` never replaces the one for `im`. + pub async fn client_token(&self, audience: &str, scope: &str) -> ImResult { + let key = (audience.to_owned(), scope.to_owned()); + let mut slots = self.service.lock().await; + if let Some((until, token)) = slots.get(&key) && Instant::now() < *until { return Ok(token.clone()); @@ -429,8 +437,8 @@ impl OidcClient { let discovery = self.discovery().await?; let form = [ ("grant_type", "client_credentials"), - ("scope", DIRECTORY_SCOPE), - ("audience", IM_AUDIENCE), + ("scope", scope), + ("audience", audience), ]; let response = self.post_token(&discovery.token_endpoint, &form).await?; let token = response @@ -439,7 +447,7 @@ impl OidcClient { .ok_or_else(|| ImError::BadResponse("the token answer has no access token".into()))?; let lifetime = Duration::from_secs(response.expires_in.unwrap_or(0)); let until = Instant::now() + lifetime.saturating_sub(SERVICE_TOKEN_MARGIN); - *slot = Some((until, token.clone())); + slots.insert(key, (until, token.clone())); Ok(token) } diff --git a/crates/iz-web/src/pages/admin.rs b/crates/iz-web/src/pages/admin.rs index 12df691..faed501 100644 --- a/crates/iz-web/src/pages/admin.rs +++ b/crates/iz-web/src/pages/admin.rs @@ -55,6 +55,7 @@ pub fn notice_text(lang: Lang, code: &str, queued: Option<&str>) -> Option t(lang, K::NoticeRetried).to_owned(), "role_set" => structure_t(lang, StructureK::NoticeRoleSet).to_owned(), "limits" => structure_t(lang, StructureK::NoticeLimitsSaved).to_owned(), + "storage" => structure_t(lang, StructureK::NoticeStorageSaved).to_owned(), "tag_added" | "tag_renamed" | "tag_coloured" | "tag_deleted" | "tag_moved" => { return crate::pages::tags::tag_notice(lang, code); } diff --git a/crates/iz-web/src/pages/files.rs b/crates/iz-web/src/pages/files.rs index f7aa93a..a8858f0 100644 --- a/crates/iz-web/src/pages/files.rs +++ b/crates/iz-web/src/pages/files.rs @@ -24,7 +24,7 @@ use iz_core::slides::{Slide, read_deck}; use iz_core::sniff::sniff; use iz_core::staging::{StagedFile, blob_path, install_blob, remove_blob}; use iz_core::store::attachments::{ - Attachment, NewAttachment, Policy, clean_name, extension_allowed, extension_of, + Attachment, LOCATION_IN, NewAttachment, Policy, clean_name, extension_allowed, extension_of, new_attachment_id, }; use jiff::tz::TimeZone; @@ -35,21 +35,25 @@ use topcoat::context::{Cx, app_context}; use topcoat::router::content::Form; use topcoat::router::content::multipart::{Field, Multipart}; use topcoat::router::error::{forbidden, see_other}; +use topcoat::router::request::headers; use topcoat::router::response::Response; -use topcoat::router::{path_param_segment, route}; +use topcoat::router::{StatusCode, path_param_segment, route}; use topcoat::view::view; use crate::auth::{ CurrentMember, Need, percent_encode, query_param, require_csrf, require_role, safe_next, }; use crate::i18n::lang; +use crate::i18n::shell::{K as ShellK, t as shell_t}; use crate::i18n::task::{K, t}; use crate::pages::board::{BoardPage, the_board}; use crate::pages::task::{Draft, FileRow, back, bump, core_err, local_text, modal_url, refuse}; -use crate::serve::{ByteAnswer, ByteSource, Disposition, inline_safe, serve_file}; +use crate::serve::{ + ByteSource, Disposition, inline_safe, into_response, serve_local, serve_remote, +}; use crate::state::AppState; use crate::views::files::file_page; -use crate::views::{ViewerInfo, respond, shell}; +use crate::views::{ViewerInfo, message_page, respond, shell}; /// Longest text field of the upload form (the csrf token, the return path), in bytes. const FIELD_MAX_BYTES: usize = 2048; @@ -210,7 +214,11 @@ pub async fn load_view( ) -> Result { let path = blob_path(&state.config.data_dir, &attachment.id)?; let kind = kind_of(attachment); + // A parser reads the bytes from this disk. A file that is only in the Files service cannot be parsed here, so + // the viewer says it cannot show it. Images, media and PDFs are shown by the byte route, which proxies. + let on_disk = tokio::fs::try_exists(&path).await.unwrap_or(false); let body = match kind { + Kind::Text | Kind::Workbook | Kind::Csv | Kind::Deck if !on_disk => ViewBody::Refused, Kind::Image => ViewBody::Image, Kind::Video => ViewBody::Video, Kind::Audio => ViewBody::Audio, @@ -579,9 +587,11 @@ async fn delete_file(cx: &Cx, form: Option>) -> Result Result { +async fn file_bytes(cx: &Cx) -> Result { let state = app_context::(cx); require_role(cx, Need::Viewer).await?; let id = path_param_segment(cx, "id").to_owned(); @@ -605,7 +615,37 @@ async fn file_bytes(cx: &Cx) -> Result { } else { Disposition::Inline }; - serve_file(cx, &source, disposition).await + let request = headers(cx); + if attachment.location != LOCATION_IN + && let Some(answer) = serve_local(request, &source, disposition).await? + { + return Ok(into_response(answer)); + } + if let Some(in_store) = state.in_store.as_deref() { + match serve_remote(request, &source, disposition, in_store, &attachment.id).await { + Ok(answer) => return Ok(into_response(answer)), + Err(error) => tracing::warn!( + error = %error, + attachment = %attachment.id, + "the Files service could not send an attachment" + ), + } + } + unavailable_page(cx).await +} + +/// The page for a file that neither this disk nor the Files service can send now: `503` in the usual shell. +async fn unavailable_page(cx: &Cx) -> Result { + let lang = lang(cx, None); + let document = view! { + cx => + shell(title: shell_t(lang, ShellK::FilesUnavailableTitle), lang: lang, viewer: None, page_script: None, + (StatusCode::SERVICE_UNAVAILABLE) + message_page(lang: lang, title: ShellK::FilesUnavailableTitle, + body: ShellK::FilesUnavailableBody, detail: None) + ) + }; + respond(cx, document).await } /// The viewer's own page, `GET /tasks/{key}/files/{id}/view`. The file must belong to the task with `key`. @@ -661,6 +701,7 @@ mod tests { sha256: "0".repeat(64), uploaded_by: "u".into(), created_at: "x".into(), + location: "local".into(), } } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index 878a367..b64c7ae 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -29,11 +29,14 @@ use crate::pages::admin::{CsrfForm, REFUSED, back, notice_text, user_text, viewe use crate::pages::board::the_board; use crate::state::AppState; use crate::views::admin::{SenderForm, SettingsView, settings_content}; -use crate::views::structure::{MemberRow, ServerInfo}; +use crate::views::structure::{MemberRow, ServerInfo, StorageInfo}; use crate::views::{ViewerInfo, respond, shell}; use iz_core::authz::Role; use iz_core::limits::{ATTACHMENT_LIMIT_MIB_MAX, ATTACHMENT_LIMIT_MIB_MIN}; -use iz_core::store::attachments::{SETTING_EXTENSIONS, SETTING_LIMIT_MIB, parse_extensions}; +use iz_core::store::attachments::{ + LOCATION_IN, LOCATION_LOCAL, SETTING_EXTENSIONS, SETTING_LIMIT_MIB, SETTING_LOCATION, + parse_extensions, +}; use iz_core::store::audit::AuditEntry; use topcoat::router::path_param_segment; @@ -104,6 +107,7 @@ async fn settings_view( let mut sender = form.unwrap_or_else(|| sender_form(&stored)); sender.password_set = stored.password_set; let policy = state.store.policy().await?; + let storage = storage_info(state).await?; let members = state .store .list_members() @@ -132,11 +136,13 @@ async fn settings_view( limit_mib, extensions, server: server_info(state).await?, + storage, }) } /// The read-only server facts of the settings page. async fn server_info(state: &AppState) -> Result { + let storage_in = state.store.attachment_target().await? == LOCATION_IN; Ok(ServerInfo { base_url: state.config.base_url.clone(), listen: state.config.listen.to_string(), @@ -145,10 +151,35 @@ async fn server_info(state: &AppState) -> Result { schema: state.store.schema_version().await?, build: env!("IZ_BUILD_SHA").to_owned(), sign_in: state.oidc.is_some(), - storage_in: state.config.in_store.enabled, + storage_in, }) } +/// The attachment storage form: the place the admin chose, `local` or `in`. +#[derive(Debug, Default, Deserialize)] +#[serde(default)] +struct StorageSubmit { + csrf: String, + location: String, +} + +/// The storage section's data: the chosen place, whether the Files service is set up, and the row counts. +async fn storage_info(state: &AppState) -> Result { + let mut info = StorageInfo { + target: state.store.attachment_target().await?, + in_available: state.in_store.is_some(), + ..StorageInfo::default() + }; + for (location, count) in state.store.attachment_location_counts().await? { + match location.as_str() { + LOCATION_LOCAL => info.local = count, + LOCATION_IN => info.in_files = count, + _ => info.moving += count, + } + } + Ok(info) +} + /// The members-and-roles form: the role word of one member. #[derive(Debug, Default, Deserialize)] #[serde(default)] @@ -459,6 +490,53 @@ async fn save_role(cx: &Cx, form: Option>) -> Result } } +/// `POST /settings/attachments`: where attachments are kept. Saving only records the choice; the mover brings the +/// files over in the background. `in` needs the Files service to be set up on this server. +#[route(POST "/settings/attachments")] +async fn save_storage(cx: &Cx, form: Option>) -> Result { + let state = app_context::(cx); + let form = form.map(|Form(form)| form).unwrap_or_default(); + let me = require_csrf(cx, Need::Admin, &form.csrf).await?; + let language = lang(cx, me.member.locale_override.as_deref()); + let outcome: iz_core::Result<&str> = match form.location.as_str() { + LOCATION_LOCAL => Ok(LOCATION_LOCAL), + LOCATION_IN if state.in_store.is_some() => Ok(LOCATION_IN), + LOCATION_IN => Err(iz_core::Error::Invalid( + "the Files service is not set up on this server".into(), + )), + _ => Err(iz_core::Error::Invalid( + "choose this server or the Files service".into(), + )), + }; + let outcome = match outcome { + Ok(place) => state.store.set_setting(SETTING_LOCATION, place).await, + Err(error) => Err(error), + }; + match outcome { + Ok(()) => { + state + .store + .audit(AuditEntry { + actor: Some(&me.member.sub), + actor_kind: "admin", + action: "attachments.location", + target_kind: "settings", + target_id: None, + ip: None, + data: serde_json::json!({ "location": form.location }), + }) + .await; + state.live.bump(&Topic::Admin(AdminSection::Settings)); + back("/settings?notice=storage") + } + Err(error) => { + let message = user_text(error)?; + let page = settings_view(state, language, None, None, Some(message)).await?; + render(cx, &me, page, REFUSED).await + } + } +} + /// `POST /settings/limits`: the attachment size (1 to 500 MiB) and the allowed extensions. #[route(POST "/settings/limits")] async fn save_limits(cx: &Cx, form: Option>) -> Result { diff --git a/crates/iz-web/src/serve.rs b/crates/iz-web/src/serve.rs index a26886c..6d685e7 100644 --- a/crates/iz-web/src/serve.rs +++ b/crates/iz-web/src/serve.rs @@ -17,6 +17,7 @@ use std::io::{self, SeekFrom}; use std::path::Path; use bytes::Bytes; +use futures_util::StreamExt; use http::header::{ ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, @@ -25,11 +26,11 @@ use http::header::{ use http_body::Frame; use http_body_util::StreamBody; use tokio::io::{AsyncReadExt, AsyncSeekExt}; -use topcoat::Result; -use topcoat::context::Cx; -use topcoat::router::request::headers; +use topcoat::router::response::Response; use topcoat::router::{Body, HeaderMap, HeaderName, HeaderValue, StatusCode}; +use crate::in_store::{InError, InResult, InStore}; + /// What a browser may do with a byte response: show it in the page, or save it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Disposition { @@ -57,9 +58,17 @@ pub struct ByteSource<'a> { pub name: &'a str, } -/// The status, headers and body of a byte response. Handlers return it as they are. +/// The status, headers and body of a byte response. pub type ByteAnswer = (StatusCode, HeaderMap, Body); +/// Turns a byte answer into the response a handler returns. +pub fn into_response((status, headers, body): ByteAnswer) -> Response { + let mut response = http::Response::new(body); + *response.status_mut() = status; + *response.headers_mut() = headers; + response +} + /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and /// `default-src 'none'` stops it from loading anything but its own image, media or style. Only a page of this /// origin may frame the bytes (the viewer). @@ -282,95 +291,201 @@ fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { } } -/// The `416` answer: no body, and the length the client may ask again within. -fn unsatisfiable(etag: &str, len: u64, mime: &str) -> ByteAnswer { - let mut headers = common_headers(etag, mime); - insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); - (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) +/// The bytes a `200` or `206` sends: `length` bytes from `start`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + /// First byte, from the start of the file. + pub start: u64, + /// Number of bytes. + pub length: u64, + /// Whether the answer is a `206` for one range (the upstream must then answer a range too). + pub ranged: bool, } -/// Sends the bytes of `source` for the request in `cx`. -/// -/// `disposition` is the caller's wish. It becomes [`Disposition::Attachment`] unless the type is in -/// [`inline_safe`]. The body streams from the file from the first byte the answer needs. A file that cannot be -/// opened is an error, which the router answers as a `500`: the row names bytes that are not there. -pub async fn serve_file( - cx: &Cx, - source: &ByteSource<'_>, - disposition: Disposition, -) -> Result { - let request = headers(cx); +/// The status and headers of a byte answer, and the bytes it sends. The headers are made here, from the row: +/// nothing of the bytes' origin is copied into them. +#[derive(Debug)] +pub struct Plan { + /// The status of the answer. + pub status: StatusCode, + /// The headers of the answer. + pub headers: HeaderMap, + /// The bytes to send, or `None` when the answer has no body (`304`, `416`). + pub span: Option, +} + +impl Plan { + /// The answer with `body` (empty when the plan sends no bytes). + fn answer(self, body: Body) -> ByteAnswer { + (self.status, self.headers, body) + } +} + +/// Decides the answer for the request headers `request` and a file described by `source`: the status, the +/// headers, and which bytes to send. Reads nothing from disk or from the network. +pub fn plan(request: &HeaderMap, source: &ByteSource<'_>, disposition: Disposition) -> Plan { let etag = format!("\"{}\"", source.sha256); let disposition = match disposition { Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, _ => Disposition::Attachment, }; - let mut answer_headers = common_headers(&etag, source.mime); + let mut headers = common_headers(&etag, source.mime); insert( - &mut answer_headers, + &mut headers, CONTENT_DISPOSITION, &content_disposition(disposition, source.name), ); - insert( - &mut answer_headers, - CONTENT_TYPE, - &content_type_value(source.mime), - ); + insert(&mut headers, CONTENT_TYPE, &content_type_value(source.mime)); if none_match_hits(request, &etag) { - return Ok((StatusCode::NOT_MODIFIED, answer_headers, Body::empty())); + return Plan { + status: StatusCode::NOT_MODIFIED, + headers, + span: None, + }; } match requested_range(request, &etag, source.size) { - Ranged::Unsatisfiable => Ok(unsatisfiable(&etag, source.size, source.mime)), - Ranged::Full => { + Ranged::Unsatisfiable => { + let mut unsatisfiable = common_headers(&etag, source.mime); insert( - &mut answer_headers, - CONTENT_LENGTH, - &source.size.to_string(), + &mut unsatisfiable, + CONTENT_RANGE, + &format!("bytes */{}", source.size), ); - let body = open_streamed(source.path, 0, source.size).await?; - Ok((StatusCode::OK, answer_headers, body)) + Plan { + status: StatusCode::RANGE_NOT_SATISFIABLE, + headers: unsatisfiable, + span: None, + } + } + Ranged::Full => { + insert(&mut headers, CONTENT_LENGTH, &source.size.to_string()); + Plan { + status: StatusCode::OK, + headers, + span: Some(Span { + start: 0, + length: source.size, + ranged: false, + }), + } } Ranged::Part { start, end } => { let length = end - start + 1; - insert(&mut answer_headers, CONTENT_LENGTH, &length.to_string()); + insert(&mut headers, CONTENT_LENGTH, &length.to_string()); insert( - &mut answer_headers, + &mut headers, CONTENT_RANGE, &format!("bytes {start}-{end}/{}", source.size), ); - let body = open_streamed(source.path, start, length).await?; - Ok((StatusCode::PARTIAL_CONTENT, answer_headers, body)) + Plan { + status: StatusCode::PARTIAL_CONTENT, + headers, + span: Some(Span { + start, + length, + ranged: true, + }), + } } } } -/// Opens `path`, seeks to `start` and streams `length` bytes from there. -async fn open_streamed(path: &Path, start: u64, length: u64) -> Result { - let mut file = tokio::fs::File::open(path).await?; - if start > 0 { - file.seek(SeekFrom::Start(start)).await?; +/// Answers from the file on this disk. `Ok(None)` when the file is not there (the row may have moved to the +/// Files service in the meantime), so the caller can try the other place. Any other failure is an error. +pub async fn serve_local( + request: &HeaderMap, + source: &ByteSource<'_>, + disposition: Disposition, +) -> io::Result> { + let plan = plan(request, source, disposition); + let Some(span) = plan.span else { + return Ok(Some(plan.answer(Body::empty()))); + }; + match open_streamed(source.path, span).await { + Ok(body) => Ok(Some(plan.answer(body))), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), } - let frames = futures_util::stream::try_unfold((file, length), |(mut file, left)| async move { - if left == 0 { - return Ok(None); - } - let want = left.min(FRAME_BYTES as u64) as usize; - let mut buf = vec![0u8; want]; - let read = file.read(&mut buf).await?; - if read == 0 { +} + +/// Answers from the Files service: the same headers as [`serve_local`], and the bytes streamed from `in` +/// (with the same range). `in`'s own headers are never copied. The upstream's status and length must match +/// what the plan expects, or the answer is an error and nothing is sent. +pub async fn serve_remote( + request: &HeaderMap, + source: &ByteSource<'_>, + disposition: Disposition, + store: &InStore, + object_id: &str, +) -> InResult { + let plan = plan(request, source, disposition); + let Some(span) = plan.span else { + return Ok(plan.answer(Body::empty())); + }; + let range = span + .ranged + .then(|| (span.start, span.start + span.length - 1)); + let response = store.get(object_id, range).await?; + let expected = if span.ranged { 206 } else { 200 }; + if response.status().as_u16() != expected { + return Err(InError::BadResponse(format!( + "the object answered {} for a {expected}", + response.status().as_u16() + ))); + } + if response + .content_length() + .is_some_and(|len| len != span.length) + { + return Err(InError::BadResponse( + "the object has another length than the record".into(), + )); + } + let limit = span.length; + let mut sent: u64 = 0; + let frames = response.bytes_stream().map(move |chunk| { + let chunk = chunk.map_err(io::Error::other)?; + sent += chunk.len() as u64; + if sent > limit { return Err(io::Error::new( - io::ErrorKind::UnexpectedEof, - "the file is shorter than its record", + io::ErrorKind::InvalidData, + "the object is longer than its record", )); } - buf.truncate(read); - Ok(Some(( - Frame::data(Bytes::from(buf)), - (file, left - read as u64), - ))) + Ok(Frame::data(chunk)) }); + Ok(plan.answer(Body::new(StreamBody::new(frames)))) +} + +/// Opens `path`, seeks to the span's start and streams its bytes. The open is the error that matters: a file +/// that is not there is `NotFound`. +async fn open_streamed(path: &Path, span: Span) -> io::Result { + let mut file = tokio::fs::File::open(path).await?; + if span.start > 0 { + file.seek(SeekFrom::Start(span.start)).await?; + } + let frames = + futures_util::stream::try_unfold((file, span.length), |(mut file, left)| async move { + if left == 0 { + return Ok(None); + } + let want = left.min(FRAME_BYTES as u64) as usize; + let mut buf = vec![0u8; want]; + let read = file.read(&mut buf).await?; + if read == 0 { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "the file is shorter than its record", + )); + } + buf.truncate(read); + Ok(Some(( + Frame::data(Bytes::from(buf)), + (file, left - read as u64), + ))) + }); Ok(Body::new(StreamBody::new(frames))) } @@ -462,4 +577,96 @@ mod tests { ); assert!(content_disposition(Disposition::Attachment, "").contains("filename=\"download\"")); } + + /// A file in the Files service is proxied with this server's headers only, and with the requested range. + #[tokio::test] + async fn a_row_in_the_files_service_is_sent_with_our_headers_only() { + use crate::boot::test_state; + use crate::in_store::InStore; + use crate::in_store::test_support::{Reply, fake_in}; + use std::sync::Arc; + use topcoat::router::to_bytes; + + let data = b"hello world"; + let base = fake_in(move |req| { + if req.method != "GET" { + return Reply { + status: 405, + headers: Vec::new(), + body: Vec::new(), + }; + } + let headers = vec![ + ("Content-Security-Policy".into(), "default-src *".into()), + ("Set-Cookie".into(), "sid=stolen".into()), + ( + "Content-Disposition".into(), + "attachment; filename=evil".into(), + ), + ("X-Frame-Options".into(), "ALLOWALL".into()), + ]; + match req.header("range").and_then(|r| r.strip_prefix("bytes=")) { + Some(spec) => { + let (first, last) = spec.split_once('-').expect("range"); + let (first, last): (usize, usize) = + (first.parse().expect("first"), last.parse().expect("last")); + Reply { + status: 206, + headers, + body: data[first..=last].to_vec(), + } + } + None => Reply { + status: 200, + headers, + body: data.to_vec(), + }, + } + }) + .await; + let (_dir, mut state) = test_state().await; + state.in_store = Some(Arc::new(InStore::for_tests(&base))); + let source = ByteSource { + path: Path::new("/does/not/exist"), + size: data.len() as u64, + sha256: "0000000000000000000000000000000000000000000000000000000000000000", + mime: "image/png", + name: "a.png", + }; + let store = state.in_store.as_deref().expect("client"); + + let mut ranged = HeaderMap::new(); + ranged.insert(RANGE, HeaderValue::from_static("bytes=0-4")); + let (status, headers, body) = serve_remote( + &ranged, + &source, + Disposition::Inline, + store, + "01HZ0000000000000000000000", + ) + .await + .expect("answer"); + assert_eq!(status, StatusCode::PARTIAL_CONTENT); + assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), b"hello"); + assert_eq!(headers.get_all(CONTENT_SECURITY_POLICY).iter().count(), 1); + assert_eq!(headers[CONTENT_SECURITY_POLICY], BYTES_CSP); + assert!(headers.get(http::header::SET_COOKIE).is_none()); + assert_eq!( + headers[CONTENT_DISPOSITION], + content_disposition(Disposition::Inline, "a.png").as_str() + ); + assert_eq!(headers[CONTENT_RANGE], "bytes 0-4/11"); + + let (status, _, body) = serve_remote( + &HeaderMap::new(), + &source, + Disposition::Inline, + store, + "01HZ0000000000000000000000", + ) + .await + .expect("answer"); + assert_eq!(status, StatusCode::OK); + assert_eq!(to_bytes(body, 1024).await.expect("body").as_ref(), data); + } } diff --git a/crates/iz-web/src/state.rs b/crates/iz-web/src/state.rs index 0d41d32..2354bd0 100644 --- a/crates/iz-web/src/state.rs +++ b/crates/iz-web/src/state.rs @@ -6,6 +6,7 @@ use iz_core::config::Config; use iz_core::store::Store; use crate::family::FamilyCache; +use crate::in_store::InStore; use crate::live::LiveHub; use crate::oidc::OidcClient; @@ -25,4 +26,10 @@ pub struct AppState { pub oidc: Option>, /// The family service list that the topbar switcher shows. Filled by the `family` worker. pub family: Arc, + /// The Files service (`in`). `None` unless `[in_store]` is enabled with a URL and sign-in gives the token. + pub in_store: Option>, + /// Held around every step that changes where attachment bytes are: a row's claim, flip or removal, a + /// local copy's removal, and a Files copy's deletion. The mover and the deleter take it, so a stale record + /// can never remove the live copy (see `attachments.rs`). + pub blob_lock: Arc>, } diff --git a/crates/iz-web/src/sweeper.rs b/crates/iz-web/src/sweeper.rs index 37d3d07..2618991 100644 --- a/crates/iz-web/src/sweeper.rs +++ b/crates/iz-web/src/sweeper.rs @@ -1,6 +1,6 @@ //! The sweeper worker: housekeeping that is not urgent. It runs once at start and then every hour until the //! stop flag is set. Each run deletes expired sessions and expired logout-token records, retries the -//! attachment bytes still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass +//! attachment copies still owed (the deleter in `attachments.rs` does this too, every few seconds; this pass //! is the backstop), deletes activity and mail-ledger rows older than `RETENTION_DAYS`, and removes staged //! uploads left in `data_dir/tmp` by a crash. //! @@ -11,12 +11,12 @@ use std::future::Future; use std::path::Path; use std::time::{Duration, SystemTime}; -use iz_core::staging::{TMP_DIR, remove_blob}; +use iz_core::staging::TMP_DIR; use iz_core::store::sweep::RETENTION_DAYS; use jiff::{SignedDuration, Timestamp}; use tokio::sync::watch; -use crate::attachments::retry_delay; +use crate::attachments; use crate::state::AppState; /// How often the sweeper runs after its first pass. Reason: none of this is urgent. @@ -44,7 +44,7 @@ pub fn spawn(state: AppState, mut stop: watch::Receiver) { async fn sweep(state: &AppState) { note("expired sessions", state.store.sweep_sessions().await); note("expired logout tokens", state.store.sweep_jti().await); - retry_blob_deletions(state).await; + attachments::sweep(state).await; match Timestamp::now().checked_sub(SignedDuration::from_hours(24 * RETENTION_DAYS)) { Ok(cutoff) => { drain("activity", |batch| { @@ -105,40 +105,6 @@ where note(what, Ok(total)); } -/// Retries the attachment bytes that are owed and due. A removal that fails is scheduled again with the -/// same backoff the deleter uses. Returns nothing; the deleter logs its own failures. -async fn retry_blob_deletions(state: &AppState) { - let due = match state.store.due_blob_deletions(BATCH).await { - Ok(due) => due, - Err(error) => { - tracing::warn!(error = %error, "reading the due attachment deletions failed"); - return; - } - }; - let mut removed: u64 = 0; - for (id, attempts) in due { - match remove_blob(&state.config.data_dir, &id).await { - Ok(()) => match state.store.finish_blob_deletion(&id).await { - Ok(()) => removed += 1, - Err(error) => { - tracing::warn!(error = %error, "clearing a finished attachment deletion failed"); - } - }, - Err(error) => { - tracing::warn!(attempts, error = %error, "removing attachment bytes failed; retrying"); - if let Err(error) = state - .store - .defer_blob_deletion(&id, attempts, retry_delay(attempts)) - .await - { - tracing::warn!(error = %error, "scheduling an attachment deletion retry failed"); - } - } - } - } - note("attachment bytes removed", Ok(removed)); -} - /// Removes regular files in `data_dir/tmp` that were last changed more than [`TEMP_MAX_AGE`] ago. A missing /// staging directory means there is nothing to remove. Links and directories are left alone. async fn remove_stale_temp_files(data_dir: &Path) -> iz_core::Result { diff --git a/crates/iz-web/src/views/admin.rs b/crates/iz-web/src/views/admin.rs index 640d735..e0d3e12 100644 --- a/crates/iz-web/src/views/admin.rs +++ b/crates/iz-web/src/views/admin.rs @@ -12,7 +12,7 @@ use crate::i18n::Lang; use crate::i18n::admin::{K, t}; use crate::i18n::structure::{K as StructureK, t as structure_t}; use crate::views::board::flag; -use crate::views::structure::{limits_section, members_section, server_section}; +use crate::views::structure::{limits_section, members_section, server_section, storage_section}; use crate::views::{alert, notice}; /// The sender form as it is shown. The password is never here, only `password_set`. @@ -136,6 +136,8 @@ pub struct SettingsView { pub extensions: String, /// Read-only facts about the server. pub server: crate::views::structure::ServerInfo, + /// Where attachments are kept and how far the move between places has got. + pub storage: crate::views::structure::StorageInfo, } /// The rules page: the list, the form (new or editing), and the choices of the form. @@ -311,6 +313,7 @@ pub async fn settings_content(page: &SettingsView, csrf: &str) -> Result members_section(lang: lang, members: &page.members, csrf: csrf) + storage_section(lang: lang, info: &page.storage, csrf: csrf) limits_section(lang: lang, limit_mib: page.limit_mib.as_str(), extensions: page.extensions.as_str(), csrf: csrf) server_section(lang: lang, info: &page.server) }) diff --git a/crates/iz-web/src/views/structure.rs b/crates/iz-web/src/views/structure.rs index beac9bb..63d14e2 100644 --- a/crates/iz-web/src/views/structure.rs +++ b/crates/iz-web/src/views/structure.rs @@ -106,6 +106,74 @@ pub struct ServerInfo { pub storage_in: bool, } +/// Where attachments are kept, and how far a move between the two places has got. Read from the store for the +/// settings page; `in_available` says whether the Files service can be chosen at all. +#[derive(Debug, Clone, Default)] +pub struct StorageInfo { + /// The chosen place: `local` or `in`. + pub target: String, + /// Whether the Files service is set up (configured, and a token can be had). + pub in_available: bool, + /// Rows whose bytes are on this server. + pub local: i64, + /// Rows whose bytes are in the Files service. + pub in_files: i64, + /// Rows being moved right now. + pub moving: i64, +} + +/// The attachment storage section of `/settings`: the chosen place, the counts, and the migration still to do. +#[component] +pub async fn storage_section(lang: Lang, info: &StorageInfo, csrf: &str) -> Result { + let in_chosen = info.target == "in"; + let counts = fill( + t(lang, K::StorageCounts), + &[ + &info.local.to_string(), + &info.in_files.to_string(), + &info.moving.to_string(), + ], + ); + // Rows not yet where the setting says: the ones the mover still has to bring over, plus any mid-move. + let waiting = if in_chosen { + info.local + info.moving + } else { + info.in_files + info.moving + }; + let target_word = if in_chosen { + t(lang, K::StorageIn) + } else { + t(lang, K::StorageLocal) + }; + let migrating = (waiting > 0).then(|| { + fill( + t(lang, K::StorageMigrating), + &[&waiting.to_string(), target_word], + ) + }); + Ok(view! { +
+

(t(lang, K::StorageHeading))

+

(t(lang, K::StorageHelp))

+

(counts.as_str())

+ if let Some(line) = &migrating { +

(line.as_str())

+ } +
+ +
+ + + if !info.in_available { +

(t(lang, K::StorageInUnavailable))

+ } +
+ +
+
+ }) +} + /// The projects page body. #[component] pub async fn tags_content(page: &TagsView, csrf: &str) -> Result {