forge
Explore
Log in

Don't you dare go Hollow

attachments can live with the family's Files service: a storage mode the admin toggles at Settings ▸ Limits (local always stands; in is offered only when config names a key and the family mirror carries the row, and both refusals say which half is missing), a card beside it reading the storage beat's health in the connection card's own shape — service and URL from the mirror, the dot, the limit im set rendered from the account's own numbers, the migration counter while rows still move, the last problem's age and word — and the bytes themselves crossing one seam. Under in, an upload pushes synchronously inside the request under a ULID minted for the row (no queue: a service that is not there is a refusal the uploader acts on now, and a quota spent is the family's own word), the row is born stored and no file lands here; a stored row serves back through the service with the exact headers the local path always sent (503, never the stranger's 404, when the service is down), and its delete takes the remote copy first — an unreachable service refuses and the row stays serviceable. Turning the mode on drains the disk's existing rows through the same idempotent push, oldest first, four a beat, the file leaving as the row flips; turning it back leaves stored rows where they are, because where a row's bytes live is the row's own fact. The key never renders and never logs; resniff passes over rows whose bytes are not here; and set_storage_backend announces Settings while the setting row itself stays as quiet as ever.

Browse files at this commit

7a6cd0c29397959e3fbee7b0f50212ca58a1d5d5Ahmet Kaan GümüşParent: dd98d9a
Cargo.lockmodified+19 -0
@@ -1931,6 +1931,7 @@ dependencies = [
19311931 "lettre",
19321932 "parking_lot",
19331933 "quick-xml",
1934+ "reqwest",
19341935 "serde",
19351936 "serde_json",
19361937 "sha2 0.10.9",
@@ -2273,6 +2274,16 @@ version = "0.3.17"
22732274 source = "registry+https://github.com/rust-lang/crates.io-index"
22742275 checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
22752276
2277+[[package]]
2278+name = "mime_guess"
2279+version = "2.0.5"
2280+source = "registry+https://github.com/rust-lang/crates.io-index"
2281+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
2282+dependencies = [
2283+ "mime",
2284+ "unicase",
2285+]
2286+
22762287 [[package]]
22772288 name = "minimal-lexical"
22782289 version = "0.2.1"
@@ -3008,6 +3019,7 @@ dependencies = [
30083019 "base64 0.22.1",
30093020 "bytes",
30103021 "futures-core",
3022+ "futures-util",
30113023 "http",
30123024 "http-body",
30133025 "http-body-util",
@@ -3016,6 +3028,7 @@ dependencies = [
30163028 "hyper-util",
30173029 "js-sys",
30183030 "log",
3031+ "mime_guess",
30193032 "percent-encoding",
30203033 "pin-project-lite",
30213034 "quinn",
@@ -4756,6 +4769,12 @@ dependencies = [
47564769 "version_check",
47574770 ]
47584771
4772+[[package]]
4773+name = "unicase"
4774+version = "2.9.0"
4775+source = "registry+https://github.com/rust-lang/crates.io-index"
4776+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
4777+
47594778 [[package]]
47604779 name = "unicode-ident"
47614780 version = "1.0.24"
crates/iz-core/migrations/0007_attachment_remote.sqladded+8 -0
@@ -0,0 +1,8 @@
1+-- An attachment row learns where its bytes live.
2+--
3+-- `local`: under `<storage>/attachments/<id>`, as every row before this
4+-- column kept them. `stored`: through the family's Files service, keyed by
5+-- the row's own id — in's service routes are keyed by external id, which is
6+-- this id, so no second id column is added. Rows from before the column are
7+-- local by definition and start there; nothing is backfilled.
8+ALTER TABLE attachment ADD COLUMN remote_state TEXT NOT NULL DEFAULT 'local';
crates/iz-core/src/config.rsmodified+135 -7
@@ -49,6 +49,13 @@ const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One p
4949 database = "iz.db"
5050 # Where attachments live as files, created on boot.
5151 storage = "storage"
52+# Attachments can live with the family's Files service instead of this
53+# disk. Uncomment, fill in the service key minted for iz, and remove the
54+# `storage` line above in the same breath — one key cannot be both a
55+# path and a table, and a file that tries both is refused at boot.
56+#[storage.in]
57+#token = ""
58+
5259 # The address the server listens on. Environment variables are ignored —
5360 # this is the only thing that decides where iz binds. It is also the
5461 # address mail links fall back to, until an admin sets one in Settings.
@@ -151,10 +158,15 @@ struct OidcToml {
151158 /// The shape of `config/iz.toml`, before the values are checked. Anything
152159 /// else the file says lands in `other`, which is read for its key names only
153160 /// — enough for the report to say a key was seen and not obeyed.
161+///
162+/// `storage` is read as a raw value on purpose: it has been a string (the
163+/// attachments directory) since the first file, and the Files service turns
164+/// it into a table — `[storage.in]`, whose `token` is the service key.
165+/// One field, both shapes, and neither shape a surprise to the reader.
154166 #[derive(Deserialize)]
155167 struct Toml {
156168 database: Option<String>,
157- storage: Option<String>,
169+ storage: Option<toml::Value>,
158170 listen: Option<String>,
159171 live_seconds: Option<u64>,
160172 base_url: Option<String>,
@@ -203,11 +215,24 @@ pub struct Config {
203215 pub base_url: String,
204216 /// The OIDC provider iz trusts.
205217 pub oidc: OidcConfig,
218+ /// The family's Files service, when `[storage.in]` names a token.
219+ /// Absent — or an empty token — means "not configured": the feature
220+ /// cannot be switched on and never auto-appears. The token is a secret
221+ /// minted once in in's panel; it is never printed and never rendered.
222+ pub storage_in: Option<InStorage>,
206223 /// Whether `config/iz.toml` did not exist and was just written with the
207224 /// development defaults this boot.
208225 pub defaulted: bool,
209226 }
210227
228+/// The family's Files service, as the file states it: the service key minted
229+/// for iz, shown once and kept here. `config/iz.toml` is created 0600, and
230+/// nothing reads this token back out — not the report, not a page.
231+#[derive(Clone, Debug, PartialEq, Eq)]
232+pub struct InStorage {
233+ pub token: String,
234+}
235+
211236 /// Why the process is not starting.
212237 #[derive(Clone, Debug, PartialEq, Eq)]
213238 pub enum ConfigError {
@@ -301,9 +326,39 @@ impl Config {
301326 let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;
302327 let database = absolute(dir, Path::new(&database));
303328
304- let storage = match value(toml.storage) {
305- Some(raw) => absolute(dir, Path::new(&raw)),
306- None => default_storage(&database),
329+ // Two shapes share the one key. A string is where binary files live,
330+ // as in every file so far — empty means the default beside the
331+ // database, the same as no line at all. A table is the Files
332+ // service: `[storage.in]`, whose `token` is the key minted for iz,
333+ // and the file no longer names a local tree, so the default stands
334+ // in for the directory the photos (always local) still need. Any
335+ // other shape is a file that does not know what it is saying.
336+ let (storage, storage_in) = match toml.storage {
337+ Some(toml::Value::String(raw)) => {
338+ let path = value(Some(raw));
339+ let storage = match path {
340+ Some(raw) => absolute(dir, Path::new(&raw)),
341+ None => default_storage(&database),
342+ };
343+ (storage, None)
344+ }
345+ Some(toml::Value::Table(table)) => {
346+ let token = table
347+ .get("in")
348+ .and_then(|in_table| in_table.get("token"))
349+ .and_then(|token| token.as_str())
350+ .map(str::to_string)
351+ .and_then(|token| value(Some(token)));
352+ let storage_in = token.map(|token| InStorage { token });
353+ (default_storage(&database), storage_in)
354+ }
355+ Some(_) => {
356+ return Err(ConfigError::Invalid {
357+ key: "storage",
358+ why: "a directory path or a [storage.in] table, not this".to_string(),
359+ })
360+ }
361+ None => (default_storage(&database), None),
307362 };
308363
309364 let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());
@@ -355,6 +410,7 @@ impl Config {
355410 redirect_uri,
356411 },
357412 ignored,
413+ storage_in,
358414 defaulted,
359415 })
360416 }
@@ -443,8 +499,15 @@ fn complete(path: &Path, text: &str, base: &Path) {
443499 .collect();
444500 // `storage` has no fixed default to print: a file silent about it derives
445501 // the directory from where `database` points, so the completed line says
446- // the value this boot actually resolved rather than a placeholder.
447- if !mentions(text, "storage") {
502+ // the value this boot actually resolved rather than a placeholder. A
503+ // file that already speaks of the Files service (`[storage.in]`) is
504+ // left alone — appending a `storage` line would turn the key into two
505+ // shapes at once, and TOML refuses that file at the next boot.
506+ let speaks_of_in = toml::from_str::<Toml>(text)
507+ .ok()
508+ .and_then(|t| t.storage)
509+ .is_some_and(|storage| storage.is_table());
510+ if !speaks_of_in && !mentions(text, "storage") {
448511 // The same base `parse` resolves against, or the completed line would
449512 // point somewhere this boot never looks (config/ vs the directory
450513 // the app runs from).
@@ -456,11 +519,22 @@ fn complete(path: &Path, text: &str, base: &Path) {
456519 .as_deref()
457520 .map(|db| default_storage(&absolute(base, Path::new(db))))
458521 .unwrap_or_else(|| PathBuf::from("storage"));
522+ // The Files service block rides along commented: the token is a
523+ // secret minted once, and a file is never auto-completed into
524+ // holding one (in's r2-config rule). Reading the file is still how
525+ // a reader learns the feature exists.
459526 missing.push((
460527 "storage",
461528 format!(
462529 "# Where attachments live as files, created on boot.\n\
463- storage = {:?}\n",
530+ storage = {:?}\n\
531+ \n\
532+ # Attachments can live with the family's Files service instead\n\
533+ # of this disk. Uncomment, fill in the service key minted for\n\
534+ # iz, and remove the `storage` line above in the same breath —\n\
535+ # one key cannot be both a path and a table.\n\
536+ #[storage.in]\n\
537+ #token = \"\"\n",
464538 storage.display().to_string()
465539 ),
466540 ));
@@ -683,6 +757,60 @@ mod tests {
683757 );
684758 let _ = std::fs::remove_dir_all(&dir);
685759 }
760+ /// The Files service block: present, it names a token and the local
761+ /// attachments tree falls back beside the database — the file that
762+ /// carries the table cannot also carry the `storage` path.
763+ #[test]
764+ fn a_storage_in_table_names_the_service_key() {
765+ let config = Config::parse(
766+ &format!("database = \"iz.db\"\n[storage.in]\ntoken = \"tok-123\"\n{OIDC}"),
767+ Path::new("."),
768+ false,
769+ )
770+ .unwrap();
771+ assert_eq!(
772+ config.storage_in,
773+ Some(InStorage {
774+ token: "tok-123".to_string()
775+ })
776+ );
777+ assert!(config.storage.ends_with("storage"), "{:?}", config.storage);
778+ }
779+
780+ /// Absent, the feature does not exist: no default is invented, and the
781+ /// mode form will never offer it.
782+ #[test]
783+ fn a_file_without_storage_in_configures_nothing() {
784+ let config = Config::parse(
785+ &format!("database = \"iz.db\"\nstorage = \"files\"\n{OIDC}"),
786+ Path::new("."),
787+ false,
788+ )
789+ .unwrap();
790+ assert_eq!(config.storage_in, None);
791+ assert!(config.storage.ends_with("files"));
792+ }
793+
794+ /// An empty token is no token: the table alone does not half-configure
795+ /// the feature.
796+ #[test]
797+ fn an_empty_storage_in_token_configures_nothing() {
798+ let config = Config::parse(
799+ &format!("database = \"iz.db\"\n[storage.in]\ntoken = \"\"\n{OIDC}"),
800+ Path::new("."),
801+ false,
802+ )
803+ .unwrap();
804+ assert_eq!(config.storage_in, None);
805+ }
806+
807+ /// The written file teaches the feature by carrying the block, but only
808+ /// as a comment: a file is never auto-completed into holding a secret.
809+ #[test]
810+ fn the_written_template_carries_the_files_service_block_commented() {
811+ assert!(DEVELOPMENT_DEFAULTS.contains("#[storage.in]"));
812+ assert!(DEVELOPMENT_DEFAULTS.contains("#token = \"\""));
813+ }
686814
687815 /// A live connection that expires instantly is a reconnect loop, so the
688816 /// key is refused rather than silently corrected.
crates/iz-core/src/store/mod.rsmodified+110 -0
@@ -112,6 +112,80 @@ pub struct Attachment {
112112 pub size_bytes: u64,
113113 pub uploaded_by: String,
114114 pub uploaded_at: OffsetDateTime,
115+ /// Where the bytes live. `Stored` rows name no file on this machine: the
116+ /// bytes sit with the family's Files service, under this very id.
117+ pub remote: AttachmentWhere,
118+}
119+
120+/// Where one attachment's bytes are. Serialized lowercase, so a page that
121+/// carries the list sees the same words the column stores.
122+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
123+#[serde(rename_all = "lowercase")]
124+pub enum AttachmentWhere {
125+ /// Under `<storage>/attachments/<id>` on this machine.
126+ Local,
127+ /// With the Files service, under this row's own id.
128+ Stored,
129+}
130+
131+impl AttachmentWhere {
132+ pub fn as_str(&self) -> &'static str {
133+ match self {
134+ AttachmentWhere::Local => "local",
135+ AttachmentWhere::Stored => "stored",
136+ }
137+ }
138+
139+ pub fn parse(raw: &str) -> Option<Self> {
140+ match raw {
141+ "local" => Some(AttachmentWhere::Local),
142+ "stored" => Some(AttachmentWhere::Stored),
143+ _ => None,
144+ }
145+ }
146+}
147+
148+/// Which surface keeps the workspace's attachment bytes.
149+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150+#[serde(rename_all = "lowercase")]
151+pub enum StorageBackend {
152+ /// This machine's own storage tree, as it has always been.
153+ Local,
154+ /// The family's Files service, through the service key iz was minted.
155+ In,
156+}
157+
158+impl StorageBackend {
159+ pub fn as_str(&self) -> &'static str {
160+ match self {
161+ StorageBackend::Local => "local",
162+ StorageBackend::In => "in",
163+ }
164+ }
165+
166+ pub fn parse(raw: &str) -> Option<Self> {
167+ match raw {
168+ "local" => Some(StorageBackend::Local),
169+ "in" => Some(StorageBackend::In),
170+ _ => None,
171+ }
172+ }
173+}
174+
175+/// A file already on the Files service, waiting for its row: the bytes went
176+/// out under `id` before this was written, so the id is passed in rather
177+/// than minted here — a row born pointing at bytes that were never pushed
178+/// would serve nothing.
179+#[derive(Debug, Clone, PartialEq, Eq)]
180+pub struct NewRemoteAttachment<'a> {
181+ pub id: String,
182+ pub task_id: &'a str,
183+ pub comment_id: Option<&'a str>,
184+ pub file_name: &'a str,
185+ pub mime_type: &'a str,
186+ pub size_bytes: u64,
187+ pub uploaded_by: &'a str,
188+ pub at: OffsetDateTime,
115189 }
116190
117191 /// A file on its way into the store, bytes and all: the row goes to the
@@ -931,6 +1005,42 @@ pub trait Store: BoardReads + DetailReads + 'static {
9311005
9321006 /// Takes a file away for good. `false` when there was no such row.
9331007 async fn delete_attachment(&self, id: &str) -> Result<bool>;
1008+ // -- attachment storage backend -----------------------------------------
1009+
1010+ /// Writes which surface keeps the attachment bytes: this machine's own
1011+ /// tree, or the family's Files service. One save, one announcement —
1012+ /// the settings surfaces that show the choice re-read when it changes.
1013+ async fn set_storage_backend(&self, backend: StorageBackend) -> Result<()>;
1014+
1015+ /// The surface currently keeping the bytes. `Local` when the key was
1016+ /// never written — the default is the caller's, and the caller's
1017+ /// default is the machine, exactly as before this existed.
1018+ async fn storage_backend(&self) -> Result<StorageBackend>;
1019+
1020+ /// Writes the row for a file whose bytes were already pushed to the
1021+ /// Files service under `new.id`. No local file is touched: the row is
1022+ /// born stored, and nothing here can fail the bytes that are already
1023+ /// out.
1024+ async fn add_remote_attachment(&self, new: NewRemoteAttachment<'_>) -> Result<String>;
1025+
1026+ /// The rows still keeping their bytes on this machine, oldest first —
1027+ /// the migration drain's pick, and its progress meter.
1028+ async fn local_attachments(&self, limit: u64) -> Result<Vec<Attachment>>;
1029+
1030+ /// Marks a row stored and takes its local file with it — one call, so a
1031+ /// row can never be seen stored beside a file that is still there.
1032+ /// `false` when there was no such row.
1033+ async fn mark_attachment_stored(&self, id: &str) -> Result<bool>;
1034+
1035+ /// How many rows still keep their bytes on this machine.
1036+ async fn local_attachment_count(&self) -> Result<u64>;
1037+
1038+ /// Says, on the live channel, that the storage surface moved, without a
1039+ /// row changing. The migration's "nothing left to move" moment is not a
1040+ /// write — the last row's own write announced itself — but the card
1041+ /// watching the drain owes its reader one more refresh when the counter
1042+ /// it shows is gone.
1043+ async fn announce_storage(&self) -> Result<()>;
9341044
9351045 /// Writes the title, description, deadline and clock the detail screen
9361046 /// saved, and records one activity line per field that actually changed.
crates/iz-core/src/store/reconcile.rsmodified+18 -10
@@ -476,16 +476,24 @@ fn build_maps(
476476 // `bytes` is deliberately unmapped: the file's contents live under
477477 // the storage directory now, and `extract_blobs` wrote each one
478478 // there before this copy ran. The row keeps only the metadata.
479- columns: old_cols(&[
480- "id",
481- "task_id",
482- "comment_id",
483- "file_name",
484- "mime_type",
485- "size_bytes",
486- "uploaded_by",
487- "created_at",
488- ]),
479+ columns: vec![
480+ ("id", "old.id".into()),
481+ ("task_id", "old.task_id".into()),
482+ ("comment_id", "old.comment_id".into()),
483+ ("file_name", "old.file_name".into()),
484+ ("mime_type", "old.mime_type".into()),
485+ ("size_bytes", "old.size_bytes".into()),
486+ ("uploaded_by", "old.uploaded_by".into()),
487+ ("created_at", "old.created_at".into()),
488+ (
489+ // Remote storage is new with this schema: every carried row
490+ // kept its bytes on this machine, so every row arrives local
491+ // — the schema's own default, said out loud here because the
492+ // map is explicit on purpose.
493+ "remote_state",
494+ "'local'".to_string(),
495+ ),
496+ ],
489497 });
490498 maps.push(TableMap {
491499 name: "transition",
crates/iz-core/src/store/schema.rsmodified+1 -0
@@ -20,6 +20,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[
2020 include_str!("../../migrations/0004_no_photo_limit.sql"),
2121 include_str!("../../migrations/0005_settings.sql"),
2222 include_str!("../../migrations/0006_photo_version.sql"),
23+ include_str!("../../migrations/0007_attachment_remote.sql"),
2324 ];
2425
2526 /// The whole declared schema — every migration applied in order — as one
crates/iz-core/src/store/turso_store.rsmodified+140 -10
@@ -15,11 +15,11 @@ use ulid::Ulid;
1515
1616 use super::secret;
1717 use super::{
18- ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,
19- Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20- MailSend, MemberSync, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind,
21- SendState, SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User,
22- UserStats, Workspace,
18+ ActivityEvent, ActivityFilter, ActivityLine, Attachment, AttachmentWhere, Audience,
19+ ClaimedSend, CommentWritten, Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision,
20+ MailOutcome, MailRule, MailSend, MemberSync, NewAttachment, NewRemoteAttachment, NewSender,
21+ NewTask, Recipient, Result, SendKind, SendState, SenderCheck, SenderTest, StorageBackend,
22+ Store, StoreError, Tag, TaskCreated, Trigger, User, UserStats, Workspace,
2323 };
2424 use super::{ReconcileOptions, reconcile, schema, sniff};
2525 use crate::Role;
@@ -392,7 +392,10 @@ impl TursoStore {
392392 // text column, no file reads, and the common case is done here.
393393 let mut rows = conn
394394 .query(
395- &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"),
395+ &format!(
396+ "SELECT COUNT(*) FROM attachment \
397+ WHERE mime_type IN ({marks}) AND remote_state = 'local'"
398+ ),
396399 params_from_iter(buckets.iter().copied()),
397400 )
398401 .await
@@ -408,7 +411,8 @@ impl TursoStore {
408411 let mut rows = conn
409412 .query(
410413 &format!(
411- "SELECT id, mime_type FROM attachment WHERE mime_type IN ({marks})",
414+ "SELECT id, mime_type FROM attachment \
415+ WHERE mime_type IN ({marks}) AND remote_state = 'local'",
412416 marks = marks,
413417 ),
414418 params_from_iter(buckets.iter().copied()),
@@ -1232,6 +1236,7 @@ fn opt_stamp(row: &Row, idx: usize) -> Result<Option<OffsetDateTime>> {
12321236
12331237 /// One attachment row, in the column order every query above selects.
12341238 fn attachment_row(row: &Row) -> Result<Attachment> {
1239+ let remote = text(row, 8)?;
12351240 Ok(Attachment {
12361241 id: text(row, 0)?,
12371242 task_id: text(row, 1)?,
@@ -1241,9 +1246,13 @@ fn attachment_row(row: &Row) -> Result<Attachment> {
12411246 size_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
12421247 uploaded_by: text(row, 6)?,
12431248 uploaded_at: parse_stamp(&text(row, 7)?)?,
1249+ remote: AttachmentWhere::parse(&remote).ok_or_else(|| {
1250+ StoreError::Corrupt(format!(
1251+ "attachment wears an unknown remote state {remote:?}"
1252+ ))
1253+ })?,
12441254 })
12451255 }
1246-
12471256 fn text(row: &Row, idx: usize) -> Result<String> {
12481257 row.get::<String>(idx).map_err(backend)
12491258 }
@@ -2848,7 +2857,7 @@ impl Store for TursoStore {
28482857 let mut rows = conn
28492858 .query(
28502859 "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \
2851- uploaded_by, created_at FROM attachment \
2860+ uploaded_by, created_at, remote_state FROM attachment \
28522861 WHERE task_id = ?1 ORDER BY created_at, rowid",
28532862 params![task_id],
28542863 )
@@ -2866,7 +2875,7 @@ impl Store for TursoStore {
28662875 let mut rows = conn
28672876 .query(
28682877 "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \
2869- uploaded_by, created_at FROM attachment WHERE id = ?1",
2878+ uploaded_by, created_at, remote_state FROM attachment WHERE id = ?1",
28702879 params![id],
28712880 )
28722881 .await
@@ -2925,6 +2934,127 @@ impl Store for TursoStore {
29252934 Ok(gone > 0)
29262935 }
29272936
2937+ async fn set_storage_backend(&self, which: StorageBackend) -> Result<()> {
2938+ // The key is also named by `iz-web` (`STORAGE_BACKEND_KEY`), which
2939+ // reads the row directly only in tests; the trait is the real door.
2940+ const KEY: &str = "storage_backend";
2941+ let conn = self.conn.lock().await;
2942+ conn.execute(
2943+ "INSERT INTO setting (key, value) VALUES (?1, ?2) \
2944+ ON CONFLICT (key) DO UPDATE SET value = excluded.value",
2945+ params![KEY, which.as_str()],
2946+ )
2947+ .await
2948+ .map_err(backend)?;
2949+ drop(conn);
2950+ self.announce([Topic::Settings]);
2951+ Ok(())
2952+ }
2953+
2954+ async fn storage_backend(&self) -> Result<StorageBackend> {
2955+ Ok(self
2956+ .get_setting("storage_backend")
2957+ .await?
2958+ .and_then(|raw| StorageBackend::parse(&raw))
2959+ .unwrap_or(StorageBackend::Local))
2960+ }
2961+
2962+ async fn add_remote_attachment(&self, new: NewRemoteAttachment<'_>) -> Result<String> {
2963+ // The bytes are already on the Files service under `new.id`; the row
2964+ // is the only fact to write, born stored. No file lands here, so a
2965+ // failure here costs a row, never bytes.
2966+ let conn = self.conn.lock().await;
2967+ conn.execute(
2968+ "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
2969+ size_bytes, uploaded_by, created_at, remote_state) \
2970+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'stored')",
2971+ params![
2972+ new.id.clone(),
2973+ new.task_id,
2974+ new.comment_id,
2975+ new.file_name,
2976+ new.mime_type,
2977+ new.size_bytes as i64,
2978+ new.uploaded_by,
2979+ stamp(new.at)?
2980+ ],
2981+ )
2982+ .await
2983+ .map_err(backend)?;
2984+ drop(conn);
2985+ self.announce([Topic::Task(new.task_id.to_string())]);
2986+ Ok(new.id)
2987+ }
2988+
2989+ async fn local_attachments(&self, limit: u64) -> Result<Vec<Attachment>> {
2990+ let conn = self.conn.lock().await;
2991+ let mut rows = conn
2992+ .query(
2993+ "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \
2994+ uploaded_by, created_at, remote_state FROM attachment \
2995+ WHERE remote_state = 'local' ORDER BY created_at, rowid LIMIT ?1",
2996+ params![limit as i64],
2997+ )
2998+ .await
2999+ .map_err(backend)?;
3000+ let mut out = Vec::new();
3001+ while let Some(row) = rows.next().await.map_err(backend)? {
3002+ out.push(attachment_row(&row)?);
3003+ }
3004+ Ok(out)
3005+ }
3006+
3007+ async fn mark_attachment_stored(&self, id: &str) -> Result<bool> {
3008+ // Which task gained a stored file has to be read before the row
3009+ // moves, the way `delete_attachment` reads its owner: after the
3010+ // write there is nothing left to ask.
3011+ let owner = self
3012+ .one_row("SELECT task_id FROM attachment WHERE id = ?1", params![id])
3013+ .await?
3014+ .map(|row| row.get::<String>(0).map_err(backend))
3015+ .transpose()?;
3016+ let conn = self.conn.lock().await;
3017+ let moved = conn
3018+ .execute(
3019+ "UPDATE attachment SET remote_state = 'stored' WHERE id = ?1",
3020+ params![id],
3021+ )
3022+ .await
3023+ .map_err(backend)?;
3024+ drop(conn);
3025+ if moved > 0 {
3026+ // The row says stored, so the file must go — one call, so no
3027+ // reader between the two ever sees stored beside a file that is
3028+ // still there. Best-effort: a file that survives the unlink is
3029+ // orphaned bytes the boot sweep collects.
3030+ let _ = std::fs::remove_file(attachment_file(&self.storage, id));
3031+ if let Some(task_id) = owner {
3032+ self.announce([Topic::Task(task_id)]);
3033+ }
3034+ }
3035+ Ok(moved > 0)
3036+ }
3037+
3038+ async fn local_attachment_count(&self) -> Result<u64> {
3039+ let conn = self.conn.lock().await;
3040+ let mut rows = conn
3041+ .query(
3042+ "SELECT COUNT(*) FROM attachment WHERE remote_state = 'local'",
3043+ (),
3044+ )
3045+ .await
3046+ .map_err(backend)?;
3047+ match rows.next().await.map_err(backend)? {
3048+ Some(row) => count_of(&row),
3049+ None => Ok(0),
3050+ }
3051+ }
3052+
3053+ async fn announce_storage(&self) -> Result<()> {
3054+ self.announce([Topic::Settings]);
3055+ Ok(())
3056+ }
3057+
29283058 async fn save_task(
29293059 &self,
29303060 task_id: &str,
crates/iz-core/tests/store.rsmodified+246 -2
@@ -8,8 +8,8 @@ use std::path::PathBuf;
88
99 use iz_core::Role;
1010 use iz_core::store::{
11- Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, SendKind, SendState, Store,
12- StoreError, Trigger, TursoStore, User,
11+ Audience, Event, MailOutcome, MailRule, NewAttachment, NewRemoteAttachment, NewSender,
12+ SendKind, SendState, StorageBackend, Store, StoreError, Trigger, TursoStore, User,
1313 };
1414 use time::{Duration, OffsetDateTime};
1515 use ulid::Ulid;
@@ -8856,3 +8856,247 @@ async fn app_settings_round_trip_through_one_row_per_key() {
88568856 Some("https://iz.example".to_string())
88578857 );
88588858 }
8859+
8860+// -- attachment storage backend ----------------------------------------------
8861+
8862+/// An attachment pushed to the Files service before its row exists: the row
8863+/// is born stored, names no file on this machine, and answers the screen's
8864+/// reads like any other attachment.
8865+#[tokio::test]
8866+async fn a_remote_attachment_is_born_stored_without_a_local_file() {
8867+ let (scratch, workspace, admin) = workspace_with_admin().await;
8868+ let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await;
8869+ let id = Ulid::new().to_string();
8870+ let stored = scratch
8871+ .store
8872+ .add_remote_attachment(NewRemoteAttachment {
8873+ id: id.clone(),
8874+ task_id: &task,
8875+ comment_id: None,
8876+ file_name: "remote.png",
8877+ mime_type: "image/png",
8878+ size_bytes: 7,
8879+ uploaded_by: &admin,
8880+ at: OffsetDateTime::now_utc(),
8881+ })
8882+ .await
8883+ .unwrap();
8884+ assert_eq!(stored, id, "the row carries the id the push used");
8885+
8886+ let row = scratch.store.attachment(&id).await.unwrap().unwrap();
8887+ assert_eq!(row.remote, iz_core::store::AttachmentWhere::Stored);
8888+ assert_eq!(row.file_name, "remote.png");
8889+ assert_eq!(row.size_bytes, 7);
8890+ assert!(
8891+ !scratch
8892+ .storage
8893+ .join("attachments")
8894+ .join(&id)
8895+ .exists(),
8896+ "a stored row names no file on this machine"
8897+ );
8898+ assert_eq!(
8899+ scratch.store.attachments(&task).await.unwrap()[0].id,
8900+ id,
8901+ "the screen lists a stored row like any other"
8902+ );
8903+ assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 0);
8904+ let _ = std::fs::remove_dir_all(&scratch.dir);
8905+}
8906+
8907+/// The mode is an app-level fact with a default the caller owns: reads
8908+/// before any write answer Local, and the write is visible to the next read.
8909+#[tokio::test]
8910+async fn the_storage_backend_reads_back_what_was_written() {
8911+ let (scratch, _workspace, _admin) = workspace_with_admin().await;
8912+ assert_eq!(
8913+ scratch.store.storage_backend().await.unwrap(),
8914+ StorageBackend::Local,
8915+ "a store never told answers Local, as it always has"
8916+ );
8917+ scratch
8918+ .store
8919+ .set_storage_backend(StorageBackend::In)
8920+ .await
8921+ .unwrap();
8922+ assert_eq!(
8923+ scratch.store.storage_backend().await.unwrap(),
8924+ StorageBackend::In
8925+ );
8926+ scratch
8927+ .store
8928+ .set_storage_backend(StorageBackend::Local)
8929+ .await
8930+ .unwrap();
8931+ assert_eq!(
8932+ scratch.store.storage_backend().await.unwrap(),
8933+ StorageBackend::Local
8934+ );
8935+ let _ = std::fs::remove_dir_all(&scratch.dir);
8936+}
8937+
8938+/// Switching the backend is a settings save: every surface showing it is
8939+/// woken, exactly like `set_limits`.
8940+#[tokio::test]
8941+async fn setting_the_storage_backend_announces_settings() {
8942+ let (scratch, _workspace, _admin) = workspace_with_admin().await;
8943+ let mut rx = scratch.store.subscribe();
8944+ scratch
8945+ .store
8946+ .set_storage_backend(StorageBackend::In)
8947+ .await
8948+ .unwrap();
8949+ let seen: Vec<String> = {
8950+ let mut out = Vec::new();
8951+ while let Ok(change) = rx.try_recv() {
8952+ out.push(change.topic.kind().to_string());
8953+ }
8954+ out
8955+ };
8956+ assert!(
8957+ seen.iter().any(|kind| kind == "settings"),
8958+ "the switch did not announce Settings; heard {seen:?}"
8959+ );
8960+ let _ = std::fs::remove_dir_all(&scratch.dir);
8961+}
8962+
8963+/// The drain's pick: only local rows, oldest first, and no more than asked.
8964+#[tokio::test]
8965+async fn local_attachments_are_the_oldest_local_rows_up_to_the_limit() {
8966+ let (scratch, workspace, admin) = workspace_with_admin().await;
8967+ let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await;
8968+ let now = OffsetDateTime::now_utc();
8969+ let mut ids = Vec::new();
8970+ for (n, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
8971+ ids.push(
8972+ scratch
8973+ .store
8974+ .add_attachment(NewAttachment {
8975+ task_id: &task,
8976+ comment_id: None,
8977+ file_name: name,
8978+ mime_type: "image/png",
8979+ bytes: vec![0x89, b'0' + n as u8, 0x50, 0x4E, 0x47],
8980+ uploaded_by: &admin,
8981+ at: now + Duration::minutes(n as i64),
8982+ })
8983+ .await
8984+ .unwrap(),
8985+ );
8986+ }
8987+ // The middle one already moved; it must not appear in the drain's pick.
8988+ scratch
8989+ .store
8990+ .mark_attachment_stored(&ids[1])
8991+ .await
8992+ .unwrap()
8993+ ;
8994+
8995+ let picked = scratch.store.local_attachments(10).await.unwrap();
8996+ assert_eq!(
8997+ picked.iter().map(|a| a.id.clone()).collect::<Vec<_>>(),
8998+ vec![ids[0].clone(), ids[2].clone()],
8999+ "only local rows, in upload order"
9000+ );
9001+ assert_eq!(
9002+ scratch
9003+ .store
9004+ .local_attachments(1)
9005+ .await
9006+ .unwrap()
9007+ .iter()
9008+ .map(|a| a.id.clone())
9009+ .collect::<Vec<_>>(),
9010+ vec![ids[0].clone()],
9011+ "the limit is the drain's batch size"
9012+ );
9013+ assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 2);
9014+ let _ = std::fs::remove_dir_all(&scratch.dir);
9015+}
9016+
9017+/// Marking stored flips the row and takes the file with it in the same
9018+/// call, and answers false for a row that is not there.
9019+#[tokio::test]
9020+async fn marking_stored_moves_the_row_and_unlinks_the_file() {
9021+ let (scratch, workspace, admin) = workspace_with_admin().await;
9022+ let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await;
9023+ let id = scratch
9024+ .store
9025+ .add_attachment(NewAttachment {
9026+ task_id: &task,
9027+ comment_id: None,
9028+ file_name: "gone.png",
9029+ mime_type: "image/png",
9030+ bytes: vec![0x89, 0x50, 0x4E, 0x47],
9031+ uploaded_by: &admin,
9032+ at: OffsetDateTime::now_utc(),
9033+ })
9034+ .await
9035+ .unwrap();
9036+ let file = scratch.storage.join("attachments").join(&id);
9037+ assert!(file.is_file());
9038+
9039+ assert!(scratch.store.mark_attachment_stored(&id).await.unwrap());
9040+ assert_eq!(
9041+ scratch
9042+ .store
9043+ .attachment(&id)
9044+ .await
9045+ .unwrap()
9046+ .unwrap()
9047+ .remote,
9048+ iz_core::store::AttachmentWhere::Stored
9049+ );
9050+ assert!(!file.exists(), "the local bytes left with the row's state");
9051+ assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 0);
9052+
9053+ let missing = Ulid::new().to_string();
9054+ assert!(
9055+ !scratch
9056+ .store
9057+ .mark_attachment_stored(&missing)
9058+ .await
9059+ .unwrap(),
9060+ "a row that is not there was never marked"
9061+ );
9062+ let _ = std::fs::remove_dir_all(&scratch.dir);
9063+}
9064+
9065+/// A row the boot sniffer must leave alone: a stored row wears bytes on the
9066+/// Files service, not under `attachments/`, so the pass that refines generic
9067+/// mimes by reading those files must not even look at it — a zip-pptx
9068+/// planted stored keeps its generic mime across the boot.
9069+#[tokio::test]
9070+async fn the_boot_resniff_leaves_stored_rows_alone() {
9071+ let dir = std::env::temp_dir().join(format!("iz-resniff-{}", Ulid::new()));
9072+ std::fs::create_dir_all(&dir).unwrap();
9073+ let path = dir.join("iz.db").to_str().unwrap().to_string();
9074+ drop(TursoStore::open(&path, &dir.join("storage")).await.unwrap());
9075+ let db = turso::Builder::new_local(&path).build().await.unwrap();
9076+ let conn = db.connect().unwrap();
9077+ conn.execute(
9078+ "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \
9079+ uploaded_by, created_at, remote_state) \
9080+ VALUES ('FR', 'T1', 'deck.bin', 'application/zip', 4, 'U1', \
9081+ '2026-08-01T00:00:00Z', 'stored')",
9082+ turso::params![],
9083+ )
9084+ .await
9085+ .unwrap();
9086+ // The very bytes a local row would be refined on.
9087+ std::fs::write(
9088+ dir.join("storage").join("attachments").join("FR"),
9089+ zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]),
9090+ )
9091+ .unwrap();
9092+ drop(conn);
9093+ drop(db);
9094+
9095+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
9096+ assert_eq!(
9097+ store.attachment("FR").await.unwrap().unwrap().mime_type,
9098+ "application/zip",
9099+ "a stored row's mime is the push's own fact, not this disk's guess"
9100+ );
9101+ let _ = std::fs::remove_dir_all(&dir);
9102+}
crates/iz-web/Cargo.tomlmodified+12 -0
@@ -25,6 +25,18 @@ iz-core = { workspace = true, features = ["server"] }
2525 serde.workspace = true
2626 serde_json.workspace = true
2727 time.workspace = true
28+# Talks to the family's Files service for attachment storage: the machine
29+# API (multipart push, raw fetch, hard delete) behind iz's `[storage.in]`
30+# token. rustls, not OpenSSL, for the same reason the mailer is.
31+reqwest = { version = "0.13.4", default-features = false, features = [
32+ "rustls",
33+ "json",
34+ "multipart",
35+] }
36+# Mints the external id every pushed attachment carries: in's service
37+# routes are keyed by it, so it is minted here, before the push, not by
38+# the store.
39+ulid = { workspace = true }
2840 thiserror.workspace = true
2941 tokio = { workspace = true }
3042 async-trait = "0.1.92"
crates/iz-web/src/detail.rsmodified+15 -2
@@ -21,7 +21,7 @@ use iz_core::detail::{
2121 Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in,
2222 moment_label_with_seconds_in, parse_zone,
2323 };
24-use iz_core::store::{Store, StoreError, User};
24+use iz_core::store::{AttachmentWhere, Store, StoreError, User};
2525 use serde::{Deserialize, Serialize};
2626 use time::{Date, UtcOffset};
2727 use topcoat::Result;
@@ -974,7 +974,10 @@ async fn delete_task(cx: &Cx, Form(input): Form<TaskIdForm>) -> Redirect {
974974 /// [`delete_task`]'s soft one — an upload is not a fact worth an audit
975975 /// trail.
976976 /// Only the person who put it there, or an admin, may
977-/// take it away.
977+/// take it away. A row stored on the Files service takes its bytes from
978+/// in first: the remote copy only goes when in says it went, so an
979+/// unreachable service refuses the delete and the row stays, serviceable
980+/// again the moment in returns.
978981 #[route(POST "/api/delete_file")]
979982 async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
980983 let user = match require_user(cx).await {
@@ -992,6 +995,16 @@ async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
992995 return redirect(cx, Some(Refusal::Forbidden));
993996 }
994997
998+ if attachment.remote == AttachmentWhere::Stored {
999+ let Some((_, url)) = crate::storage::in_of(store.as_ref()).await else {
1000+ return redirect(cx, Some(Refusal::StorageUnavailable));
1001+ };
1002+ if let Err(problem) = crate::storage::client(cx).delete(&url, &attachment.id).await {
1003+ eprintln!("storage delete: {problem:?}");
1004+ return redirect(cx, Some(Refusal::StorageUnavailable));
1005+ }
1006+ }
1007+
9951008 store.delete_attachment(&input.file_id).await?;
9961009 let _ = store
9971010 .record_activity(
crates/iz-web/src/files.rsmodified+126 -17
@@ -15,9 +15,12 @@ use topcoat::router::{
1515 };
1616
1717 use iz_core::store::sniff::sniff;
18-use iz_core::store::{NewAttachment, Store, User};
18+use iz_core::store::{
19+ NewAttachment, NewRemoteAttachment, AttachmentWhere, StorageBackend, Store, User,
20+};
1921
2022 use crate::server::{Refusal, store, require_user};
23+use ulid::Ulid;
2124
2225 path_param!(id);
2326
@@ -218,6 +221,16 @@ fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {
218221 (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())
219222 }
220223
224+/// The 503 a stored attachment serves when the Files service cannot be
225+/// reached — one plain line, and never the 404, because the row exists.
226+fn service_unavailable() -> (StatusCode, HeaderMap, Vec<u8>) {
227+ (
228+ StatusCode::SERVICE_UNAVAILABLE,
229+ HeaderMap::new(),
230+ b"the Files service is unreachable\n".to_vec(),
231+ )
232+}
233+
221234 /// A single-range `Range: bytes=...` request resolved against `total` bytes,
222235 /// as `(start, end)` inclusive. `None` for anything this does not parse as
223236 /// exactly one `bytes=` range (a multi-range header included) — the caller
@@ -376,23 +389,47 @@ async fn upload(
376389 None => None,
377390 };
378391
379- let mut added: Result<(), iz_core::store::StoreError> = Ok(());
392+ // Which surface keeps the bytes is decided per request, after the
393+ // validation chain above — that chain (role, task, extension, streamed
394+ // size, sniff, label) is identical in both modes, because a file iz
395+ // would refuse on its own disk it refuses in the family's storage too.
396+ let backend = match store.storage_backend().await {
397+ Ok(backend) => backend,
398+ Err(_) => return Ok(back_to(&task_id, Some(Refusal::Unavailable))),
399+ };
400+ let mut added: Result<(), Refusal> = Ok(());
380401 for (file_name, bytes) in files {
381402 let label = label_of(&file_name);
382403 let mime_type = sniff(&bytes);
383404
384- added = store
385- .add_attachment(NewAttachment {
386- task_id: &task_id,
387- comment_id: comment_id.as_deref(),
388- file_name: &label,
389- mime_type,
390- bytes,
391- uploaded_by: &user.id,
392- at: OffsetDateTime::now_utc(),
393- })
394- .await
395- .map(|_| ());
405+ added = match backend {
406+ StorageBackend::Local => store
407+ .add_attachment(NewAttachment {
408+ task_id: &task_id,
409+ comment_id: comment_id.as_deref(),
410+ file_name: &label,
411+ mime_type,
412+ bytes,
413+ uploaded_by: &user.id,
414+ at: OffsetDateTime::now_utc(),
415+ })
416+ .await
417+ .map(|_| ())
418+ .map_err(|_| Refusal::NotFound),
419+ StorageBackend::In => {
420+ push_to_in(
421+ cx,
422+ store.as_ref(),
423+ &task_id,
424+ comment_id.as_deref(),
425+ &label,
426+ mime_type,
427+ bytes,
428+ &user.id,
429+ )
430+ .await
431+ }
432+ };
396433
397434 if added.is_ok() && comment_id.is_none() {
398435 let _ = store
@@ -410,10 +447,63 @@ async fn upload(
410447
411448 Ok(match added {
412449 Ok(_) => back_to(&task_id, None),
413- Err(_) => back_to(&task_id, Some(Refusal::NotFound)),
450+ Err(refusal) => back_to(&task_id, Some(refusal)),
414451 })
415452 }
416453
454+/// The In-mode half of the upload: the bytes go out under an id minted
455+/// here, and only when in says they landed does the row exist. Synchronous
456+/// passthrough on purpose — no upload queue — so a service that is not
457+/// there is a refusal the uploader can act on now. On the rare failure
458+/// after the push landed (the task gone mid-request, say) the push is
459+/// taken back best-effort; a leaked remote file is the accepted residual
460+/// if that take-back also fails.
461+async fn push_to_in(
462+ cx: &Cx,
463+ store: &dyn Store,
464+ task_id: &str,
465+ comment_id: Option<&str>,
466+ label: &str,
467+ mime_type: &str,
468+ bytes: Vec<u8>,
469+ uploader: &str,
470+) -> Result<(), Refusal> {
471+ let Some((_, url)) = crate::storage::in_of(store).await else {
472+ return Err(Refusal::StorageNotListed);
473+ };
474+ let external_id = Ulid::new().to_string();
475+ let size = bytes.len() as u64;
476+ let client = crate::storage::client(cx);
477+ if let Err(problem) = client
478+ .put(&url, &external_id, label, bytes, mime_type)
479+ .await
480+ {
481+ eprintln!("storage push: {problem:?}");
482+ return Err(match problem {
483+ crate::storage::StorageProblem::Quota => Refusal::StorageQuota,
484+ _ => Refusal::StorageUnavailable,
485+ });
486+ }
487+ if let Err(problem) = store
488+ .add_remote_attachment(NewRemoteAttachment {
489+ id: external_id.clone(),
490+ task_id,
491+ comment_id,
492+ file_name: label,
493+ mime_type,
494+ size_bytes: size,
495+ uploaded_by: uploader,
496+ at: OffsetDateTime::now_utc(),
497+ })
498+ .await
499+ {
500+ eprintln!("storage row after push: {problem}");
501+ let _ = client.delete(&url, &external_id).await;
502+ return Err(Refusal::NotFound);
503+ }
504+ Ok(())
505+}
506+
417507 /// Serves one attachment's bytes, or the same not-found a stranger to the
418508 /// task would see for a task that does not exist — never a `403`, which would
419509 /// confirm the id belongs to someone else's workspace.
@@ -433,8 +523,27 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
433523 if task_of(store.as_ref(), &user, &row.task_id).await.is_err() {
434524 return Ok(not_found());
435525 }
436- let Ok(Some(bytes)) = store.attachment_bytes(id).await else {
437- return Ok(not_found());
526+ // A stored row's bytes are not on this disk: they come back through
527+ // the Files service, and an unreachable service is a 503 — never the
528+ // not-found a stranger sees, because the row exists and this caller
529+ // has already cleared its task. A local row reads exactly as before.
530+ let bytes = match row.remote {
531+ AttachmentWhere::Local => match store.attachment_bytes(id).await {
532+ Ok(Some(bytes)) => bytes,
533+ _ => return Ok(not_found()),
534+ },
535+ AttachmentWhere::Stored => {
536+ let Some((_, url)) = crate::storage::in_of(store.as_ref()).await else {
537+ return Ok(service_unavailable());
538+ };
539+ match crate::storage::client(cx).fetch(&url, id).await {
540+ Ok(bytes) => bytes,
541+ Err(problem) => {
542+ eprintln!("storage fetch: {problem:?}");
543+ return Ok(service_unavailable());
544+ }
545+ }
546+ }
438547 };
439548
440549 let forced_download = query_params::<DownloadQuery>(cx)?.dl.is_some();
crates/iz-web/src/i18n.rsmodified+33 -0
@@ -131,6 +131,17 @@ pub enum Key {
131131 ConnectionLastEvent,
132132 ConnectionLastPass,
133133 ConnectionNever,
134+ StorageTitle,
135+ StorageService,
136+ StorageMode,
137+ StorageModeLocal,
138+ StorageModeIn,
139+ StorageConnection,
140+ StorageUnreachable,
141+ StorageLimit,
142+ StorageMigration,
143+ StorageLastProblem,
144+ StorageAbsent,
134145 EmailLabel,
135146 ThemeLabel,
136147 LightOption,
@@ -565,6 +576,28 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
565576 (ConnectionLastPass, Tr) => "Son tam geçiş",
566577 (ConnectionNever, En) => "never",
567578 (ConnectionNever, Tr) => "hiç",
579+ (StorageTitle, En) => "Storage",
580+ (StorageTitle, Tr) => "Depolama",
581+ (StorageService, En) => "Service",
582+ (StorageService, Tr) => "Hizmet",
583+ (StorageMode, En) => "Mode",
584+ (StorageMode, Tr) => "Mod",
585+ (StorageModeLocal, En) => "Local disk",
586+ (StorageModeLocal, Tr) => "Yerel disk",
587+ (StorageModeIn, En) => "Files (in)",
588+ (StorageModeIn, Tr) => "Dosyalar (in)",
589+ (StorageConnection, En) => "Connection",
590+ (StorageConnection, Tr) => "Bağlantı",
591+ (StorageUnreachable, En) => "Unreachable",
592+ (StorageUnreachable, Tr) => "Erişilemiyor",
593+ (StorageLimit, En) => "Limit",
594+ (StorageLimit, Tr) => "Limit",
595+ (StorageMigration, En) => "Migration",
596+ (StorageMigration, Tr) => "Aktarım",
597+ (StorageLastProblem, En) => "Last problem",
598+ (StorageLastProblem, Tr) => "Son sorun",
599+ (StorageAbsent, En) => "Not in the family",
600+ (StorageAbsent, Tr) => "Ailede değil",
568601 (EmailLabel, En) => "EMAIL",
569602 (EmailLabel, Tr) => "E-POSTA",
570603 (ThemeLabel, En) => "THEME",
crates/iz-web/src/layout.rsmodified+1 -1
@@ -239,7 +239,7 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: iz_core::Role, lang: Lan
239239 /// background beat in `main.rs`. Absent, empty, unparseable or a store
240240 /// that will not answer all read the same: an empty list, which renders
241241 /// no switcher. A page must not fail for the want of a wordmark.
242-async fn family_of(cx: &Cx) -> Vec<iz_client::FamilyService> {
242+pub(crate) async fn family_of(cx: &Cx) -> Vec<iz_client::FamilyService> {
243243 match store(cx).get_setting(FAMILY_KEY).await {
244244 Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(),
245245 _ => Vec::new(),
crates/iz-web/src/lib.rsmodified+1 -0
@@ -18,6 +18,7 @@ pub mod people;
1818 pub mod rules;
1919 pub mod server;
2020 pub mod settings;
21+pub mod storage;
2122 pub mod sheet;
2223 pub mod slides;
2324 pub mod smtp;
crates/iz-web/src/main.rsmodified+41 -1
@@ -143,6 +143,16 @@ async fn main() {
143143 config.oidc.client_id.clone(),
144144 config.oidc.client_secret.clone(),
145145 );
146+ // The family's Files service as a storage peer, beside the identity
147+ // peer above: the client carries the key `[storage.in]` named (and
148+ // when the deployment never configured one, the client still exists —
149+ // every call then refuses before the wire), and the health beside it
150+ // is what the Settings Storage card renders. The beat below keeps
151+ // both current.
152+ let storage_client = iz_web::storage::StorageClient::new(
153+ config.storage_in.as_ref().map(|storage| storage.token.clone()),
154+ );
155+ let storage_health = iz_web::storage::StorageHealth::new();
146156 // The engine is always built, because a sender can appear at any moment:
147157 // an admin fills the panel in and the next sweep sends what was held. It
148158 // holds one connection pool, rebuilt only when the settings behind it
@@ -173,6 +183,16 @@ async fn main() {
173183 health.clone(),
174184 ));
175185 tokio::spawn(directory_stream(store.clone(), directory.clone(), health.clone()));
186+ // The storage mirror's watchdog: follows the family to wherever in
187+ // lives now, keeps the card's facts current, and — while the
188+ // workspace's attachments live on in — drains the rows still on this
189+ // disk. First pass runs right away, so a fresh enablement starts
190+ // moving rows within the beat.
191+ tokio::spawn(storage_beat(
192+ store.clone(),
193+ storage_client.clone(),
194+ storage_health.clone(),
195+ ));
176196 // Told when the process is stopping, so the live streams end instead of
177197 // being waited out. See `iz_web::live::Shutdown`.
178198 let (stop, stopping) = tokio::sync::watch::channel(false);
@@ -190,7 +210,9 @@ async fn main() {
190210 )
191211 .app_context(store.clone())
192212 .app_context(directory)
193- .app_context(health)
213+ .app_context(health.clone())
214+ .app_context(storage_client.clone())
215+ .app_context(storage_health.clone())
194216 .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back)))
195217 .app_context(config.clone())
196218 .app_context(iz_web::live::LiveWindow(std::time::Duration::from_secs(
@@ -505,6 +527,24 @@ async fn directory_stream(
505527 }
506528 }
507529
530+/// The storage beat: [`iz_web::storage::storage_cycle`] over and over,
531+/// [`iz_web::storage::STORAGE_SECONDS`] apart. The cycle body is extracted
532+/// the way `mirror_directory` is, so a test can run one beat by hand; this
533+/// loop is only the alarm clock.
534+async fn storage_beat(
535+ store: Arc<dyn iz_core::store::Store>,
536+ client: iz_web::storage::StorageClient,
537+ health: iz_web::storage::StorageHealth,
538+) {
539+ loop {
540+ iz_web::storage::storage_cycle(&store, &client, &health).await;
541+ tokio::time::sleep(std::time::Duration::from_secs(
542+ iz_web::storage::STORAGE_SECONDS,
543+ ))
544+ .await;
545+ }
546+}
547+
508548 /// Waits for something to happen to the mail queue specifically.
509549 ///
510550 /// The channel carries every topic, and the sweep cares about one. Filtering
crates/iz-web/src/server.rsmodified+32 -0
@@ -37,6 +37,11 @@ pub fn config(cx: &Cx) -> iz_core::Config {
3737 /// value is a JSON array of `{key, name, url}` — exactly what im's
3838 /// `/family` served.
3939 pub const FAMILY_KEY: &str = "family";
40+/// The app-level `setting` key the storage mode form writes: which surface
41+/// keeps the attachment bytes, `"local"` or `"in"`. The store's
42+/// `set_storage_backend` owns the write and the announcement; the constant
43+/// is named here beside `FAMILY_KEY` because tests read the row directly.
44+pub const STORAGE_BACKEND_KEY: &str = "storage_backend";
4045
4146 /// The app-level `setting` key the public-address field on Settings
4247 /// writes: where a sign-out that started here sends the browser. Saving
@@ -410,6 +415,17 @@ pub enum Refusal {
410415 NoSuchMember,
411416 /// The address typed into the add-member form already has a row here.
412417 AlreadyMember,
418+ /// in refused the push: the bytes iz holds have spent the limit im set.
419+ StorageQuota,
420+ /// Storage through the Files service was asked for while `[storage.in]`
421+ /// holds no token — there is no key to speak with.
422+ StorageNotConfigured,
423+ /// The Files service is not in the family mirror, so there is no URL to
424+ /// push to. im's panel puts it there; iz does not guess.
425+ StorageNotListed,
426+ /// The Files service did not answer — down, mid-deploy, or the wire
427+ /// between. An upload is not queued for later; it is refused now.
428+ StorageUnavailable,
413429 Unavailable,
414430 }
415431
@@ -454,6 +470,10 @@ impl Refusal {
454470 Refusal::NotFound => "No such task.".to_string(),
455471 Refusal::NoSuchMember => "No such member.".to_string(),
456472 Refusal::AlreadyMember => "Already a member.".to_string(),
473+ Refusal::StorageNotConfigured => "The Files service has no key.".to_string(),
474+ Refusal::StorageNotListed => "The Files service is not in the family.".to_string(),
475+ Refusal::StorageUnavailable => "The Files service is unreachable.".to_string(),
476+ Refusal::StorageQuota => "The Files service is full.".to_string(),
457477 Refusal::Unavailable => "Something went wrong.".to_string(),
458478 }
459479 }
@@ -487,6 +507,10 @@ impl Refusal {
487507 Refusal::NotFound => "Böyle bir görev yok.".to_string(),
488508 Refusal::NoSuchMember => "Böyle bir üye yok.".to_string(),
489509 Refusal::AlreadyMember => "Zaten üye.".to_string(),
510+ Refusal::StorageNotConfigured => "Dosyalar hizmetinin anahtarı yok.".to_string(),
511+ Refusal::StorageNotListed => "Dosyalar hizmeti ailede değil.".to_string(),
512+ Refusal::StorageUnavailable => "Dosyalar hizmetine erişilemiyor.".to_string(),
513+ Refusal::StorageQuota => "Dosyalar hizmeti dolu.".to_string(),
490514 Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(),
491515 Refusal::BadLimit => {
492516 "Limit en az 1 MB, dosya başına en çok 500 MB olabilir.".to_string()
@@ -552,6 +576,10 @@ impl Refusal {
552576 "not-found" => Refusal::NotFound,
553577 "no-such-member" => Refusal::NoSuchMember,
554578 "already-member" => Refusal::AlreadyMember,
579+ "storage-quota" => Refusal::StorageQuota,
580+ "storage-not-configured" => Refusal::StorageNotConfigured,
581+ "storage-not-listed" => Refusal::StorageNotListed,
582+ "storage-unavailable" => Refusal::StorageUnavailable,
555583 "unavailable" => Refusal::Unavailable,
556584 _ => return None,
557585 })
@@ -596,6 +624,10 @@ impl Refusal {
596624 Refusal::NotFound => "not-found",
597625 Refusal::NoSuchMember => "no-such-member",
598626 Refusal::AlreadyMember => "already-member",
627+ Refusal::StorageNotConfigured => "storage-not-configured",
628+ Refusal::StorageNotListed => "storage-not-listed",
629+ Refusal::StorageUnavailable => "storage-unavailable",
630+ Refusal::StorageQuota => "storage-quota",
599631 Refusal::Unavailable => "unavailable",
600632 }
601633 }
crates/iz-web/src/settings.rsmodified+178 -9
@@ -21,7 +21,7 @@ use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route};
2121 use topcoat::view::view;
2222
2323 use iz_core::detail::ActivityKind;
24-use iz_core::store::{NewSender, SenderCheck, SenderTest, Store, StoreError, User};
24+use iz_core::store::{NewSender, SenderCheck, SenderTest, StorageBackend, Store, StoreError, User};
2525
2626 use crate::i18n::{Key, Lang, t};
2727 use crate::server::{PUBLIC_URL_KEY, Refusal, config, mail, require_admin, require_user, store};
@@ -142,7 +142,7 @@ fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec<u8>) {
142142 fn section_of_call(call: &str) -> &'static str {
143143 match call {
144144 "save_sender" | "send_test_mail" | "check_sender" => "outgoing",
145- "save_limits" => "limits",
145+ "save_limits" | "save_storage" => "limits",
146146 "save_public_url" => "server",
147147 "set_role" | "set_disabled" | "add_member" => "members",
148148 "send_message" => "message",
@@ -305,6 +305,58 @@ async fn save_limits(
305305 Ok(saved_or_refused("save_limits", refusal))
306306 }
307307
308+#[derive(serde::Deserialize)]
309+struct SaveStorageForm {
310+ backend: String,
311+}
312+
313+/// Switches which surface keeps attachment bytes. Admin-only, checked here
314+/// — the Limits panel is an admin's, but the route is the gate.
315+///
316+/// `in` is refused unless the whole road is there: a key named by
317+/// `[storage.in]`, and a family row pointing at the service. Anything
318+/// less would strand new uploads at a service this workspace cannot
319+/// reach; `local` always stands, because this disk is always here.
320+#[route(POST "/api/save_storage")]
321+async fn save_storage(
322+ cx: &Cx,
323+ Form(input): Form<SaveStorageForm>,
324+) -> Result<(StatusCode, HeaderMap, Vec<u8>)> {
325+ if let Err(refusal) = require_admin(cx).await {
326+ return Ok(saved_or_refused("save_storage", Some(refusal)));
327+ }
328+ let backend = match input.backend.as_str() {
329+ "local" => StorageBackend::Local,
330+ "in" => {
331+ if config(cx).storage_in.is_none() {
332+ return Ok(saved_or_refused(
333+ "save_storage",
334+ Some(Refusal::StorageNotConfigured),
335+ ));
336+ }
337+ let listed = crate::layout::family_of(cx)
338+ .await
339+ .iter()
340+ .any(|service| service.key == "in");
341+ if !listed {
342+ return Ok(saved_or_refused(
343+ "save_storage",
344+ Some(Refusal::StorageNotListed),
345+ ));
346+ }
347+ StorageBackend::In
348+ }
349+ _ => return Ok(saved_or_refused("save_storage", Some(Refusal::NotFound))),
350+ };
351+ match store(cx).set_storage_backend(backend).await {
352+ Ok(()) => Ok(saved_or_refused("save_storage", None)),
353+ Err(problem) => {
354+ eprintln!("store error: {problem}");
355+ Ok(saved_or_refused("save_storage", Some(Refusal::Unavailable)))
356+ }
357+ }
358+}
359+
308360 #[derive(serde::Deserialize)]
309361 struct SaveSenderForm {
310362 host: String,
@@ -942,6 +994,65 @@ async fn connection_card(cx: &Cx, lang: Lang) -> Result {
942994 }
943995 }
944996
997+/// The Storage card's body: where the family says the Files service is,
998+/// whether it answered the last beat, how full the account im limits
999+/// stands, and — while rows still move — how far the drain has come.
1000+/// Read from the mirror and the beat's health only; the key
1001+/// `[storage.in]` holds is not read here, so no render path can carry it.
1002+async fn storage_card(
1003+ cx: &Cx,
1004+ lang: Lang,
1005+ listed: Option<(String, String)>,
1006+ snap: &crate::storage::StorageSnapshot,
1007+ backend: StorageBackend,
1008+) -> Result {
1009+ let service_line = match &listed {
1010+ Some((name, url)) => format!("{name} · {url}"),
1011+ None => t(lang, Key::StorageAbsent).to_string(),
1012+ };
1013+ let (state_word, state_class) = if snap.connected {
1014+ (t(lang, Key::ConnectionConnected), "connection-on")
1015+ } else {
1016+ (t(lang, Key::StorageUnreachable), "connection-wait")
1017+ };
1018+ let limit_line = match (snap.used, snap.quota) {
1019+ (Some(used), Some(quota)) => format!(
1020+ "{} of {}",
1021+ crate::storage::human_bytes(used),
1022+ crate::storage::human_bytes(quota)
1023+ ),
1024+ _ => "—".to_string(),
1025+ };
1026+ let problem_line = match &snap.problem_word {
1027+ Some(word) => format!(
1028+ "{} ago · {}",
1029+ crate::directory::age_text(snap.problem_age),
1030+ word
1031+ ),
1032+ None => t(lang, Key::ConnectionNever).to_string(),
1033+ };
1034+ view! {
1035+ cx =>
1036+ <dl class="connection-facts">
1037+ <dt>(t(lang, Key::StorageService))</dt>
1038+ <dd class="connection-fact">(service_line)</dd>
1039+ <dt>(t(lang, Key::StorageConnection))</dt>
1040+ <dd class="connection-fact">
1041+ <span class=(format!("connection-dot {state_class}"))></span>
1042+ (state_word)
1043+ </dd>
1044+ <dt>(t(lang, Key::StorageLimit))</dt>
1045+ <dd class="connection-fact">(limit_line)</dd>
1046+ if backend == StorageBackend::In && let Some((moved, total)) = snap.migrating {
1047+ <dt>(t(lang, Key::StorageMigration))</dt>
1048+ <dd class="connection-fact">(format!("{moved} of {total}"))</dd>
1049+ }
1050+ <dt>(t(lang, Key::StorageLastProblem))</dt>
1051+ <dd class="connection-fact">(problem_line)</dd>
1052+ </dl>
1053+ }
1054+}
1055+
9451056 /// One row of the member list, as an admin may see it. Identity is im's to
9461057 /// vouch — the row carries no password and no link token, only what the
9471058 /// workspace itself decides: the role and whether the account is disabled.
@@ -1253,13 +1364,33 @@ async fn settings_page(cx: &Cx) -> Result {
12531364 let (profile_refusal, profile_saved) = call_state(query, "save_profile");
12541365 let (sender_refusal, sender_saved) = call_state(query, "save_sender");
12551366 let (test_refusal, _) = call_state(query, "send_test_mail");
1256- let (limits_refusal, limits_saved) = call_state(query, "save_limits");
1257- let (server_refusal, server_saved) = call_state(query, "save_public_url");
1258- let (role_refusal, _) = call_state(query, "set_role");
1259- let (disabled_refusal, _) = call_state(query, "set_disabled");
1260- let (add_refusal, add_saved) = call_state(query, "add_member");
1261- let member_refusal = role_refusal.or(disabled_refusal).or(add_refusal);
1262- let (message_refusal, message_saved) = call_state(query, "send_message");
1367+ let (limits_refusal, limits_saved) = call_state(query, "save_limits");
1368+ let (storage_refusal, storage_saved) = call_state(query, "save_storage");
1369+ let (server_refusal, server_saved) = call_state(query, "save_public_url");
1370+ let (role_refusal, _) = call_state(query, "set_role");
1371+ let (disabled_refusal, _) = call_state(query, "set_disabled");
1372+ let (add_refusal, add_saved) = call_state(query, "add_member");
1373+ let member_refusal = role_refusal.or(disabled_refusal).or(add_refusal);
1374+ let (message_refusal, message_saved) = call_state(query, "send_message");
1375+
1376+ // What the Storage panel renders: the surface the workspace currently
1377+ // keeps its bytes on, where the family mirror says the Files service
1378+ // is, and the storage beat's latest stand. The key `[storage.in]`
1379+ // holds is only asked about (`is_some`), never read into the page.
1380+ let storage = if administers && section == Section::Limits {
1381+ let backend = store(cx)
1382+ .storage_backend()
1383+ .await
1384+ .unwrap_or(StorageBackend::Local);
1385+ let listed = crate::layout::family_of(cx)
1386+ .await
1387+ .into_iter()
1388+ .find(|service| service.key == "in")
1389+ .map(|service| (service.name, service.url));
1390+ Some((backend, listed, crate::storage::health(cx).snapshot()))
1391+ } else {
1392+ None
1393+ };
12631394
12641395 view! {
12651396 cx =>
@@ -1558,6 +1689,44 @@ async fn settings_page(cx: &Cx) -> Result {
15581689 </section>
15591690 }
15601691
1692+ // The storage toggle and its card, beside the limits it
1693+ // answers to: which surface keeps the bytes, and how the
1694+ // Files service stands this beat. The `in` option only
1695+ // exists when `[storage.in]` named a key — a deployment
1696+ // without one is offered no road it cannot take.
1697+ if section == Section::Limits && let Some((backend, listed, snap)) = storage {
1698+ let local = backend == StorageBackend::Local;
1699+ <section class="panel" id="storage" data-tick="">
1700+ <div class="panel-head">
1701+ <h2 class="panel-title">(t(lang, Key::StorageTitle))</h2>
1702+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
1703+ </div>
1704+ <form method="post" action="/api/save_storage" class="panel-body">
1705+ <label class="field">
1706+ <span class="field-label">(t(lang, Key::StorageMode))</span>
1707+ <select class="field-input" name="backend">
1708+ <option value="local" selected=(local)>(t(lang, Key::StorageModeLocal))</option>
1709+ if config(cx).storage_in.is_some() {
1710+ <option value="in" selected=(!local)>(t(lang, Key::StorageModeIn))</option>
1711+ }
1712+ </select>
1713+ </label>
1714+ <div class="panel-foot">
1715+ if let Some(refusal) = &storage_refusal {
1716+ <span class="field-error">(refusal.message_in(lang))</span>
1717+ }
1718+ if storage_saved {
1719+ <span class="field-note">(t(lang, Key::Saved))</span>
1720+ }
1721+ <button class="primary" type="submit">(t(lang, Key::Save))</button>
1722+ </div>
1723+ </form>
1724+ <div class="panel-body">
1725+ (storage_card(cx, lang, listed, &snap, backend).await?)
1726+ </div>
1727+ </section>
1728+ }
1729+
15611730 if section == Section::Server {
15621731 <section class="panel" id="server">
15631732 <div class="panel-head">
crates/iz-web/src/storage.rsadded+479 -0
@@ -0,0 +1,479 @@
1+//! How attachments reach the family's Files service, and how the Settings
2+//! card sees that service: the storage client and its health, one file.
3+//!
4+//! The client is stateless by design — the base URL is a per-call argument,
5+//! because the family can move between beats and a URL captured at boot is
6+//! a URL that goes stale. The token is the one thing held: it comes from
7+//! `config/iz.toml` at boot and never leaves this struct except onto the
8+//! wire, as a Bearer header. It is never logged and never rendered.
9+//!
10+//! Every call carries a ceiling so a stalled service cannot park a request
11+//! or the drain forever: a connect ceiling on the client, a read ceiling
12+//! between body bytes, and a total ceiling on the small calls. A large push
13+//! or fetch takes as long as the bytes take — the ceilings bite silence,
14+//! not size.
15+
16+use std::sync::Arc;
17+use std::time::{Duration, Instant};
18+
19+use iz_core::store::Store;
20+use parking_lot::Mutex;
21+use topcoat::context::{Cx, try_app_context};
22+
23+// ---------------------------------------------------------------------------
24+// Client
25+// ---------------------------------------------------------------------------
26+
27+/// Why a storage call did not do what it was asked. `Quota` is in's own word
28+/// for "the limit im set is spent"; everything else is either the wire or a
29+/// refusal whose words only a log can use.
30+#[derive(Debug, Clone, PartialEq, Eq)]
31+pub enum StorageProblem {
32+ /// The service did not answer at all — down, mid-deploy, unreachable.
33+ Unreachable,
34+ /// in refused the push because the account's bytes are spent.
35+ Quota,
36+ /// The service answered with something unusable. The words are for the
37+ /// log and the card's "last problem", never for a page.
38+ Other(String),
39+}
40+
41+/// What in reports about iz's service account: the limit im set, and how
42+/// much of it the stored attachments hold.
43+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
44+pub struct Status {
45+ #[serde(default)]
46+ pub quota_bytes: u64,
47+ #[serde(default)]
48+ pub used_bytes: u64,
49+}
50+
51+#[derive(Clone)]
52+pub struct StorageClient {
53+ http: reqwest::Client,
54+ token: Option<String>,
55+}
56+
57+impl StorageClient {
58+ /// One client per process: it holds a connection pool. A `None` token is
59+ /// a deployment with no `[storage.in]` — the client exists (the handlers
60+ /// keep one shape) and every call refuses before touching the wire.
61+ pub fn new(token: Option<String>) -> Self {
62+ let http = reqwest::Client::builder()
63+ // A stalled connect is the one hang a total ceiling on the small
64+ // calls cannot cover; five seconds is generous for a LAN peer.
65+ .connect_timeout(Duration::from_secs(5))
66+ // Silence between body bytes, not total time: a half-sent 400 MB
67+ // attachment is a transfer, a half-sent nothing is a stall.
68+ .read_timeout(Duration::from_secs(10))
69+ .build()
70+ .unwrap_or_default();
71+ Self { http, token }
72+ }
73+
74+ fn bearer(&self) -> Option<&str> {
75+ self.token.as_deref()
76+ }
77+
78+ /// Is the service standing? `GET /healthz` is open — no key, no body to
79+ /// read — because a probe that needed the account could not tell "in is
80+ /// down" from "the key was rotated" without a second call.
81+ pub async fn probe(&self, url: &str) -> bool {
82+ let Ok(reply) = self
83+ .http
84+ .get(format!("{url}/healthz"))
85+ .timeout(Duration::from_secs(10))
86+ .send()
87+ .await
88+ else {
89+ return false;
90+ };
91+ reply.status().is_success()
92+ }
93+
94+ /// The account's bytes: the limit im set and what is held. `None` on a
95+ /// refused key, a service too old to know the route, or a dead wire —
96+ /// the card reads it as "no facts yet", the same quiet it starts with.
97+ pub async fn status(&self, url: &str) -> Option<Status> {
98+ let reply = self
99+ .http
100+ .get(format!("{url}/api/service/status"))
101+ .bearer_auth(self.bearer()?)
102+ .timeout(Duration::from_secs(10))
103+ .send()
104+ .await
105+ .ok()?;
106+ if !reply.status().is_success() {
107+ return None;
108+ }
109+ reply.json::<Status>().await.ok()
110+ }
111+
112+ /// Pushes one attachment. Idempotent by construction: in keys its rows
113+ /// by `external_id`, which is iz's own attachment id, so a retry after
114+ /// an unclear answer replaces the same bytes rather than doubling them.
115+ /// Answers in's file id — the same `external_id` it was handed.
116+ pub async fn put(
117+ &self,
118+ url: &str,
119+ external_id: &str,
120+ name: &str,
121+ bytes: Vec<u8>,
122+ mime: &str,
123+ ) -> Result<String, StorageProblem> {
124+ let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?;
125+ let part = reqwest::multipart::Part::bytes(bytes)
126+ .file_name(name.to_string())
127+ .mime_str(mime)
128+ .map_err(|_| StorageProblem::Other(format!("mime {mime:?}")))?;
129+ let form = reqwest::multipart::Form::new()
130+ .text("external_id", external_id.to_string())
131+ .text("name", name.to_string())
132+ .part("file", part);
133+ // No total ceiling on purpose: the widest attachment iz allows is
134+ // the widest push this makes, and the read ceiling above is what
135+ // stops a stalled body.
136+ let reply = self
137+ .http
138+ .post(format!("{url}/api/service/files"))
139+ .bearer_auth(token)
140+ .multipart(form)
141+ .send()
142+ .await
143+ .map_err(|_| StorageProblem::Unreachable)?;
144+ let body: serde_json::Value = reply
145+ .json()
146+ .await
147+ .map_err(|problem| StorageProblem::Other(problem.to_string()))?;
148+ if let Some(id) = body.get("ok").and_then(|id| id.as_str()) {
149+ return Ok(id.to_string());
150+ }
151+ match body.get("err").and_then(|err| err.as_str()) {
152+ Some("QuotaExceeded") => Err(StorageProblem::Quota),
153+ Some(other) => Err(StorageProblem::Other(other.to_string())),
154+ None => Err(StorageProblem::Other("unusable answer".into())),
155+ }
156+ }
157+
158+ /// Fetches one attachment's bytes back. The row exists in iz — an
159+ /// unreachable service is a problem to say so, never a not-found.
160+ pub async fn fetch(&self, url: &str, external_id: &str) -> Result<Vec<u8>, StorageProblem> {
161+ let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?;
162+ let reply = self
163+ .http
164+ .get(format!("{url}/api/service/file/{external_id}"))
165+ .bearer_auth(token)
166+ .send()
167+ .await
168+ .map_err(|_| StorageProblem::Unreachable)?;
169+ if !reply.status().is_success() {
170+ return Err(StorageProblem::Other(format!(
171+ "fetch answered {}",
172+ reply.status()
173+ )));
174+ }
175+ let bytes = reply
176+ .bytes()
177+ .await
178+ .map_err(|_| StorageProblem::Unreachable)?;
179+ Ok(bytes.to_vec())
180+ }
181+
182+ /// Takes one attachment away from in — a hard delete, no trash, the
183+ /// same hard delete iz's own store does.
184+ pub async fn delete(&self, url: &str, external_id: &str) -> Result<(), StorageProblem> {
185+ let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?;
186+ let reply = self
187+ .http
188+ .delete(format!("{url}/api/service/file/{external_id}"))
189+ .bearer_auth(token)
190+ .timeout(Duration::from_secs(10))
191+ .send()
192+ .await
193+ .map_err(|_| StorageProblem::Unreachable)?;
194+ if reply.status().is_success() {
195+ Ok(())
196+ } else {
197+ Err(StorageProblem::Other(format!(
198+ "delete answered {}",
199+ reply.status()
200+ )))
201+ }
202+ }
203+}
204+
205+/// The client `main.rs` registers beside the store; every handler that
206+/// branches on the backend reaches it through here.
207+pub fn client(cx: &Cx) -> &StorageClient {
208+ try_app_context::<StorageClient>(cx)
209+ .expect("the storage client was registered on the router")
210+}
211+
212+// ---------------------------------------------------------------------------
213+// Health
214+// ---------------------------------------------------------------------------
215+
216+/// The Files service's stand, as the Settings card renders it. The storage
217+/// beat writes; the page reads.
218+///
219+/// Deliberately dumb, like [`crate::directory::DirectoryHealth`] beside
220+/// which it lives: one mutex over plain fields, written a few times a
221+/// minute, read once a view. The token never comes near this struct, so the
222+/// render path cannot leak what it was never given.
223+#[derive(Clone, Default)]
224+pub struct StorageHealth(Arc<Mutex<Inner>>);
225+
226+#[derive(Default)]
227+struct Inner {
228+ /// Where the family says in lives, and what im named it — refreshed
229+ /// every beat, so a moved service is followed, not remembered.
230+ url: Option<String>,
231+ name: Option<String>,
232+ /// The last probe found a standing service.
233+ connected: bool,
234+ used: Option<u64>,
235+ quota: Option<u64>,
236+ /// The drain's counter: `(moved so far, total there were to move)`.
237+ /// `None` whenever no drain is running — before the first, and the
238+ /// moment the last row moved.
239+ migrating: Option<(u64, u64)>,
240+ last_ok: Option<Instant>,
241+ /// What went wrong, as a short machine word, and when.
242+ last_problem: Option<(Instant, String)>,
243+}
244+
245+/// One rendered view of [`StorageHealth`].
246+#[derive(Clone)]
247+pub struct StorageSnapshot {
248+ pub has_service: bool,
249+ pub connected: bool,
250+ pub used: Option<u64>,
251+ pub quota: Option<u64>,
252+ pub migrating: Option<(u64, u64)>,
253+ pub ok_age: Option<Duration>,
254+ pub problem_age: Option<Duration>,
255+ pub problem_word: Option<String>,
256+}
257+
258+impl StorageHealth {
259+ pub fn new() -> Self {
260+ Self::default()
261+ }
262+
263+ /// The family mirror named the service this beat.
264+ pub fn seen(&self, url: &str, name: &str) {
265+ let mut inner = self.0.lock();
266+ inner.url = Some(url.to_string());
267+ inner.name = Some(name.to_string());
268+ }
269+
270+ /// The family mirror has no row for in.
271+ pub fn unlisted(&self) {
272+ let mut inner = self.0.lock();
273+ inner.url = None;
274+ inner.name = None;
275+ inner.connected = false;
276+ }
277+
278+ /// The probe and the status both landed: the facts are current.
279+ pub fn reachable(&self, used: Option<u64>, quota: Option<u64>) {
280+ let mut inner = self.0.lock();
281+ inner.connected = true;
282+ inner.used = used;
283+ inner.quota = quota;
284+ inner.last_ok = Some(Instant::now());
285+ }
286+
287+ /// The probe or the status did not land. The word is the fact in
288+ /// shorthand — `unreachable`, `quota` — for the card's one line.
289+ pub fn problem(&self, word: &str) {
290+ let mut inner = self.0.lock();
291+ inner.connected = false;
292+ inner.last_problem = Some((Instant::now(), word.to_string()));
293+ }
294+
295+ /// A drain is running and moved one more row.
296+ pub fn migrating(&self, moved: u64, total: u64) {
297+ self.0.lock().migrating = Some((moved, total));
298+ }
299+
300+ /// The drain finished: the counter goes, and does not come back until a
301+ /// new batch of local rows earns a new total.
302+ pub fn drained(&self) {
303+ self.0.lock().migrating = None;
304+ }
305+
306+ pub fn snapshot(&self) -> StorageSnapshot {
307+ let inner = self.0.lock();
308+ let now = Instant::now();
309+ StorageSnapshot {
310+ has_service: inner.url.is_some(),
311+ connected: inner.connected,
312+ used: inner.used,
313+ quota: inner.quota,
314+ migrating: inner.migrating,
315+ ok_age: inner.last_ok.map(|at| now.saturating_duration_since(at)),
316+ problem_age: inner
317+ .last_problem
318+ .as_ref()
319+ .map(|(at, _)| now.saturating_duration_since(*at)),
320+ problem_word: inner.last_problem.as_ref().map(|(_, word)| word.clone()),
321+ }
322+ }
323+}
324+
325+/// The health `main.rs` registers on the router beside the client it
326+/// describes.
327+pub fn health(cx: &Cx) -> &StorageHealth {
328+ try_app_context::<StorageHealth>(cx).expect("the storage health was registered on the router")
329+}
330+
331+// ---------------------------------------------------------------------------
332+// The cycle
333+// ---------------------------------------------------------------------------
334+
335+/// How often the storage beat runs. Short enough that an enablement starts
336+/// moving rows within half a minute, long enough that the probe is a
337+/// glance, not a conversation.
338+pub const STORAGE_SECONDS: u64 = 30;
339+
340+/// How many rows one drain cycle pushes. The push is the expensive half, so
341+/// the batch is small: the beat is the retry, and four rows a beat drains a
342+/// real backlog quietly instead of monopolising the store.
343+const DRAIN_BATCH: u64 = 4;
344+
345+/// Where in sits in the family mirror: its human name and its URL, or
346+/// nothing when the mirror has no row for it. Read per use — the family can
347+/// move between beats.
348+pub async fn in_of(store: &dyn Store) -> Option<(String, String)> {
349+ let raw = store.get_setting(crate::server::FAMILY_KEY).await.ok()??;
350+ let family: Vec<iz_client::FamilyService> = serde_json::from_str(&raw).ok()?;
351+ let row = family.into_iter().find(|service| service.key == "in")?;
352+ Some((row.name, row.url))
353+}
354+
355+/// One pass of the storage beat: follow the family mirror, ask the service
356+/// how it stands, and — while the workspace's attachments live on in —
357+/// drain the rows still on this disk. The body is extracted from the loop
358+/// in `main.rs` the way `mirror_directory` is, so a test can run one beat
359+/// by hand.
360+pub async fn storage_cycle(
361+ store: &std::sync::Arc<dyn Store>,
362+ client: &StorageClient,
363+ health: &StorageHealth,
364+) {
365+ // 1. Where does the family say in is, this beat?
366+ let service = in_of(store.as_ref()).await;
367+ match &service {
368+ Some((name, url)) => health.seen(url, name),
369+ None => health.unlisted(),
370+ }
371+ let Some((_, url)) = service else {
372+ return;
373+ };
374+
375+ // 2. How does the service stand?
376+ if !client.probe(&url).await {
377+ health.problem("unreachable");
378+ return;
379+ }
380+ match client.status(&url).await {
381+ Some(status) => health.reachable(Some(status.used_bytes), Some(status.quota_bytes)),
382+ None => {
383+ health.problem("status");
384+ return;
385+ }
386+ }
387+
388+ // 3. Only a workspace switched to in drains; local mode leaves the
389+ // local rows exactly where they are.
390+ if store
391+ .storage_backend()
392+ .await
393+ .unwrap_or(iz_core::store::StorageBackend::Local)
394+ != iz_core::store::StorageBackend::In
395+ {
396+ return;
397+ }
398+ let count = store.local_attachment_count().await.unwrap_or(0);
399+ if count == 0 {
400+ return;
401+ }
402+
403+ // The total is captured when a drain starts and never re-captured
404+ // while one runs, so the counter only ever climbs to its end. A beat
405+ // that finds the counter standing picks up where it left off.
406+ let total = match health.snapshot().migrating {
407+ Some((_, total)) => total,
408+ None => count,
409+ };
410+
411+ let Ok(rows) = store.local_attachments(DRAIN_BATCH).await else {
412+ health.problem("store");
413+ return;
414+ };
415+ for row in rows {
416+ let Ok(Some(bytes)) = store.attachment_bytes(&row.id).await else {
417+ health.problem("store");
418+ return;
419+ };
420+ match client
421+ .put(&url, &row.id, &row.file_name, bytes, &row.mime_type)
422+ .await
423+ {
424+ Ok(_) => {}
425+ Err(StorageProblem::Quota) => {
426+ health.problem("quota");
427+ return;
428+ }
429+ Err(problem) => {
430+ health.problem(&problem_word(&problem));
431+ return;
432+ }
433+ }
434+ // The row flips and the file leaves this disk in one call; a push
435+ // that landed but a row that refuses is retried whole next beat —
436+ // in's push is idempotent by external id, so the replace is free.
437+ if store.mark_attachment_stored(&row.id).await.ok() != Some(true) {
438+ health.problem("store");
439+ return;
440+ }
441+ let remaining = store.local_attachment_count().await.unwrap_or(0);
442+ health.migrating(total.saturating_sub(remaining), total);
443+ }
444+
445+ // 4. The last row of the batch gone and nothing left: the counter the
446+ // card shows is gone with it, and every open admin page hears once.
447+ if store.local_attachment_count().await.unwrap_or(0) == 0 {
448+ health.drained();
449+ let _ = store.announce_storage().await;
450+ }
451+}
452+
453+/// A storage problem as the card's one word for it.
454+fn problem_word(problem: &StorageProblem) -> String {
455+ match problem {
456+ StorageProblem::Unreachable => "unreachable".to_string(),
457+ StorageProblem::Quota => "quota".to_string(),
458+ StorageProblem::Other(other) => other.chars().take(40).collect(),
459+ }
460+}
461+
462+/// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past
463+/// bytes so a quota line reads at a glance. Ported from in's settings panel,
464+/// whose usage lines this card's Limit row mirrors — the family renders
465+/// bytes one way.
466+pub fn human_bytes(bytes: u64) -> String {
467+ const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
468+ let mut value = bytes as f64;
469+ let mut unit = 0;
470+ while value >= 1024.0 && unit + 1 < UNITS.len() {
471+ value /= 1024.0;
472+ unit += 1;
473+ }
474+ if unit == 0 {
475+ format!("{bytes} {}", UNITS[unit])
476+ } else {
477+ format!("{value:.1} {}", UNITS[unit])
478+ }
479+}
crates/iz-web/tests/http.rsmodified+884 -32
@@ -273,6 +273,11 @@ struct App {
273273 store: Arc<dyn Store>,
274274 client: iz_client::Config,
275275 fake: FakeIm,
276+ /// The storage peer's client and health, registered exactly as
277+ /// `main.rs` registers them; `storage_cycle` tests run the beat by
278+ /// hand over these.
279+ storage_client: iz_web::storage::StorageClient,
280+ storage_health: iz_web::storage::StorageHealth,
276281 /// What the Settings Connection card renders: poked by hand in tests
277282 /// the way the mirror task pokes it in the process.
278283 health: iz_web::directory::DirectoryHealth,
@@ -283,15 +288,23 @@ struct App {
283288
284289 impl App {
285290 async fn build(mail: Mail) -> Self {
286- Self::build_with(mail, None, "").await
291+ Self::build_with(mail, None, "", None).await
287292 }
288-
293+
289294 /// Like `build`, but with the knobs a configured deployment has: the
290- /// family list mirrored from im — passed as the raw JSON the `setting`
291- /// row holds, so a test can also feed it a body that will not parse —
292- /// and the configured `base_url`. Building them in is what lets the
293- /// switcher and the sign-out handoff be asserted over real HTTP.
294- async fn build_with(mail: Mail, family: Option<String>, base_url: &str) -> Self {
295+ /// family list mirrored from im — passed as the raw JSON the `setting`
296+ /// row holds, so a test can also feed it a body that will not parse —
297+ /// and the configured `base_url`. Building them in is what lets the
298+ /// switcher and the sign-out handoff be asserted over real HTTP.
299+ ///
300+ /// `storage_in` is the `[storage.in]` token, when the deployment
301+ /// under test has one.
302+ async fn build_with(
303+ mail: Mail,
304+ family: Option<String>,
305+ base_url: &str,
306+ storage_in: Option<String>,
307+ ) -> Self {
295308 let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::new()));
296309 std::fs::create_dir_all(&dir).unwrap();
297310 let db = dir.join("iz.db");
@@ -309,6 +322,8 @@ impl App {
309322 .await
310323 .unwrap();
311324 }
325+ let storage_client = iz_web::storage::StorageClient::new(storage_in.clone());
326+ let storage_health = iz_web::storage::StorageHealth::new();
312327 let fake = FakeIm::spawn().await;
313328 let config = iz_core::Config {
314329 database: db,
@@ -323,6 +338,8 @@ impl App {
323338 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
324339 },
325340 ignored: Vec::new(),
341+ storage_in: storage_in
342+ .map(|token| iz_core::config::InStorage { token }),
326343 defaulted: false,
327344 };
328345 // The fallback half of the chain, built exactly as `main.rs` builds
@@ -358,7 +375,9 @@ impl App {
358375 "iz-test",
359376 "s3cr3t",
360377 ))
361- .app_context(health.clone())
378+ .app_context(health.clone())
379+ .app_context(storage_client.clone())
380+ .app_context(storage_health.clone())
362381 .app_context(iz_client::LogoutBack(Arc::new(
363382 iz_web::server::logout_back,
364383 )))
@@ -367,15 +386,17 @@ impl App {
367386 .app_context(iz_web::live::Shutdown(stopping))
368387 .app_context(mail)
369388 .build();
370- Self {
371- dir,
372- router,
373- store,
374- client,
375- fake,
376- health,
377- stop,
378- }
389+ Self {
390+ dir,
391+ router,
392+ store,
393+ client,
394+ fake,
395+ storage_client,
396+ storage_health,
397+ health,
398+ stop,
399+ }
379400 }
380401
381402 async fn open() -> Self {
@@ -414,6 +435,7 @@ impl App {
414435 redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(),
415436 },
416437 ignored: Vec::new(),
438+ storage_in: None,
417439 defaulted: false,
418440 };
419441 // The fallback half of the chain, built exactly as `main.rs` builds
@@ -428,6 +450,8 @@ impl App {
428450 cookie_key: [7u8; 32],
429451 };
430452 let health = iz_web::directory::DirectoryHealth::new();
453+ let storage_client = iz_web::storage::StorageClient::new(None);
454+ let storage_health = iz_web::storage::StorageHealth::new();
431455 let (stop, stopping) = tokio::sync::watch::channel(false);
432456 let router = iz_client::mount(
433457 Router::builder()
@@ -449,7 +473,9 @@ impl App {
449473 "iz-test",
450474 "s3cr3t",
451475 ))
452- .app_context(health.clone())
476+ .app_context(health.clone())
477+ .app_context(storage_client.clone())
478+ .app_context(storage_health.clone())
453479 .app_context(iz_client::LogoutBack(Arc::new(
454480 iz_web::server::logout_back,
455481 )))
@@ -458,17 +484,18 @@ impl App {
458484 .app_context(iz_web::live::Shutdown(stopping))
459485 .app_context(Mail::sending(engine))
460486 .build();
461- Self {
462- dir,
463- router,
464- store,
465- client,
466- fake,
467- health,
468- stop,
469- }
487+ Self {
488+ dir,
489+ router,
490+ store,
491+ client,
492+ fake,
493+ storage_client,
494+ storage_health,
495+ health,
496+ stop,
497+ }
470498 }
471-
472499 /// Mints a session cookie for an im identity, registering its claims on
473500 /// the fake — exactly what `/auth/callback` seals, without the browser
474501 /// dance. The local row is provisioned on the next request, the way a
@@ -9723,7 +9750,8 @@ async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() {
97239750
97249751 // A configured `base_url` is what the fallback says when nothing is
97259752 // stored — a deployment behind a proxy says its name once, in the file.
9726- let configured = App::build_with(Mail::silent(), None, "https://board.example").await;
9753+ let configured =
9754+ App::build_with(Mail::silent(), None, "https://board.example", None).await;
97279755 let raw = configured.get("/auth/logout", None).await;
97289756 let expected = format!(
97299757 "{}/logout?back={}",
@@ -9734,7 +9762,7 @@ async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() {
97349762
97359763 // A stored public address wins over the configured chain, and it reads
97369764 // per request: no restart between the save and the next sign-out.
9737- let stored = App::build_with(Mail::silent(), None, "https://stale.example").await;
9765+ let stored = App::build_with(Mail::silent(), None, "https://stale.example", None).await;
97389766 stored
97399767 .store
97409768 .set_setting(iz_web::server::PUBLIC_URL_KEY, "https://stored.example")
@@ -9760,7 +9788,7 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi
97609788 {\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"},\
97619789 {\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]"
97629790 .to_string();
9763- let app = App::build_with(Mail::silent(), Some(family), "").await;
9791+ let app = App::build_with(Mail::silent(), Some(family), "", None).await;
97649792 let board_admin = admin(&app).await;
97659793 let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
97669794 assert!(html.contains("wordmark-family"), "{html}");
@@ -9777,7 +9805,7 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi
97779805 // and a mirror that never arrived.
97789806 let alone = "[{\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"}]";
97799807 for broken in ["[".to_string(), "[]".to_string(), alone.to_string()] {
9780- let app = App::build_with(Mail::silent(), Some(broken), "").await;
9808+ let app = App::build_with(Mail::silent(), Some(broken), "", None).await;
97819809 let board_admin = admin(&app).await;
97829810 let html =
97839811 String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string();
@@ -9792,3 +9820,827 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi
97929820 "no mirror, no switcher: {plain}"
97939821 );
97949822 }
9823+
9824+// -- the Files service ------------------------------------------------------
9825+
9826+/// The Bearer key the storage tests name in `[storage.in]`: the fake in
9827+/// answers it and nothing else, so a call that arrives without it is a
9828+/// 401 the same way the real service answers an unknown key.
9829+const STORAGE_TOKEN: &str = "iz-storage-key";
9830+
9831+/// A fake in: the Files service's machine side over bare TCP, canned the
9832+/// way `iz_web::storage::StorageClient` speaks. Every `/api/service/*`
9833+/// call is recorded as `"<METHOD> <path>"` so a test can assert on the
9834+/// wire, not only on the rows; a push's file part is kept and served
9835+/// back by `GET /api/service/file/{id}`, so the fetch path reads the
9836+/// same bytes the push path wrote.
9837+struct FakeIn {
9838+ addr: std::net::SocketAddr,
9839+ calls: Arc<Mutex<Vec<String>>>,
9840+ files: Arc<Mutex<HashMap<String, Vec<u8>>>>,
9841+ refuse_quota: Arc<std::sync::atomic::AtomicBool>,
9842+ down: Arc<std::sync::atomic::AtomicBool>,
9843+}
9844+
9845+impl FakeIn {
9846+ async fn spawn() -> Self {
9847+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
9848+ let addr = listener.local_addr().unwrap();
9849+ let calls: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
9850+ let files: Arc<Mutex<HashMap<String, Vec<u8>>>> = Arc::new(Mutex::new(HashMap::new()));
9851+ let refuse_quota = Arc::new(std::sync::atomic::AtomicBool::new(false));
9852+ let down = Arc::new(std::sync::atomic::AtomicBool::new(false));
9853+ let log = calls.clone();
9854+ let store = files.clone();
9855+ let quota_flag = refuse_quota.clone();
9856+ let down_flag = down.clone();
9857+ tokio::spawn(async move {
9858+ loop {
9859+ let Ok((socket, _)) = listener.accept().await else {
9860+ return;
9861+ };
9862+ if down_flag.load(std::sync::atomic::Ordering::SeqCst) {
9863+ continue;
9864+ }
9865+ let log = log.clone();
9866+ let store = store.clone();
9867+ let quota_flag = quota_flag.clone();
9868+ let socket_down = down_flag.clone();
9869+ tokio::spawn(async move {
9870+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
9871+ let mut socket = socket;
9872+ let mut buf = vec![0u8; 8192];
9873+ let mut req = Vec::new();
9874+ // Same keep-alive loop as the fake im: closing after
9875+ // every answer races the client's pool.
9876+ loop {
9877+ let body_start = loop {
9878+ let Ok(n) = socket.read(&mut buf).await else {
9879+ return;
9880+ };
9881+ if n == 0 {
9882+ return;
9883+ }
9884+ req.extend_from_slice(&buf[..n]);
9885+ if let Some(end) = headers_end(&req) {
9886+ let head = String::from_utf8_lossy(&req[..end]).to_string();
9887+ let len = content_length(&head);
9888+ if req.len() >= end + len {
9889+ break end;
9890+ }
9891+ }
9892+ if req.len() > 2_000_000 {
9893+ return;
9894+ }
9895+ };
9896+ let head = String::from_utf8_lossy(&req[..body_start]).to_string();
9897+ // Down is per request, not per socket: a pooled
9898+ // connection that was alive when the service went
9899+ // down must stop answering too, the way the real
9900+ // service's sockets die mid-conversation.
9901+ if socket_down.load(std::sync::atomic::Ordering::SeqCst) {
9902+ return;
9903+ }
9904+ let first = head.lines().next().unwrap_or("").to_string();
9905+ let len = content_length(&head);
9906+ let body: Vec<u8> = req[body_start..body_start + len].to_vec();
9907+ req.drain(..body_start + len);
9908+ let (status, content_type, payload) =
9909+ storage_answer(&log, &store, &quota_flag, &head, &first, &body);
9910+ let response = format!(
9911+ "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n",
9912+ payload.len()
9913+ );
9914+ if socket.write_all(response.as_bytes()).await.is_err() {
9915+ return;
9916+ }
9917+ if socket.write_all(&payload).await.is_err() {
9918+ return;
9919+ }
9920+ }
9921+ });
9922+ }
9923+ });
9924+ Self {
9925+ addr,
9926+ calls,
9927+ files,
9928+ refuse_quota,
9929+ down,
9930+ }
9931+ }
9932+
9933+ fn url(&self) -> String {
9934+ format!("http://{}", self.addr)
9935+ }
9936+
9937+ /// The wire, in order: one `"<METHOD> <path>"` per service call.
9938+ fn calls(&self) -> Vec<String> {
9939+ self.calls.lock().clone()
9940+ }
9941+
9942+ /// Whether a push under this id is being held by the service.
9943+ fn holds(&self, id: &str) -> bool {
9944+ self.files.lock().contains_key(id)
9945+ }
9946+
9947+ fn refuse_quota(&self) {
9948+ self.refuse_quota
9949+ .store(true, std::sync::atomic::Ordering::SeqCst);
9950+ }
9951+
9952+ /// Stops answering — accepts and drops, which reads to the client as
9953+ /// the connection the storage ceilings are for.
9954+ fn set_down(&self) {
9955+ self.down
9956+ .store(true, std::sync::atomic::Ordering::SeqCst);
9957+ }
9958+}
9959+
9960+/// The fake in's one router: the probe is open, the machine side wants
9961+/// the Bearer key, and the four service routes answer the JSON shape the
9962+/// client parses. A push is kept under its `external_id` — pulled out of
9963+/// the multipart body by boundary, the way the real service's form
9964+/// parser would — so the fetch and delete routes have something real to
9965+/// work on.
9966+fn storage_answer(
9967+ log: &Arc<Mutex<Vec<String>>>,
9968+ files: &Arc<Mutex<HashMap<String, Vec<u8>>>>,
9969+ refuse_quota: &Arc<std::sync::atomic::AtomicBool>,
9970+ head: &str,
9971+ request_line: &str,
9972+ body: &[u8],
9973+) -> (&'static str, String, Vec<u8>) {
9974+ let mut parts = request_line.split_whitespace();
9975+ let method = parts.next().unwrap_or("");
9976+ let target = parts.next().unwrap_or("");
9977+ let path = target
9978+ .split_once('?')
9979+ .map(|(path, _)| path)
9980+ .unwrap_or(target);
9981+ if method == "GET" && path == "/healthz" {
9982+ return ("200 OK", "text/plain".to_string(), b"ok".to_vec());
9983+ }
9984+ let authed = head
9985+ .lines()
9986+ .filter_map(|line| line.split_once(':'))
9987+ .any(|(name, value)| {
9988+ name.trim().eq_ignore_ascii_case("authorization")
9989+ && value.trim() == format!("Bearer {STORAGE_TOKEN}")
9990+ });
9991+ if !authed {
9992+ return (
9993+ "401 Unauthorized",
9994+ "application/json".to_string(),
9995+ br#"{"err":"Unauthorized"}"#.to_vec(),
9996+ );
9997+ }
9998+ log.lock().push(format!("{method} {path}"));
9999+ match (method, path) {
10000+ ("GET", "/api/service/status") => (
10001+ "200 OK",
10002+ "application/json".to_string(),
10003+ br#"{"ok":true,"quota_bytes":10737418240,"used_bytes":1073741824}"#.to_vec(),
10004+ ),
10005+ ("POST", "/api/service/files") => {
10006+ if refuse_quota.load(std::sync::atomic::Ordering::SeqCst) {
10007+ return (
10008+ "200 OK",
10009+ "application/json".to_string(),
10010+ br#"{"err":"QuotaExceeded"}"#.to_vec(),
10011+ );
10012+ }
10013+ let Some(id) = multipart_field(body, head, "external_id") else {
10014+ return (
10015+ "400 Bad Request",
10016+ "application/json".to_string(),
10017+ br#"{"err":"NoExternalId"}"#.to_vec(),
10018+ );
10019+ };
10020+ let bytes = multipart_file(body, head);
10021+ files.lock().insert(id.clone(), bytes);
10022+ let answer = format!("{{\"ok\":\"{id}\"}}");
10023+ ("200 OK", "application/json".to_string(), answer.into_bytes())
10024+ }
10025+ ("GET", path) => match path.strip_prefix("/api/service/file/") {
10026+ Some(id) if !id.is_empty() => match files.lock().get(id) {
10027+ Some(bytes) => (
10028+ "200 OK",
10029+ "application/octet-stream".to_string(),
10030+ bytes.clone(),
10031+ ),
10032+ None => (
10033+ "404 Not Found",
10034+ "application/json".to_string(),
10035+ br#"{"err":"NotFound"}"#.to_vec(),
10036+ ),
10037+ },
10038+ _ => (
10039+ "404 Not Found",
10040+ "application/json".to_string(),
10041+ br#"{"err":"NotFound"}"#.to_vec(),
10042+ ),
10043+ },
10044+ ("DELETE", path) => {
10045+ if let Some(id) = path.strip_prefix("/api/service/file/") {
10046+ files.lock().remove(id);
10047+ }
10048+ (
10049+ "200 OK",
10050+ "application/json".to_string(),
10051+ br#"{"ok":true}"#.to_vec(),
10052+ )
10053+ }
10054+ _ => (
10055+ "404 Not Found",
10056+ "text/plain".to_string(),
10057+ Vec::new(),
10058+ ),
10059+ }
10060+}
10061+/// One text field out of a multipart body, by `name`. The parts are read
10062+/// line-wise — a part's headers carry `name="..."`, its value rides the
10063+/// lines after them — which is enough for the two fields the client
10064+/// writes; the content-type check is the proof this is a multipart body
10065+/// at all.
10066+fn multipart_field(body: &[u8], head: &str, name: &str) -> Option<String> {
10067+ let multipart = head.lines().any(|line| {
10068+ line.to_ascii_lowercase()
10069+ .starts_with("content-type: multipart/form-data")
10070+ });
10071+ if !multipart {
10072+ return None;
10073+ }
10074+ let marker = format!("name=\"{name}\"");
10075+ let mut in_part = false;
10076+ for part in body.split(|&b| b == b'\n') {
10077+ let text = String::from_utf8_lossy(part);
10078+ let line = text.trim_end_matches('\r');
10079+ if line.starts_with("--") {
10080+ in_part = false;
10081+ continue;
10082+ }
10083+ // The header line names the part; the value is the first line
10084+ // after the blank one that follows it.
10085+ if in_part {
10086+ if !line.is_empty() {
10087+ return Some(line.to_string());
10088+ }
10089+ } else if line.contains(&marker) && line.contains(':') {
10090+ in_part = true;
10091+ }
10092+ }
10093+ None
10094+}
10095+
10096+/// The file part's bytes out of a multipart body: everything between the
10097+/// `name="file"` part's blank line and the boundary that closes it.
10098+fn multipart_file(body: &[u8], head: &str) -> Vec<u8> {
10099+ let Some(boundary) = head
10100+ .lines()
10101+ .filter_map(|line| line.split_once(':'))
10102+ .find(|(field, _)| field.trim().eq_ignore_ascii_case("content-type"))
10103+ .and_then(|(_, value)| value.split("boundary=").nth(1).map(str::trim))
10104+ else {
10105+ return Vec::new();
10106+ };
10107+ let marker = format!("--{boundary}");
10108+ let needle = b"name=\"file\"";
10109+ let Some(at) = body.windows(needle.len()).position(|w| w == needle) else {
10110+ return Vec::new();
10111+ };
10112+ let after = &body[at..];
10113+ let Some(start) = after.windows(4).position(|w| w == b"\r\n\r\n") else {
10114+ return Vec::new();
10115+ };
10116+ let bytes = &after[start + 4..];
10117+ let end = bytes
10118+ .windows(marker.len())
10119+ .position(|w| w == marker.as_bytes())
10120+ .unwrap_or(bytes.len());
10121+ bytes[..end]
10122+ .strip_suffix(b"\r\n")
10123+ .unwrap_or(&bytes[..end])
10124+ .to_vec()
10125+}
10126+
10127+/// The family mirror holding a Files row at `url`: the JSON the `setting`
10128+/// row keeps, exactly the shape the beat stores.
10129+fn family_with_in(url: &str) -> String {
10130+ format!(
10131+ "[{{\"key\":\"in\",\"name\":\"Files\",\"url\":\"{url}\"}},\
10132+ {{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}}]"
10133+ )
10134+}
10135+
10136+/// An app whose deployment named a storage key, with a Files service in
10137+/// the family mirror to point at.
10138+async fn storage_app(fake: &FakeIn) -> App {
10139+ App::build_with(
10140+ Mail::silent(),
10141+ Some(family_with_in(&fake.url())),
10142+ "",
10143+ Some(STORAGE_TOKEN.to_string()),
10144+ )
10145+ .await
10146+}
10147+
10148+/// How many files sit in the storage tree's attachment directory: the
10149+/// honest count of what is still on this disk.
10150+fn local_file_count(app: &App) -> usize {
10151+ std::fs::read_dir(app.dir.join("storage").join("attachments"))
10152+ .map(|entries| entries.count())
10153+ .unwrap_or(0)
10154+}
10155+
10156+#[tokio::test]
10157+async fn an_upload_in_in_mode_lands_on_the_service_and_serves_from_it() {
10158+ let fake = FakeIn::spawn().await;
10159+ let app = storage_app(&fake).await;
10160+ let admin_cookie = admin(&app).await;
10161+ let column = first_column(&app).await;
10162+ let task = a_task(&app, &admin_cookie, &column, "Stored upload").await;
10163+
10164+ let saved = app
10165+ .post(
10166+ "/api/save_storage",
10167+ Some(&admin_cookie),
10168+ &[("backend", "in")],
10169+ )
10170+ .await;
10171+ assert_eq!(saved.status, StatusCode::SEE_OTHER, "{}", saved.body);
10172+ assert!(
10173+ saved
10174+ .location
10175+ .as_deref()
10176+ .unwrap_or_default()
10177+ .contains("saved=save_storage&section=limits"),
10178+ "{:?}",
10179+ saved.location
10180+ );
10181+
10182+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10183+ let answer = app
10184+ .post_multipart(
10185+ "/files",
10186+ Some(&admin_cookie),
10187+ &[("task_id", &task)],
10188+ Some(("spec.png", "image/png", &png)),
10189+ )
10190+ .await;
10191+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10192+ assert_eq!(
10193+ answer.location.as_deref(),
10194+ Some(format!("/?task={task}&tab=files").as_str())
10195+ );
10196+ assert!(
10197+ fake.calls().iter().any(|call| call == "POST /api/service/files"),
10198+ "the push never happened: {:?}",
10199+ fake.calls()
10200+ );
10201+
10202+ let rows = app.store.attachments(&task).await.unwrap();
10203+ assert_eq!(rows.len(), 1);
10204+ assert_eq!(rows[0].remote, iz_core::store::AttachmentWhere::Stored);
10205+ assert_eq!(local_file_count(&app), 0, "a local file was written anyway");
10206+ assert!(fake.holds(&rows[0].id));
10207+
10208+ let download = app
10209+ .get(&format!("/files/{}", rows[0].id), Some(&admin_cookie))
10210+ .await;
10211+ assert_eq!(download.status, StatusCode::OK);
10212+ assert_eq!(download.bytes, png);
10213+ assert_eq!(download.content_type.as_deref(), Some("image/png"));
10214+ assert!(
10215+ download
10216+ .disposition
10217+ .as_deref()
10218+ .unwrap_or_default()
10219+ .starts_with("inline;"),
10220+ "{:?}",
10221+ download.disposition
10222+ );
10223+ assert_eq!(
10224+ download.cache_control.as_deref(),
10225+ Some("private, max-age=31536000, immutable")
10226+ );
10227+ assert!(
10228+ fake.calls()
10229+ .iter()
10230+ .any(|call| call.starts_with("GET /api/service/file/")),
10231+ "the fetch never happened: {:?}",
10232+ fake.calls()
10233+ );
10234+}
10235+
10236+/// A Files service that is not there is refused in the moment, on every
10237+/// leg: the upload says so, the download is a 503 rather than a
10238+/// not-found, and the delete leaves the row exactly where it was.
10239+#[tokio::test]
10240+async fn a_down_files_service_refuses_uploads_downloads_and_deletes() {
10241+ let fake = FakeIn::spawn().await;
10242+ let app = storage_app(&fake).await;
10243+ let admin_cookie = admin(&app).await;
10244+ let column = first_column(&app).await;
10245+ let task = a_task(&app, &admin_cookie, &column, "Down service").await;
10246+ app.post(
10247+ "/api/save_storage",
10248+ Some(&admin_cookie),
10249+ &[("backend", "in")],
10250+ )
10251+ .await;
10252+
10253+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10254+ app.post_multipart(
10255+ "/files",
10256+ Some(&admin_cookie),
10257+ &[("task_id", &task)],
10258+ Some(("up.png", "image/png", &png)),
10259+ )
10260+ .await;
10261+ let rows = app.store.attachments(&task).await.unwrap();
10262+ assert_eq!(rows.len(), 1);
10263+ let stored = rows[0].id.clone();
10264+
10265+ fake.set_down();
10266+
10267+ let answer = app
10268+ .post_multipart(
10269+ "/files",
10270+ Some(&admin_cookie),
10271+ &[("task_id", &task)],
10272+ Some(("down.png", "image/png", &png)),
10273+ )
10274+ .await;
10275+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10276+ assert!(
10277+ answer
10278+ .location
10279+ .as_deref()
10280+ .unwrap_or_default()
10281+ .contains("refusal=storage-unavailable&on=upload_file"),
10282+ "{:?}",
10283+ answer.location
10284+ );
10285+ assert_eq!(app.store.attachments(&task).await.unwrap().len(), 1);
10286+
10287+ let download = app.get(&format!("/files/{stored}"), Some(&admin_cookie)).await;
10288+ assert_eq!(download.status, StatusCode::SERVICE_UNAVAILABLE);
10289+
10290+ let delete = app
10291+ .post(
10292+ "/api/delete_file",
10293+ Some(&admin_cookie),
10294+ &[("file_id", &stored)],
10295+ )
10296+ .await;
10297+ assert_eq!(delete.status, StatusCode::SEE_OTHER);
10298+ assert!(
10299+ delete.body.contains("StorageUnavailable"),
10300+ "the delete did not refuse: {}",
10301+ delete.body
10302+ );
10303+ assert!(
10304+ app.store.attachment(&stored).await.unwrap().is_some(),
10305+ "the row went while the service was down"
10306+ );
10307+}
10308+
10309+/// Deleting a stored row takes the remote copy first and only then the
10310+/// row: the service sees the DELETE, its copy is gone, and the task's
10311+/// file list is empty.
10312+#[tokio::test]
10313+async fn deleting_a_stored_row_takes_the_remote_copy_first() {
10314+ let fake = FakeIn::spawn().await;
10315+ let app = storage_app(&fake).await;
10316+ let admin_cookie = admin(&app).await;
10317+ let column = first_column(&app).await;
10318+ let task = a_task(&app, &admin_cookie, &column, "Remote delete").await;
10319+ app.post(
10320+ "/api/save_storage",
10321+ Some(&admin_cookie),
10322+ &[("backend", "in")],
10323+ )
10324+ .await;
10325+
10326+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10327+ app.post_multipart(
10328+ "/files",
10329+ Some(&admin_cookie),
10330+ &[("task_id", &task)],
10331+ Some(("gone.png", "image/png", &png)),
10332+ )
10333+ .await;
10334+ let rows = app.store.attachments(&task).await.unwrap();
10335+ assert_eq!(rows.len(), 1);
10336+ let stored = rows[0].id.clone();
10337+ assert!(fake.holds(&stored));
10338+
10339+ let answer = app
10340+ .post(
10341+ "/api/delete_file",
10342+ Some(&admin_cookie),
10343+ &[("file_id", &stored)],
10344+ )
10345+ .await;
10346+ assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body);
10347+ assert!(
10348+ !answer
10349+ .location
10350+ .as_deref()
10351+ .unwrap_or_default()
10352+ .contains("refusal="),
10353+ "{:?}",
10354+ answer.location
10355+ );
10356+ assert!(
10357+ fake.calls()
10358+ .iter()
10359+ .any(|call| call == &format!("DELETE /api/service/file/{stored}")),
10360+ "the remote copy was never taken: {:?}",
10361+ fake.calls()
10362+ );
10363+ assert!(!fake.holds(&stored));
10364+ assert!(
10365+ app.store.attachment(&stored).await.unwrap().is_none(),
10366+ "the row survived the delete"
10367+ );
10368+ assert!(app.store.attachments(&task).await.unwrap().is_empty());
10369+}
10370+
10371+/// The mode switch is an admin's, and `in` is only offered when the whole
10372+/// road is there: a key in the config and a family row naming the
10373+/// service. A member is refused; a keyless deployment is refused; a
10374+/// family without the service is refused; with both, the save lands.
10375+#[tokio::test]
10376+async fn save_storage_is_admin_only_and_refuses_a_road_that_is_not_there() {
10377+ // A member cannot switch the surface, on either value.
10378+ let fake = FakeIn::spawn().await;
10379+ let app = storage_app(&fake).await;
10380+ let admin_cookie = admin(&app).await;
10381+ let plain = member(&app, "memre@iz.sh", "Memre").await;
10382+ let answer = app
10383+ .post("/api/save_storage", Some(&plain), &[("backend", "local")])
10384+ .await;
10385+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10386+ // Settings routes carry the refusal on the redirect's query, not the
10387+ // body — the route has no hydrated caller to answer with a value.
10388+ assert_eq!(answer.body, "");
10389+ assert!(
10390+ answer
10391+ .location
10392+ .as_deref()
10393+ .unwrap_or_default()
10394+ .contains("refusal=forbidden&on=save_storage&section=limits"),
10395+ "{:?}",
10396+ answer.location
10397+ );
10398+
10399+ // No `[storage.in]` token: `in` is not a road this deployment can
10400+ // take, no matter what the family says.
10401+ let keyless = App::build_with(
10402+ Mail::silent(),
10403+ Some(family_with_in(&fake.url())),
10404+ "",
10405+ None,
10406+ )
10407+ .await;
10408+ let keyless_admin = admin(&keyless).await;
10409+ let answer = keyless
10410+ .post(
10411+ "/api/save_storage",
10412+ Some(&keyless_admin),
10413+ &[("backend", "in")],
10414+ )
10415+ .await;
10416+ assert!(
10417+ answer
10418+ .location
10419+ .as_deref()
10420+ .unwrap_or_default()
10421+ .contains("refusal=storage-not-configured&on=save_storage"),
10422+ "{:?}",
10423+ answer.location
10424+ );
10425+ // The form never offered it either.
10426+ let html = String::from_utf8_lossy(
10427+ &keyless
10428+ .get("/settings?section=limits", Some(&keyless_admin))
10429+ .await
10430+ .bytes,
10431+ )
10432+ .to_string();
10433+ assert!(!html.contains("value=\"in\""), "{html}");
10434+
10435+ // A family with no Files row: there is no URL to push to.
10436+ let unlisted = App::build_with(
10437+ Mail::silent(),
10438+ Some(
10439+ "[{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]"
10440+ .to_string(),
10441+ ),
10442+ "",
10443+ Some(STORAGE_TOKEN.to_string()),
10444+ )
10445+ .await;
10446+ let unlisted_admin = admin(&unlisted).await;
10447+ let answer = unlisted
10448+ .post(
10449+ "/api/save_storage",
10450+ Some(&unlisted_admin),
10451+ &[("backend", "in")],
10452+ )
10453+ .await;
10454+ assert!(
10455+ answer
10456+ .location
10457+ .as_deref()
10458+ .unwrap_or_default()
10459+ .contains("refusal=storage-not-listed&on=save_storage"),
10460+ "{:?}",
10461+ answer.location
10462+ );
10463+
10464+ // Both in place: the save lands, the store says so, and local stands
10465+ // as the way back.
10466+ let answer = app
10467+ .post(
10468+ "/api/save_storage",
10469+ Some(&admin_cookie),
10470+ &[("backend", "in")],
10471+ )
10472+ .await;
10473+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10474+ assert!(
10475+ answer
10476+ .location
10477+ .as_deref()
10478+ .unwrap_or_default()
10479+ .contains("saved=save_storage&section=limits"),
10480+ "{:?}",
10481+ answer.location
10482+ );
10483+ assert_eq!(
10484+ app.store.storage_backend().await.unwrap(),
10485+ iz_core::store::StorageBackend::In
10486+ );
10487+ let answer = app
10488+ .post(
10489+ "/api/save_storage",
10490+ Some(&admin_cookie),
10491+ &[("backend", "local")],
10492+ )
10493+ .await;
10494+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10495+ assert_eq!(
10496+ app.store.storage_backend().await.unwrap(),
10497+ iz_core::store::StorageBackend::Local
10498+ );
10499+}
10500+
10501+/// The Storage card carries the beat's facts — the family's name for the
10502+/// service, the connection's stand, the limit im set, the drain's count,
10503+/// the last problem — and never the key the calls speak with.
10504+#[tokio::test]
10505+async fn the_storage_card_shows_the_beats_facts_without_the_key() {
10506+ let fake = FakeIn::spawn().await;
10507+ let app = storage_app(&fake).await;
10508+ let admin_cookie = admin(&app).await;
10509+
10510+ app.storage_health.seen(&fake.url(), "Files");
10511+ app.storage_health
10512+ .reachable(Some(1024 * 1024 * 1024), Some(10 * 1024 * 1024 * 1024));
10513+ let html = String::from_utf8_lossy(
10514+ &app
10515+ .get("/settings?section=limits", Some(&admin_cookie))
10516+ .await
10517+ .bytes,
10518+ )
10519+ .to_string();
10520+ assert!(html.contains("id=\"storage\""), "{html}");
10521+ assert!(html.contains(&format!("Files · {}", fake.url())), "{html}");
10522+ assert!(html.contains("connection-on"), "{html}");
10523+ assert!(html.contains("Connected"), "{html}");
10524+ assert!(html.contains("1.0 GiB of 10.0 GiB"), "{html}");
10525+ assert!(html.contains("never"), "{html}");
10526+ assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}");
10527+
10528+ // The drain's count and the last problem, once the beat has both.
10529+ app.post(
10530+ "/api/save_storage",
10531+ Some(&admin_cookie),
10532+ &[("backend", "in")],
10533+ )
10534+ .await;
10535+ app.storage_health.problem("quota");
10536+ app.storage_health.migrating(2, 5);
10537+ let html = String::from_utf8_lossy(
10538+ &app
10539+ .get("/settings?section=limits", Some(&admin_cookie))
10540+ .await
10541+ .bytes,
10542+ )
10543+ .to_string();
10544+ assert!(html.contains("2 of 5"), "{html}");
10545+ assert!(html.contains("quota"), "{html}");
10546+ assert!(html.contains("connection-wait"), "{html}");
10547+ assert!(html.contains("Unreachable"), "{html}");
10548+ assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}");
10549+}
10550+
10551+/// One beat of the storage cycle, by hand: a workspace switched to in
10552+/// with rows still on this disk has them pushed, flipped to stored, and
10553+/// unlinked, and a service that has gone down since is a problem on the
10554+/// card rather than a stuck drain.
10555+#[tokio::test]
10556+async fn the_storage_beat_drains_local_rows_into_the_service() {
10557+ let fake = FakeIn::spawn().await;
10558+ let app = storage_app(&fake).await;
10559+ let admin_cookie = admin(&app).await;
10560+ let column = first_column(&app).await;
10561+ let task = a_task(&app, &admin_cookie, &column, "Drained rows").await;
10562+
10563+ // Two rows on local disk, the way every row was before the switch.
10564+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10565+ for name in ["one.png", "two.png"] {
10566+ app.post_multipart(
10567+ "/files",
10568+ Some(&admin_cookie),
10569+ &[("task_id", &task)],
10570+ Some((name, "image/png", &png)),
10571+ )
10572+ .await;
10573+ }
10574+ assert_eq!(local_file_count(&app), 2);
10575+ assert!(fake.calls().is_empty());
10576+
10577+ app.post(
10578+ "/api/save_storage",
10579+ Some(&admin_cookie),
10580+ &[("backend", "in")],
10581+ )
10582+ .await;
10583+ iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await;
10584+
10585+ let rows = app.store.attachments(&task).await.unwrap();
10586+ assert_eq!(rows.len(), 2);
10587+ assert!(
10588+ rows.iter()
10589+ .all(|row| row.remote == iz_core::store::AttachmentWhere::Stored),
10590+ "not every row drained"
10591+ );
10592+ assert_eq!(local_file_count(&app), 0, "the local files survived the drain");
10593+ assert!(rows.iter().all(|row| fake.holds(&row.id)));
10594+ let snap = app.storage_health.snapshot();
10595+ assert!(snap.connected);
10596+ assert_eq!(snap.migrating, None);
10597+
10598+ // The service gone: the beat says so on the card and nothing moves —
10599+ // there is nothing left to move — while the rows stay serviceable
10600+ // from wherever the service comes back.
10601+ fake.set_down();
10602+ iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await;
10603+ let snap = app.storage_health.snapshot();
10604+ assert!(!snap.connected);
10605+ assert_eq!(snap.problem_word.as_deref(), Some("unreachable"));
10606+}
10607+
10608+/// A full service refuses the push with its own word, and the upload
10609+/// carries it: nothing is stored, on either side.
10610+#[tokio::test]
10611+async fn a_full_service_refuses_the_upload_with_its_own_word() {
10612+ let fake = FakeIn::spawn().await;
10613+ let app = storage_app(&fake).await;
10614+ let admin_cookie = admin(&app).await;
10615+ let column = first_column(&app).await;
10616+ let task = a_task(&app, &admin_cookie, &column, "Full service").await;
10617+ app.post(
10618+ "/api/save_storage",
10619+ Some(&admin_cookie),
10620+ &[("backend", "in")],
10621+ )
10622+ .await;
10623+ fake.refuse_quota();
10624+
10625+ let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4];
10626+ let answer = app
10627+ .post_multipart(
10628+ "/files",
10629+ Some(&admin_cookie),
10630+ &[("task_id", &task)],
10631+ Some(("full.png", "image/png", &png)),
10632+ )
10633+ .await;
10634+ assert_eq!(answer.status, StatusCode::SEE_OTHER);
10635+ assert!(
10636+ answer
10637+ .location
10638+ .as_deref()
10639+ .unwrap_or_default()
10640+ .contains("refusal=storage-quota&on=upload_file"),
10641+ "{:?}",
10642+ answer.location
10643+ );
10644+ assert!(app.store.attachments(&task).await.unwrap().is_empty());
10645+ assert_eq!(local_file_count(&app), 0);
10646+}