//! A person's files, as this Mac handles them outside a source's pass (e2e //! rulings R6): the film and fetch importers' uploads, opening a file a phone //! sent sealed, and re-sealing the files an object still stores in the clear. //! //! Every file here is one of the person's kinds (`/photos|videos| //! books|music|films/…`). It is sealed on this Mac in the f1 format under its //! own key (`person_file_key` of the data key's file root and the object //! key), with the steady prefix, so the bytes are the ones a phone would send //! and every phone holding the data key opens them with no key in any row. //! //! A film's HLS folder is sealed file by file: the master and each playlist, //! every init section, segment and subtitle is its own f1 file under its own //! key (the key's name is in the AAD, so a segment moved onto another's key //! opens nothing). The playlists keep their relative names, so a phone plays //! the folder through its own loopback door, which opens each file as the //! player asks for it. The object stores and serves bytes and never a //! playlist it can read. //! //! RE-SEALING a file stored in the clear ([`reseal`]) never has a moment with //! neither copy: the clear bytes come down into `keep` first and are checked //! (against the sha256 the key names, where it names one), the sealed file //! replaces the clear one under the same key in one write, the sealed file is //! read back and opened and must hash to the clear copy, and only then is the //! local clear copy deleted. Stopped anywhere, a run starts again where it //! stopped: a key already stored sealed is counted and left. use std::collections::BTreeSet; use std::io::{Read, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use cotton_client::media::sealed::{self, SEALED_KINDS}; use cotton_core::seal::file::{self as f1, OpeningReader}; use serde::Serialize; use serde_json::Value; use sha2::{Digest, Sha256}; use crate::object::{is_person_key, ObjectClient, ObjectError}; use crate::patience::Patience; /// The tables whose rows name a person's files. pub const FILE_TABLES: &[&str] = &["photo", "video", "book", "song", "music_album", "film", "film_season", "film_episode", "podcast", "episode", "fetch", "person", "record_group", "media"]; /// One file to send: where it is on this Mac and the key it goes under. #[derive(Debug, Clone, serde::Deserialize)] pub struct Item { pub key: String, pub path: PathBuf, #[serde(default)] pub content_type: Option, /// Put it sealed even where the key holds a sealed file already (a /// film's master named afresh with its ladder); absent, a held key is left. #[serde(default)] pub replace: bool, } /// What became of one key. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Outcome { pub key: String, /// `sent`, `held` (stored sealed already), `sealed` (re-sealed and /// verified), `clear` (a dry run's count), `missing`, `corrupt` (the clear /// bytes are not the ones the key names: left alone), `failed`. pub state: &'static str, /// Bytes: sent, or the stored size of a counted file. pub bytes: u64, #[serde(skip_serializing_if = "Option::is_none")] pub why: Option, } impl Outcome { fn of(key: &str, state: &'static str, bytes: u64) -> Outcome { Outcome { key: key.to_string(), state, bytes, why: None } } fn failed(key: &str, why: impl Into) -> Outcome { Outcome { key: key.to_string(), state: "failed", bytes: 0, why: Some(why.into()) } } } fn not_a_persons(key: &str) -> String { format!("{key} is not one of a person's files ({})", SEALED_KINDS.join(", ")) } /// Send every item sealed, `threads` at a time, in the order given within a /// thread; the answers come back in the items' order. A key that is not a /// person's is refused, never sent open. An object that stops answering for a /// while is waited for ([`Patience`]). pub fn put_listed(object: &ObjectClient, items: &[Item], threads: usize) -> Vec { put_listed_patiently(object, items, threads, &Patience::default()) } /// The keys of `items` the object already stores sealed, asked in batches so a /// landing started again costs a few calls and not one per file. Empty when /// the object cannot say: each file is then asked about as it is sent. fn already_sealed(object: &ObjectClient, items: &[Item], patience: &Patience) -> BTreeSet { let keys: Vec = items.iter().filter(|item| !item.replace && is_person_key(&item.key)).map(|item| item.key.clone()).collect(); if keys.is_empty() { return BTreeSet::new(); } patience.run(|| object.media_held_sealed(&keys)).ok().flatten().unwrap_or_default() } /// [`put_listed`], waiting on the `patience` given. pub fn put_listed_patiently(object: &ObjectClient, items: &[Item], threads: usize, patience: &Patience) -> Vec { put_listed_telling(object, items, threads, patience, &|_| {}) } /// [`put_listed_patiently`], each outcome told to `done` as its file finishes, /// so a long send can say how far it is. pub fn put_listed_telling(object: &ObjectClient, items: &[Item], threads: usize, patience: &Patience, done: &(dyn Fn(&Outcome) + Sync)) -> Vec { let held = already_sealed(object, items, patience); let next = std::sync::atomic::AtomicUsize::new(0); let out = std::sync::Mutex::new(vec![None; items.len()]); std::thread::scope(|scope| { for _ in 0..threads.clamp(1, 8) { scope.spawn(|| loop { let at = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let Some(item) = items.get(at) else { return }; let outcome = if held.contains(&item.key) { Outcome::of(&item.key, "held", 0) } else { put_one(object, item, patience) }; done(&outcome); out.lock().unwrap_or_else(|p| p.into_inner())[at] = Some(outcome); }); } }); out.into_inner().unwrap_or_else(|p| p.into_inner()).into_iter().flatten().collect() } fn put_one(object: &ObjectClient, item: &Item, patience: &Patience) -> Outcome { if !is_person_key(&item.key) { return Outcome::failed(&item.key, not_a_persons(&item.key)); } let size = match std::fs::metadata(&item.path) { Ok(meta) => meta.len(), Err(error) => return Outcome::failed(&item.key, format!("{}: {error}", item.path.display())), }; match patience.run(|| object.put_person_file_as(&item.key, &item.path, size, item.content_type.as_deref().unwrap_or("application/octet-stream"), item.replace)) { Ok(0) => Outcome::of(&item.key, "held", 0), Ok(sent) => Outcome::of(&item.key, "sent", sent), Err(error) => Outcome::failed(&item.key, error.to_string()), } } /// The file stored under `key`, opened into `dest`: a sealed file with the /// key this Mac derives (or the one a file sealed at arrival carries), a clear /// one only when its bytes are the ones its key names. Answers its plain size. pub fn fetch_opened(object: &ObjectClient, key: &str, dest: &Path) -> Result { let files = object.person_files().ok_or("seal_key_missing: this Mac holds no data key")?; if !files.seals(key) { return Err(not_a_persons(key)); } let stored = object.media_stored(key).map_err(|e| e.to_string())?.ok_or_else(|| format!("{key}: the object holds no such file"))?; let raw = dest.with_extension("sealed-part"); let mut out = std::fs::File::create(&raw).map_err(|e| format!("{}: {e}", raw.display()))?; let fetched = object.get_media_to(key, stored.size, &mut out).map_err(|e| e.to_string()); drop(out); if let Err(error) = fetched { let _ = std::fs::remove_file(&raw); return Err(error); } // A clear file from before opens with no key held (AVATAR SEAL 2 (2)); a sealed one waits for the key. files.open_fetched(key, &raw, dest).map_err(|refusal| refusal.message)?; std::fs::metadata(dest).map(|meta| meta.len()).map_err(|e| e.to_string()) } /// One file to bring down opened (`seal-files get --list`): its key, and where it lands. #[derive(Debug, Clone, serde::Deserialize)] pub struct Fetch { pub key: String, pub out: PathBuf, } /// Every item brought down opened, `threads` at a time (`film:open`'s pieces: /// one device sign-in for thousands of files, never one each). A file already /// at its `out` is `had` and left, so a stopped run starts again where it /// stopped; any other lands at `.part` and is renamed when whole (`got`); /// a try that fails is tried again after `backoff`, doubling, `tries` in all, /// then `failed` with its reason and nothing left at `out`. Each outcome is /// told to `done` as it finishes; the answers come back in the items' order. pub fn fetch_listed(object: &ObjectClient, items: &[Fetch], threads: usize, tries: u32, backoff: std::time::Duration, done: &(dyn Fn(&Outcome) + Sync)) -> Vec { let next = AtomicUsize::new(0); let out = std::sync::Mutex::new(vec![None; items.len()]); std::thread::scope(|scope| { for _ in 0..threads.clamp(1, 16) { scope.spawn(|| loop { let at = next.fetch_add(1, Ordering::SeqCst); let Some(item) = items.get(at) else { return }; let outcome = fetch_one(object, item, tries.max(1), backoff); done(&outcome); out.lock().unwrap_or_else(|p| p.into_inner())[at] = Some(outcome); }); } }); out.into_inner().unwrap_or_else(|p| p.into_inner()).into_iter().flatten().collect() } fn fetch_one(object: &ObjectClient, item: &Fetch, tries: u32, backoff: std::time::Duration) -> Outcome { if let Ok(meta) = std::fs::metadata(&item.out) { return Outcome::of(&item.key, "had", meta.len()); } let mut name = item.out.clone().into_os_string(); name.push(".part"); let part = PathBuf::from(name); let mut why = String::new(); for attempt in 0..tries { if attempt > 0 { std::thread::sleep(backoff * 2u32.saturating_pow(attempt - 1)); } match fetch_opened(object, &item.key, &part) { Ok(bytes) => { if let Err(error) = std::fs::rename(&part, &item.out) { why = format!("{}: {error}", item.out.display()); continue; } return Outcome::of(&item.key, "got", bytes); } Err(error) => { let _ = std::fs::remove_file(&part); why = error; // A file that is not a person's, or one the object does not hold, is not there on a second try either. if why.contains("not one of a person's files") || why.contains("the object holds no such file") { break; } } } } Outcome::failed(&item.key, why) } // ── which files a person holds ────────────────────────────────────────────── /// Every string in `value` that names one of `database_id`'s files of `kinds`. fn keys_in(value: &Value, database_id: &str, kinds: &[String], out: &mut BTreeSet) { match value { Value::String(text) => { if sealed::is_person_file(database_id, text) && kinds.iter().any(|kind| text.split('/').nth(1) == Some(kind.as_str())) { out.insert(text.clone()); // A picture's renditions, drawn by a device and stored beside it. if let Some((stem, _)) = text.rsplit_once('.').filter(|_| text.split('/').nth(1) == Some("photos")) { if stem.rsplit('/').next().is_some_and(|name| name.len() == 64) { out.insert(format!("{stem}.t256.jpg")); out.insert(format!("{stem}.d1600.jpg")); } } } else if text.starts_with('{') || text.starts_with('[') { // A list or object a column keeps as text (a message's media). if let Ok(inner) = serde_json::from_str::(text) { keys_in(&inner, database_id, kinds, out); } } } Value::Array(items) => items.iter().for_each(|item| keys_in(item, database_id, kinds, out)), Value::Object(map) => map.values().for_each(|item| keys_in(item, database_id, kinds, out)), _ => {} } } /// The names a playlist points at, relative to its own folder. pub fn playlist_names(text: &str) -> Vec { let mut names = Vec::new(); for line in text.lines().map(str::trim).filter(|line| !line.is_empty()) { if let Some(rest) = line.strip_prefix('#') { // `URI="…"` in a tag: a rendition's playlist, an init section, a key. let mut at = rest; while let Some(found) = at.find("URI=\"") { let tail = &at[found + 5..]; let Some(end) = tail.find('"') else { break }; names.push(tail[..end].to_string()); at = &tail[end..]; } } else { names.push(line.to_string()); } } names.retain(|name| !name.contains("://") && !name.starts_with('/') && !name.split('/').any(|part| part == "..")); names } /// The files of the HLS folder whose master (or playlist) is `key`, the /// playlist itself left out: read through, playlist by playlist. fn folder_of(object: &ObjectClient, key: &str, seen: &mut BTreeSet) -> Result<(), String> { let Some(stored) = object.media_stored(key).map_err(|e| e.to_string())? else { return Ok(()) }; let mut bytes = Vec::new(); object.get_media_to(key, stored.size, &mut bytes).map_err(|e| e.to_string())?; let text = if stored.sealed() { let fk = object.person_file_key(key).map_err(|e| e.to_string())?; let mut plain = Vec::new(); f1::open_file(&fk, key, &mut bytes.as_slice(), &mut plain).map_err(|e| format!("{key}: {}", e.code()))?; String::from_utf8_lossy(&plain).into_owned() } else { String::from_utf8_lossy(&bytes).into_owned() }; let folder = key.rsplit_once('/').map(|(folder, _)| folder).unwrap_or(""); for name in playlist_names(&text) { let child = format!("{folder}/{name}"); if seen.insert(child.clone()) && child.ends_with(".m3u8") { folder_of(object, &child, seen)?; } } Ok(()) } /// Every key of `kinds` the person's rows name, with each picture's /// renditions and each film folder's files. Read over `/v1/sync`, as a device /// reads; a sealed row is opened by the client's door. pub fn held_keys(object: &ObjectClient, database_id: &str, kinds: &[String]) -> Result, String> { let served: BTreeSet = object.definitions().map_err(|e| e.to_string())?["tables"] .as_array() .into_iter() .flatten() .filter_map(|table| table["id"].as_str().map(str::to_string)) .collect(); let mut keys = BTreeSet::new(); for table in FILE_TABLES.iter().filter(|table| served.contains(**table)) { let rows = match object.device_rows(table) { Some(rows) => rows.map_err(|e| format!("{table}: {e}"))?, None => return Err("this client reads no rows: open it as a device".to_string()), }; for row in rows { keys_in(&row["data"], database_id, kinds, &mut keys); } } for playlist in keys.clone().into_iter().filter(|key| key.ends_with(".m3u8")) { folder_of(object, &playlist, &mut keys)?; } Ok(keys.into_iter().collect()) } /// The kinds the object lists plain itself (`GET /v1/media-plain`, apps/business `MEDIA_PLAIN_KINDS`): kept chat /// pictures (22 Nov 2026) and faces (AVATAR SEAL, 27 Nov 2026). For these the object also holds a reseal back, /// naming the person's devices that read the kind on an app from before, which would find a sealed file unreadable. pub const LISTED_PLAIN_KINDS: &[&str] = &["messages", "people"]; /// What a re-seal is to go over: the keys, and per kind the devices the object holds it back for. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct ResealPlan { pub keys: Vec, /// Kind → the device names the object said are waiting. A real run leaves every key of such a kind alone. pub held_back: std::collections::BTreeMap>, } /// Every key of `kinds` to re-seal: those the person's rows name ([`held_keys`]) and, for a kind the object lists /// plain itself, every plain file it holds of that kind (a face no row names any more, a WhatsApp picture of a chat /// since gone). While the object holds a kind back, a dry run still counts the row-named keys of that kind (reads /// only); a real run takes none of them. pub fn reseal_plan(object: &ObjectClient, database_id: &str, kinds: &[String], dry_run: bool) -> Result { let mut keys: BTreeSet = held_keys(object, database_id, kinds)?.into_iter().collect(); let mut held_back = std::collections::BTreeMap::new(); for kind in kinds.iter().filter(|kind| LISTED_PLAIN_KINDS.contains(&kind.as_str())) { let mut after: Option = None; loop { let mut query = vec![("kind", kind.clone()), ("limit", "1000".to_string())]; if let Some(after) = &after { query.push(("after", after.clone())); } let page = object.get_json("/v1/media-plain", &query).map_err(|e| format!("the object's plain {kind}: {e}"))?; let waiting: Vec = page["waiting"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(str::to_string)).collect(); if !waiting.is_empty() { held_back.insert(kind.clone(), waiting); break; } for file in page["files"].as_array().into_iter().flatten() { if let Some(key) = file["key"].as_str().filter(|key| sealed::is_person_file(database_id, key)) { keys.insert(key.to_string()); } } match page["next"].as_str() { Some(next) if after.as_deref() != Some(next) => after = Some(next.to_string()), _ => break, } } } if !dry_run { keys.retain(|key| !held_back.contains_key(key.split('/').nth(1).unwrap_or(""))); } Ok(ResealPlan { keys: keys.into_iter().collect(), held_back }) } // ── re-sealing what is stored in the clear ────────────────────────────────── #[derive(Debug, Clone)] pub struct ResealOptions { /// Count only: nothing is fetched, written or sent. pub dry_run: bool, /// Where each clear copy is kept until its sealed one is verified. pub keep: PathBuf, /// Leave the verified clear copies in `keep` (a backup the run made). pub keep_clear: bool, /// Keys verified sealed, one a line: a run reads it to skip them without asking the object. pub progress: Option, /// Stop after this many files are re-sealed (a run in pieces). With more /// than one thread, the files already in hand still finish. pub limit: Option, /// How many files are re-sealed at once (1 to 32). pub threads: usize, } /// The sha256 a key names, when it names one: `…/<64 hex>.` and nothing between. fn named_sha(key: &str) -> Option<&str> { let name = key.rsplit('/').next()?; let (stem, ext) = name.split_once('.')?; (stem.len() == 64 && stem.bytes().all(|b| b.is_ascii_hexdigit()) && !ext.contains('.')).then_some(stem) } fn sha256_of(read: &mut dyn Read) -> std::io::Result { let mut hasher = Sha256::new(); let mut buffer = vec![0u8; 1 << 20]; loop { let got = read.read(&mut buffer)?; if got == 0 { return Ok(hex::encode(hasher.finalize())); } hasher.update(&buffer[..got]); } } fn local_of(keep: &Path, key: &str) -> PathBuf { key.split('/').filter(|part| !part.is_empty() && *part != "." && *part != "..").fold(keep.to_path_buf(), |path, part| path.join(part)) } /// Where a key's clear bytes wait while they come down: the whole file name /// with a suffix, so two keys of one folder that differ only by extension /// (a playlist and its subtitles) never share it. fn part_of(local: &Path) -> PathBuf { let mut name = local.file_name().map(|name| name.to_os_string()).unwrap_or_default(); name.push(".clear-part"); local.with_file_name(name) } /// Re-seal one key; see the module's words for the order. fn reseal_one(object: &ObjectClient, key: &str, options: &ResealOptions) -> Outcome { let stored = match object.media_stored(key) { Ok(Some(stored)) => stored, Ok(None) => return Outcome::of(key, "missing", 0), Err(error) => return Outcome::failed(key, error.to_string()), }; if stored.sealed() { return Outcome::of(key, "held", stored.size); } if options.dry_run { return Outcome::of(key, "clear", stored.size); } let fk = match object.person_file_key(key) { Ok(fk) => fk, Err(error) => return Outcome::failed(key, error.to_string()), }; let io = |what: &str, error: std::io::Error| Outcome::failed(key, format!("{what}: {error}")); // 1. The clear bytes come down first, and are the ones the key names. let local = local_of(&options.keep, key); if let Some(folder) = local.parent() { if let Err(error) = std::fs::create_dir_all(folder) { return io("the keep folder", error); } } let part = part_of(&local); let fetched = std::fs::File::create(&part).map_err(|e| e.to_string()).and_then(|mut out| object.get_media_to(key, stored.size, &mut out).map_err(|e| e.to_string())); if let Err(error) = fetched { let _ = std::fs::remove_file(&part); return Outcome::failed(key, error); } let clear_sha = match std::fs::File::open(&part).and_then(|mut file| sha256_of(&mut file)) { Ok(sha) => sha, Err(error) => return io("the clear copy", error), }; if named_sha(key).is_some_and(|named| !named.eq_ignore_ascii_case(&clear_sha)) { let _ = std::fs::remove_file(&part); return Outcome { key: key.to_string(), state: "corrupt", bytes: stored.size, why: Some("the stored bytes are not the ones the key names".to_string()) }; } if let Err(error) = std::fs::rename(&part, &local) { return io("the clear copy", error); } // 2. The sealed file takes the clear one's place under the same key, in one write. if let Err(error) = object.put_person_file(key, &local, stored.size, &stored.content_type) { return Outcome::failed(key, format!("{error} (the clear copy is still stored, and kept at {})", local.display())); } // 3. Read back, opened, and the same bytes: only then does the clear copy go. let kept = || format!("the clear copy is kept at {}", local.display()); let verified = (|| -> Result<(), String> { let now = object.media_stored(key).map_err(|e| e.to_string())?.ok_or("the object holds nothing under the key")?; if !now.sealed() || now.size != f1::sealed_len(stored.size) { return Err(format!("the object holds {} bytes as {:?}, not the sealed file", now.size, now.content_type)); } let mut back = tempfile::tempfile_in(&options.keep).map_err(|e| e.to_string())?; object.get_media_to(key, now.size, &mut back).map_err(|e| e.to_string())?; back.rewind().map_err(|e| e.to_string())?; let mut opening = OpeningReader::new(&fk, key, back, now.size).map_err(|e| e.code().to_string())?; let opened = sha256_of(&mut opening).map_err(|e| e.to_string())?; if opened != clear_sha { return Err("the sealed file opens to other bytes".to_string()); } Ok(()) })(); if let Err(why) = verified { return Outcome::failed(key, format!("not verified: {why}; {}", kept())); } if !options.keep_clear { let _ = std::fs::remove_file(&local); } if let Some(progress) = &options.progress { if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(progress) { // One write a line: several threads append to the same file. let _ = file.write_all(format!("{key}\n").as_bytes()); } } Outcome::of(key, "sealed", stored.size) } /// Re-seal every key of `keys` stored in the clear; `each` hears every /// outcome as it is known. A dry run only counts. pub fn reseal(object: &ObjectClient, keys: &[String], options: &ResealOptions, each: &mut dyn FnMut(&Outcome)) -> Result, String> { if !options.dry_run { std::fs::create_dir_all(&options.keep).map_err(|e| format!("{}: {e}", options.keep.display()))?; // Asked once before a byte moves: with no data key nothing is touched. if let Some(first) = keys.first() { object.person_file_key(first).map_err(|e| e.to_string())?; } } let done: BTreeSet = options .progress .as_ref() .and_then(|path| std::fs::read_to_string(path).ok()) .map(|text| text.lines().map(str::to_string).collect()) .unwrap_or_default(); let next = AtomicUsize::new(0); let sealed_now = AtomicUsize::new(0); let stop = AtomicBool::new(false); let mut outcomes: Vec<(usize, Outcome)> = Vec::with_capacity(keys.len()); std::thread::scope(|scope| { let (said, heard) = std::sync::mpsc::channel::<(usize, Outcome)>(); for _ in 0..options.threads.clamp(1, 32) { let said = said.clone(); let (next, sealed_now, stop, done) = (&next, &sealed_now, &stop, &done); scope.spawn(move || loop { if stop.load(Ordering::SeqCst) || options.limit.is_some_and(|limit| sealed_now.load(Ordering::SeqCst) >= limit) { break; } let at = next.fetch_add(1, Ordering::SeqCst); let Some(key) = keys.get(at) else { break }; let outcome = if done.contains(key) { Outcome::of(key, "held", 0) } else { reseal_one(object, key, options) }; if outcome.state == "sealed" { sealed_now.fetch_add(1, Ordering::SeqCst); } // Signed out: every later key would say the same. if outcome.why.as_deref() == Some(&ObjectError::SignedOut.to_string()) { stop.store(true, Ordering::SeqCst); } if said.send((at, outcome)).is_err() { break; } }); } drop(said); for (at, outcome) in heard { each(&outcome); outcomes.push((at, outcome)); } }); outcomes.sort_by_key(|(at, _)| *at); let outcomes: Vec = outcomes.into_iter().map(|(_, outcome)| outcome).collect(); Ok(outcomes) } /// The run's counts by kind and state, and its failures: no key's contents. pub fn report(outcomes: &[Outcome], dry_run: bool) -> Value { let mut kinds: std::collections::BTreeMap> = Default::default(); for outcome in outcomes { let kind = outcome.key.split('/').nth(1).unwrap_or("").to_string(); let entry = kinds.entry(kind).or_default().entry(outcome.state).or_insert((0, 0)); entry.0 += 1; entry.1 += outcome.bytes; } let kinds: serde_json::Map = kinds .into_iter() .map(|(kind, states)| (kind, Value::Object(states.into_iter().map(|(state, (files, bytes))| (state.to_string(), serde_json::json!({ "files": files, "bytes": bytes }))).collect()))) .collect(); let left = outcomes.iter().filter(|o| matches!(o.state, "clear" | "failed" | "corrupt")).count(); serde_json::json!({ "dryRun": dry_run, "files": outcomes.len(), "kinds": kinds, // What a run still leaves in the clear: 0 is the whole job done. "left": left, "failed": outcomes.iter().filter(|o| matches!(o.state, "failed" | "corrupt")).collect::>(), }) } #[cfg(test)] mod part_tests { use super::*; /// RULE: two keys of one folder that differ only by extension wait under different names. #[test] fn keys_that_differ_only_by_extension_wait_apart() { let playlist = part_of(Path::new("/keep/films/f1/sub-en.m3u8")); let subtitles = part_of(Path::new("/keep/films/f1/sub-en.vtt")); assert_ne!(playlist, subtitles); assert_eq!(playlist, Path::new("/keep/films/f1/sub-en.m3u8.clear-part")); } } /// TOKEN SCOPES (coordinator, 24 Nov 2026; assets/design/shared/TOKEN-SCOPES-GO-LIVE.md): the film and fetch /// importers write their rows as this Mac, a device, never with the owner's `ctn_` token, so a row of a sealed /// table goes sealed by the device (`ObjectClient::act`, through its seal door) instead of sealed at arrival. /// /// `seal-files serve`: one JSON line in, `{ "act": "create" | "update", "table", "id", "data" }`; one JSON line /// out for each, in order: `{ "ok": true, "answer": … }`, or `{ "ok": false, "status", "code", "message" }` for /// a refusal (the line goes on). Never a row's values on stderr. Ends at the end of its input. pub fn serve_acts( input: impl std::io::BufRead, mut output: impl std::io::Write, mut act: impl FnMut(crate::object::Act, &str, &str, &serde_json::Value) -> Result, ) -> Result { let mut served = 0; for line in input.lines() { let line = line.map_err(|e| format!("the acts could not be read: {e}"))?; if line.trim().is_empty() { continue; } let said: serde_json::Value = match serde_json::from_str(&line) { Ok(said) => said, Err(e) => { writeln!(output, "{}", serde_json::json!({ "ok": false, "status": 400, "code": "bad_line", "message": format!("an act is one JSON line: {e}") })).map_err(|e| e.to_string())?; output.flush().map_err(|e| e.to_string())?; continue; } }; let kind = match said["act"].as_str() { Some("create") => Some(crate::object::Act::Create), Some("update") => Some(crate::object::Act::Update), _ => None, }; let (table, id) = (said["table"].as_str().unwrap_or_default(), said["id"].as_str().unwrap_or_default()); let answer = match kind { None => serde_json::json!({ "ok": false, "status": 400, "code": "bad_act", "message": "serve takes create or update" }), Some(_) if table.is_empty() || id.is_empty() => serde_json::json!({ "ok": false, "status": 400, "code": "bad_args", "message": "an act names its table and its row's id" }), Some(kind) => match act(kind, table, id, &said["data"]) { Ok(answer) => serde_json::json!({ "ok": true, "answer": answer }), Err(ObjectError::Refused { status, code, message }) => serde_json::json!({ "ok": false, "status": status, "code": code, "message": message }), Err(other) => serde_json::json!({ "ok": false, "status": 0, "code": "unreached", "message": other.to_string() }), }, }; writeln!(output, "{answer}").map_err(|e| e.to_string())?; output.flush().map_err(|e| e.to_string())?; served += 1; } Ok(served) } #[cfg(test)] mod serve_tests { use super::*; use crate::object::Act; /// RULE (token scopes, 24 Nov 2026): `seal-files serve` answers each act on its own line, in order; a /// refusal is that line's answer and the next act is still served; a line that is not an act is said so. #[test] fn each_act_is_answered_on_its_own_line_and_a_refusal_does_not_stop_the_rest() { let input = [ r#"{"act":"create","table":"book","id":"b-1","data":{"title":"Invented book"}}"#, r#"{"act":"update","table":"film","id":"f-404","data":{"file":"k"}}"#, "not json", r#"{"act":"delete","table":"film","id":"f-1"}"#, r#"{"act":"update","table":"film","id":"f-1","data":{"file":"k"}}"#, ] .join("\n"); let mut seen = Vec::new(); let mut out = Vec::new(); let served = serve_acts(std::io::Cursor::new(input), &mut out, |act, table, id, data| { seen.push((act.as_str().to_string(), table.to_string(), id.to_string(), data.clone())); if id == "f-404" { return Err(ObjectError::Refused { status: 404, code: "no_such_record".into(), message: "no film f-404".into() }); } Ok(serde_json::json!({ "sealed": true })) }) .expect("served"); let lines: Vec = String::from_utf8(out).expect("utf8").lines().map(|l| serde_json::from_str(l).expect("a JSON line")).collect(); assert_eq!(served, 4, "the bad line is answered but not counted"); assert_eq!(lines.len(), 5); assert_eq!(lines[0], serde_json::json!({ "ok": true, "answer": { "sealed": true } })); assert_eq!((lines[1]["ok"].clone(), lines[1]["code"].clone()), (serde_json::json!(false), serde_json::json!("no_such_record"))); assert_eq!(lines[2]["code"], "bad_line"); assert_eq!(lines[3]["code"], "bad_act"); assert_eq!(lines[4]["ok"], true); assert_eq!(seen.iter().map(|s| (s.0.as_str(), s.2.as_str())).collect::>(), vec![("create", "b-1"), ("update", "f-404"), ("update", "f-1")]); assert_eq!(seen[0].3["title"], "Invented book"); let _ = Act::Create; } }