//! The hydrator: bytes coming DOWN to this machine, until two devices hold //! every original. //! //! It is [`super::drain`] read backwards, and it keeps the drain's two //! properties for the drain's reasons: //! //! **THE LEDGER IS THE QUEUE.** There is no in-memory work list — //! `cotton_media_holdings` says who holds what, so a pass computes its own work //! from the file and quitting mid-pull loses nothing. The next pass asks the //! same question and gets a shorter answer. //! //! **A FAILURE IS A PASS THAT DID LESS.** A key the server will not sign, a //! socket that went away — the object is simply not pulled and comes back on //! the next pass. There is no attempt counter and no `failed` state, because //! unlike an upload there is nothing here that is only on this device: the //! bytes exist somewhere or the ledger is wrong about them, and neither is //! fixed by remembering a number. //! //! ## What "done" means //! //! **Two live holders.** [`REPLICATION_HOLDERS`] is the target and //! [`cotton_store::media_holdings::objects_with_fewer_than`] is the question; //! when it answers empty the pass has nothing to do and the household's //! originals each exist on two machines. That is EVENTUAL and never an //! invariant (plan §I, limit 4) — a Mac that is off pulls nothing — and it is //! blind to what nobody recorded (limit 5): an object with no holdings row is //! UNKNOWN, not unheld, and cannot come back from the query, so a phone that //! has never met a Mac stays the only holder of its own captures for ever. The //! budget fence on the phone protects that; this pass does not fix it. //! //! ## Two policies, one pass //! //! A Mac takes [`Policy::Everything`] — every original, oldest first, until the //! disk guard — because a Mac is where a household's second copy lives. Its //! own keep rules still decide per object (`storage_rules::wants_original`): //! a Mac whose device row says "rows only" pulls nothing nobody opened. //! And only a Mac that keeps everything is one of the two holders the target //! counts (`cotton_store::storage_rules::KEEPS_EVERYTHING`): a phone's copy, //! a rows-only Mac's and the mirror bucket's are not. A phone //! takes [`Policy::Viewed`] and pulls NOTHING here: the phone's downloads are //! `media.ensure` on a picture somebody opened, driven by a finger rather than //! by a timer, and a phone quietly replicating two hundred gigabytes is the //! opposite of what any of this is for — a matter of the phone's disk, never //! of which network it is on. //! //! ## Where the bytes come from //! //! The object's own GET, `GET /v1/media/` under the object's bearer //! ([`super::transport::ObjectMediaTransport`]) — the same read //! `personal.connect`'s `ObjectMedia` draws pictures through. use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use cotton_store::mint::Held; use cotton_store::outbox::IdSource; use cotton_store::media_holdings::{holders_of, objects_with_fewer_than, record_holding, Tier}; use cotton_store::media_ledger::{enqueue_media, MediaEnqueueInput}; use crate::layout::Layout; use crate::replica::Replica; use crate::seams::Clock; use crate::transport::ServerRefusal; /// How many live KEEPERS — Macs that keep everything — should hold each /// original. /// /// TWO. One is a household that loses its pictures with a disk; three is a /// third machine most people do not have, and the ledger cost (plan §I, limit /// 3) grows with it. pub const REPLICATION_HOLDERS: i64 = 2; /// Objects one pass pulls at most. A step size, not a ceiling — the next tick /// takes the next batch, and a pass that moved a full batch is followed at once /// rather than in fifteen minutes. pub const HYDRATE_BATCH: usize = 20; /// The DISK FLOOR: a pass pulls nothing while the volume holding the media /// store has less than this free. /// /// 20 GB, and it is deliberately generous. The thing being protected is not the /// replication — a pass that stops is a pass that runs again tomorrow — it is /// the MACHINE: this Mac is serving a person's database out of the same volume, /// and a SQLite file that cannot extend its WAL is a household whose phone /// stops syncing. A replica of somebody's library is the last thing that should /// win that race. pub const HYDRATE_DISK_FLOOR_BYTES: u64 = 20 * 1024 * 1024 * 1024; /// What the disk floor says about taking one more object onto a volume. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DiskRoom { /// More than [`HYDRATE_DISK_FLOOR_BYTES`] is free. Enough, /// At or under the floor: stop, and try again on a later pass. Floor, /// Nobody could say how much is free — and unknown stops a pass too /// ([`MediaHydrateDeps::free_bytes`] says why). Unread, } /// The sentence a pass carries when the volume could not be read. /// /// Spelled once because two passes stop on it: this one, and a standby Mac's /// pull into the store its server serves from (`cotton-server`'s /// `media::standby`, which asks it through `cotton-ffi`). pub const DISK_UNREAD: &str = "how much room is left on this volume could not be read, so nothing was pulled"; /// The ONE reading of [`HYDRATE_DISK_FLOOR_BYTES`] against a free-space /// figure. /// /// A function rather than a comparison each caller writes, because the Mac has /// two pulls — the replica's and the standby's — and a second `>` against the /// floor is where a `>=` would slip in. pub fn room_left(free: Option) -> DiskRoom { match free { Some(free) if free > HYDRATE_DISK_FLOOR_BYTES => DiskRoom::Enough, Some(_) => DiskRoom::Floor, None => DiskRoom::Unread, } } /// What this device pulls of its own accord. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Policy { /// A MAC: every original the household is short a holder of, oldest first, /// until the disk floor. Everything, /// A PHONE: nothing. Its bytes arrive through `media.ensure`, on a picture /// somebody opened. Named rather than "no policy" because the absence is a /// decision, and a decision with a name is one a reader can find. Viewed, } /// What one pass did. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct HydratePass { /// Objects whose bytes landed here and whose hold was recorded. pub pulled: usize, pub bytes: u64, /// Objects this pass tried and could not take. No state is kept for them; /// they are simply on the next pass's list too. pub failed: usize, /// Objects still short of [`REPLICATION_HOLDERS`] after this pass — the /// per-pass bound, or failures. Non-zero means "come back at once". pub pending: usize, /// The pass stopped because the volume is nearly full. pub floor: bool, /// The policy said there was nothing for this device to do. pub off: bool, pub last_error: Option, } impl HydratePass { /// Whether the next pass should follow this one immediately rather than /// waiting for the tick — the mirror's `catch_up` rule, for the mirror's /// reason: the cadence is for a household that is level, not for a library /// that is not yet there. pub fn catch_up(&self) -> bool { self.pulled > 0 && self.pending > 0 && !self.floor } } /// Everything the hydrator touches that is not the file. Ports, so the whole /// ordering contract is testable without a network and without a disk full of /// pictures. pub trait MediaHydrateDeps: Send + Sync + std::fmt::Debug { /// Write the bytes behind `key` into `dest`. /// /// `database` is the file the pass is pulling for — the replica's own id, /// never read off the key: the server signs a key only inside the database /// the request names, so a pull for a second database must say which. fn fetch_object_to(&self, database: &str, key: &str, dest: &Path) -> Result<(), ServerRefusal>; /// Rule fetches bound the stream by remaining cap space. Other hydrators /// have no cap; test ports may use this default and the arrival check. fn fetch_object_to_bounded(&self, database:&str, key:&str, dest:&Path, limit:Option) -> Result<(),ServerRefusal> { self.fetch_object_to(database,key,dest)?; if limit.is_some_and(|n|std::fs::metadata(dest).map(|m|m.len()>n).unwrap_or(true)) { return Err(ServerRefusal::offline("The original exceeds Space for kept things")); } Ok(()) } /// How much room is left on the volume holding `path`. /// /// `None` is UNKNOWN, and unknown stops the pass. A replicator that filled /// a disk because nobody could tell it how full the disk was is the silent /// fallback this repo does not allow — and the number is knowable on every /// machine that runs [`Policy::Everything`], which is a Mac. fn free_bytes(&self, path: &Path) -> Option; /// Mac ports override this with their device's core keep-free policy. /// The phone's existing reserve remains its own mobile policy. fn disk_room(&self, path: &Path) -> DiskRoom { room_left(self.free_bytes(path)) } } /// The free-space reading a Mac uses, over `statvfs`. /// /// `statvfs` and not the iOS number: the caveat in `cotton-ffi`'s `Disk` seam is /// about a PHONE, where the figure people mean is /// `volumeAvailableCapacityForImportantUsage` and only the app side can read /// it. A phone takes [`Policy::Viewed`] and never asks this question, so the /// honest answer on a Mac is the one the filesystem gives. /// /// The two `try_from`s are ALLOWED to be redundant on purpose: `f_bavail` and /// `f_frsize` are platform-width (`u32` and `u64` on macOS, both `u64` on /// Linux), so one of the pair is infallible on any given target and a cast that /// was right here would be a narrowing cast somewhere else. #[cfg(unix)] #[allow( clippy::unnecessary_fallible_conversions, clippy::useless_conversion, reason = "statvfs field widths differ per platform; the fallible form is the portable one" )] pub fn free_bytes_at(path: &Path) -> Option { use std::os::unix::ffi::OsStrExt; let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?; // SAFETY: `statvfs` reads the path and fills the struct; the path is a // NUL-terminated C string that outlives the call, and the struct is this // frame's. let stats = unsafe { let mut stats = std::mem::MaybeUninit::::zeroed(); if libc::statvfs(c_path.as_ptr(), stats.as_mut_ptr()) != 0 { return None; } stats.assume_init() }; // `f_bavail` is what a non-root process may actually have, which is the // number this guard is about; `f_bfree` counts the reserve too. u64::try_from(stats.f_bavail) .ok()? .checked_mul(u64::try_from(stats.f_frsize).ok()?) } #[cfg(not(unix))] pub fn free_bytes_at(_path: &Path) -> Option { None } /// The objects THIS device should pull, newest first — `device_id` is this /// device's KEY, the id its own holds name it by. /// /// Two filters and they are different questions. The ledger's own /// [`objects_with_fewer_than`] answers "which originals are short of a second /// live holder"; this then drops the ones this device already holds, because an /// object held by this Mac alone has no second copy to pull FROM — pulling it /// would be a request to a server for bytes that are already under this /// process's own media directory. /// /// Capped at `limit` for what it PULLS, and complete for what it COUNTS: the /// second number is what a screen prints and what decides whether the next pass /// follows at once, so it is the real remainder rather than the batch's. /// /// **The cost is one indexed lookup per short object**, and it is taken under /// the replica's lock. A household of fifty thousand objects on one machine /// therefore spends a fraction of a second there every fifteen minutes — the /// same order the drain spends per row, and the reason this is a `work_list` /// with a bound rather than a walk that pulls as it goes. pub fn work_list( db: &cotton_store::driver::Driver, workspace_id: &str, device_id: &str, limit: usize, now_ms: i64, ) -> Result<(Vec, usize), cotton_store::StoreError> { let short = objects_with_fewer_than(db, workspace_id, REPLICATION_HOLDERS, Tier::Original)?; let mut mine = Vec::with_capacity(limit.min(short.len())); let mut short_of_two = 0usize; for key in short { // Dead bytes are owed to nobody (slice 7): a device that has not yet // unlinked its copy still holds it, and pulling it would bring back // what the erase took. Asked of the index: this runs once per short // object under the replica's lock (`unlink::index_says_bytes_dead`). if super::unlink::index_says_bytes_dead(db, &key)? { continue; } let holders = holders_of(db, workspace_id, &key, Tier::Original)?; if holders.iter().any(|holder| holder.device_id == device_id) { // This machine IS the one holder. Somebody else has to pull it; // there is nothing here to ask a server for. continue; } if !cotton_store::storage_rules::wants_original(db, workspace_id, device_id, &key, now_ms)? { continue; } short_of_two += 1; if mine.len() < limit { mine.push(key); } } Ok((mine, short_of_two)) } /// Where a fetched original lands — the store's own content-addressed path. /// /// The digest comes off the file rather than off the key, through /// [`super::store::sha256_file`], which is the one hasher on this device and /// streams in chunks. The key names the extension and nothing else that is /// trusted: a scratch file renamed under a digest it does not have would be a /// store that lies about its own contents. pub(super) fn land( layout: &Layout, workspace_id: &str, key: &str, scratch: &Path, ) -> std::io::Result<(PathBuf, String, u64)> { let (sha256, size_bytes) = super::store::sha256_file(scratch)?; land_measured(layout, workspace_id, key, scratch, sha256, size_bytes) } pub(super) fn land_measured( layout: &Layout, workspace_id: &str, key: &str, scratch: &Path, sha256: String, size_bytes: u64, ) -> std::io::Result<(PathBuf, String, u64)> { let _backup = cotton_store::media_backup_lock::mutating(&layout.client_media_dir())?; let path = super::store::media_file_path(layout, workspace_id, &sha256, extension_of(key)); if path.exists() { // The same bytes are already here under the same digest — which is the // whole meaning of a content-addressed store. The scratch goes. std::fs::remove_file(scratch)?; return Ok((path, sha256, size_bytes)); } if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } std::fs::rename(scratch, &path)?; Ok((path, sha256, size_bytes)) } /// `…/photos/.heic` → `heic`. Empty for a key with no extension, which /// [`super::store::media_file_path`] already spells as a bare digest. fn extension_of(key: &str) -> &str { key.rsplit('/') .next() .and_then(|name| name.rsplit_once('.')) .map_or("", |(_, ext)| ext) } /// One pass over EVERY database this device holds at one server: one /// [`hydrate_pass`] each, summed. /// /// `open` is asked per database as its turn comes, so a database the floor /// stops the pass before is never opened. A database that will not open is a /// failure of that database alone — its sentence is kept and the others are /// still pulled. The floor is one disk's, so it ends the whole pass. #[allow(clippy::too_many_arguments)] pub fn hydrate_every( databases: &[String], open: &mut dyn FnMut(&str) -> Result>, String>, deps: &dyn MediaHydrateDeps, layout: &Layout, policy: Policy, clock: &dyn Clock, device_key: Option<&str>, ids: &mut dyn IdSource, ) -> HydratePass { // ONE WALK PER MEDIA STORE. The pass runs on a blocking thread, which a // stopped server cannot cancel: a server restarted in the same process // (a re-attach, an update's drain that ran out of time) started its // first tick while the old walk was still streaming, and the two walked // the same work list. A walk that finds one running is not started; the // running one carries the list (the phone's sweep, 7bc59e40c). let Some(_walking) = Walking::take(layout.client_media_dir()) else { return HydratePass::default(); }; let mut total = HydratePass { off: true, ..HydratePass::default() }; for database in databases { let replica = match open(database) { Ok(replica) => replica, Err(error) => { total.off = false; total.last_error = Some(error); continue; } }; let pass = hydrate_pass(&replica, deps, layout, policy, clock, device_key, ids); total.pulled += pass.pulled; total.bytes += pass.bytes; total.failed += pass.failed; total.pending += pass.pending; total.floor |= pass.floor; total.off &= pass.off; if pass.last_error.is_some() { total.last_error = pass.last_error; } // The floor is the disk's: it ends the whole walk. if total.floor { break; } } total } /// The media stores a replica walk is going over in this process. static WALKING: Mutex> = Mutex::new(std::collections::BTreeSet::new()); /// This process's one walk over a media store, until it drops. pub(super) struct Walking(PathBuf); impl Walking { /// The walk over `store`, or `None` while another is going over it. pub(super) fn take(store: PathBuf) -> Option { let taken = WALKING .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .insert(store.clone()); // Built only when taken: a `Walking` dropped here would release the // other walk's store. taken.then(|| Walking(store)) } } impl Drop for Walking { fn drop(&mut self) { WALKING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.0); } } /// One pass: take what this device lacks, up to [`HYDRATE_BATCH`] objects. /// /// SYNCHRONOUS and blocking, unlike the drain's pass. The drain overlaps three /// uploads because a phone's uploads are what a person is waiting on; a /// replicator is background work with no one watching, and one object at a time /// leaves the link to the sync loop, which IS what a person is waiting on. /// /// The replica's lock is taken and RELEASED around every network call, the /// drain's own rule: a read on this device (`with_file` takes the same lock) /// must never wait behind a download of unbounded length. pub fn hydrate_pass( replica: &Arc>, deps: &dyn MediaHydrateDeps, layout: &Layout, policy: Policy, clock: &dyn Clock, device_key: Option<&str>, ids: &mut dyn IdSource, ) -> HydratePass { if policy == Policy::Viewed { return HydratePass { off: true, ..HydratePass::default() }; } // THIS DEVICE'S KEY, never the replica's author id: the key is what // every reader of the ledger joins on, so "the device I exclude from the // work list" and "the device I record a hold for" are the one id every // other machine counts (`super::holds`). let (workspace_id, device_id, listed, restate_error, reader) = { let mut held = replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let reader = !super::holds::may_announce_holds(&held.driver, device_key); let holder = super::holds::holder_in(&held.driver, &held.workspace_id, device_key); let mut restate_error = None; let listed = if reader { match device_key.filter(|key| !key.is_empty()) { Some(device_id) => work_list( &held.driver, &held.workspace_id, device_id, HYDRATE_BATCH, clock.now().timestamp_millis(), ) .map_err(|error| error.to_string()), None => Err("this device has no device key yet, so it cannot choose media to cache".to_string()), } } else { match &holder { Ok(Ok(device_id)) => { // Holds this replica wrote under its author id are restated // under the key, and a hold on an object whose file is not // here goes — both before the work list is read, so that // object is owed again. restate_error = super::holds::keep_holds_level( &mut held, Some(device_id.as_str()), clock.now().timestamp_millis(), ids, ); work_list(&held.driver, &held.workspace_id, device_id, HYDRATE_BATCH, clock.now().timestamp_millis()) .map_err(|error| error.to_string()) } Ok(Err(sentence)) => Err(sentence.clone()), Err(error) => Err(error.clone()), } }; let device_id = if reader { device_key.unwrap_or_default().to_string() } else { holder.ok().and_then(Result::ok).unwrap_or_default() }; (held.workspace_id.clone(), device_id, listed, restate_error, reader) }; let (due, short_of_two) = match listed { Ok(answer) => answer, Err(error) => { return HydratePass { last_error: Some(error), ..HydratePass::default() } } }; let mut pass = HydratePass { pending: short_of_two, last_error: restate_error, ..HydratePass::default() }; if due.is_empty() { return pass; } let folder = layout.client_media_dir().join(&workspace_id); if let Err(error) = std::fs::create_dir_all(&folder) { pass.last_error = Some(error.to_string()); return pass; } // The per-process scratch the pass used before a fetch resumed // (`hydrate--.part`): nothing asks for it again, so it goes. if let Ok(entries) = std::fs::read_dir(&folder) { for entry in entries.flatten() { let name = entry.file_name(); let name = name.to_string_lossy(); if name.starts_with("hydrate-") && name.ends_with(".part") { let _ = std::fs::remove_file(entry.path()); } } } for key in &due { // THE FLOOR IS ASKED PER OBJECT, not once per pass: a pass pulling // twenty originals off a phone's camera roll can be several gigabytes, // and a guard read before the first of them is a guard that measured // the wrong disk. match deps.disk_room(&folder) { DiskRoom::Enough => {} DiskRoom::Floor => { pass.floor = true; break; } DiskRoom::Unread => { pass.floor = true; pass.last_error = Some(DISK_UNREAD.to_string()); break; } } // ONE FETCH OF A KEY AT A TIME in this process, into the key's ONE // partial file: a fetch cut part way (a quit, a dropped line, a sync // read closing the stream) keeps what arrived and the next pass asks // only for the rest (`Range: bytes=N-`, `super::fetching`). On 13 Oct // 2026 a standby's quit threw away 195 MB of a 196.4 MB bundle. let _turn = super::fetching::turn(key); let scratch = super::fetching::partial_path(&folder, key); if let Err(refusal) = deps.fetch_object_to(&workspace_id, key, &scratch) { if !super::fetching::keeps_partial(&refusal) { let _ = std::fs::remove_file(&scratch); } pass.failed += 1; pass.last_error = Some(format!("`{key}` did not come down: {}", refusal.message)); continue; } let landed = match land(layout, &workspace_id, key, &scratch) { Ok(landed) => landed, Err(error) => { let _ = std::fs::remove_file(&scratch); pass.failed += 1; pass.last_error = Some(format!("`{key}` could not be stored: {error}")); continue; } }; let (path, sha256, size_bytes) = landed; let now = clock.now(); let recorded = { let held = replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); // THE LEDGER ROW IS `synced`, NEVER `pending`. These bytes came OUT // of the bucket, so queueing them for upload would send back what // is already there — the same reasoning `media.ensure` writes down. // It is also what makes the file findable: `read.mediaPath` resolves // through `_media.local_path`, so a replica pulled without this row // would be bytes on a disk no screen could draw. enqueue_media( &held.driver, &MediaEnqueueInput { key: key.clone(), workspace_id: workspace_id.clone(), sha256: sha256.clone(), // The bytes did not come with a type this layer can trust, // and the record row already carries the one the writer // declared. The generic answer is the honest one. content_type: "application/octet-stream".to_string(), size_bytes: i64::try_from(size_bytes).unwrap_or(i64::MAX), local_path: Some(path.to_string_lossy().to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, // The same tier the hold below records, said in the ledger // too: this pass pulls ORIGINALS, and the budgeted cache // decides an eviction off this column. tier: Some(Tier::Original), // NOT a capture. This device pulled these bytes off the // bucket and can pull them again; the fence that makes a // file permanent is for the ones the person's own camera // took. captured_here: false, now: crate::seams::iso(now), }, ) .map_err(|error| error.to_string()) .and_then(|_| { if reader { return Ok(()); } // AND THE HOLD, which is the whole point of the pass: it is what // makes the count on the Server view fall and what lets the // OTHER machine's leave stop refusing. record_holding( &held.driver, &workspace_id, &device_id, key, Tier::Original, i64::try_from(size_bytes).unwrap_or(i64::MAX), now.timestamp_millis(), ids, Held::Replica, ) .map_err(|error| error.to_string()) .map(|_| ()) }) }; match recorded { Ok(_) => { pass.pulled += 1; pass.bytes = pass.bytes.saturating_add(size_bytes); pass.pending = pass.pending.saturating_sub(1); } Err(reason) => { // The bytes are here and nothing says so. Counted as a failure // rather than a pull, so the pass reports what is true — and // the next pass finds the file already under its digest and // pays only for the round trip. pass.failed += 1; pass.last_error = Some(format!("`{key}` landed and could not be recorded: {reason}")); } } } pass } #[cfg(test)] #[path = "hydrate_tests.rs"] mod tests;