//! The ledger drain: a device's captures leaving it for the person's object, //! in the background, for ever. //! //! It keeps the two properties that matter: //! //! **`_media` IS THE QUEUE.** There is no in-memory job list, so the queue does //! not exist only in the process that made it. Quitting mid-upload loses //! nothing; the next launch reads the same rows, and a row cut off part way //! goes up again whole. //! //! **FAILURE IS A ROW, NOT AN EXCEPTION.** A transport failure moves a backoff //! and nothing else, with no attempt ceiling — these bytes are on this device //! and a row given up on is a file that never reaches the backup. Only a //! refusal the object will REPEAT becomes `failed`, with the object's own //! line: `object_full` (the object's media at their cap), `too_big`, a key it //! will not take — because retrying one of those forever is a loop that never //! says so. //! //! It runs BESIDE the sync loop rather than inside it, deliberately: a pass //! pushes ops at network speed and reads at disk speed, and a 90 MB video in //! front of a person's messages would hold up the rows they are waiting to see. //! //! The bytes go up by the object's media door (`super::transport`): one `PUT //! /v1/media/`, or the file in parts above `PART_BYTES`. A key the object //! holds already (the Mac imported the same picture) is taken as it stands — //! the object answers `stored: false` and keeps one copy. A row's bytes stay //! on this device after they go up: the object is the backup, not a move. use std::sync::{Arc, Mutex}; use std::path::{Path, PathBuf}; use cotton_core::media::keys::media_kind_for; use cotton_store::media_ledger::{ claim_due_media_on, codes, mark_media_failed_as, mark_media_synced, media_counts, park_until_exchange, record_media_attempt_as, MediaCounts, MediaRow, }; use super::uploads::UploadWatch; use serde::Serialize; use crate::replica::Replica; use crate::seams::Clock; use crate::sync::cycle::held; use crate::transport::ServerRefusal; /// How many rows one pass looks at. A step size, not a ceiling. pub const MEDIA_DRAIN_BATCH: i64 = 20; /// How many uploads run at once. /// /// THREE, the phone's number, for the phone's reason: one at a time spends the /// whole pass on latency, and a dozen at once starves the sync loop's push and /// pull — the calls a person is actually waiting on. pub const MEDIA_DRAIN_CONCURRENCY: usize = 3; /// How often the drain wakes on its own when there is nothing to do. pub const MEDIA_DRAIN_INTERVAL_MS: u64 = 60_000; /// What an upload found at the object. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Landed { /// The bytes were stored under the key. Stored, /// The object held the key at that size already and took nothing. Held, } /// Everything the drain touches that is not the ledger. A port, so the whole /// ordering contract is testable without a network and without a disk. pub trait MediaDrainDeps: Send + Sync + std::fmt::Debug { /// Put the file at `local_path` under `row.key`, with `row.content_type`. /// A round trip (several, for a file in parts): never called with the /// replica held. fn upload(&self, row: &MediaRow, local_path: &Path) -> Result; /// [`MediaDrainDeps::upload`], saying as it goes how many bytes of how /// many have gone (`progress(sent, total)`, the bytes on the wire). A port /// that cannot tell answers as `upload` does and says nothing: the file /// reads as going up, with no count. fn upload_watched(&self, row: &MediaRow, local_path: &Path, progress: Progress) -> Result { let _ = progress; self.upload(row, local_path) } } /// Told `(sent, total)` as an upload's bytes go. pub type Progress = Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum DrainState { Idle, Uploading, Stopped, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct MediaDrainStatus { pub state: DrainState, pub pending: i64, /// The bytes `pending` rows still have to send. pub pending_bytes: i64, pub synced: i64, pub failed: i64, pub delete_pending: i64, pub last_error: Option, } impl MediaDrainStatus { fn with_counts(mut self, counts: MediaCounts) -> MediaDrainStatus { self.pending = counts.pending; self.pending_bytes = counts.pending_bytes; self.synced = counts.synced; self.failed = counts.failed; self.delete_pending = counts.delete_pending; self } } impl Default for MediaDrainStatus { fn default() -> Self { MediaDrainStatus { state: DrainState::Stopped, pending: 0, pending_bytes: 0, synced: 0, failed: 0, delete_pending: 0, last_error: None, } } } /// What one row's trip up did. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Uploaded { Uploaded, /// A rendition the object draws from its original (`.t256.jpg`, /// `.d1600.jpg`): nothing goes up, and the row is settled. Drawn, /// Terminal — the object will refuse it the same way next time. Failed, /// Transient — backed off, still in the queue. Retry, } /// A refusal the object will repeat, told apart from one worth retrying. /// /// The object's terminal answers: 413 (`object_full`, `too_big`), 415, and /// 400/403 a key or a body it will not take. Everything else — a 5xx, a 401 /// the sync loop signs out on, no network at all — is transient by definition /// and goes back on the backoff ladder. `bad_upload` is a 400 that is not /// repeated: parts that did not make a file are sent again as a new upload. /// `space_full` is a 413 that waits for room, never given up on. pub fn is_terminal_refusal(refusal: &ServerRefusal) -> bool { matches!(refusal.status, 400 | 403 | 413 | 415) && !matches!(refusal.code.as_deref(), Some("bad_upload") | Some(SPACE_FULL)) } /// The space for photos and files is full (assets/design/shared/SPACE.md): never terminal. The file stays on the /// phone and in the queue, backed off, and goes up by itself once there is room (a friend counted, space freed or /// bought). pub const SPACE_FULL: &str = "space_full"; /// The server refused these bytes as DEAD — an erase it holds left nothing /// naming the key. Never terminal: see [`finish_upload`]. pub fn is_dead_key_refusal(refusal: &ServerRefusal) -> bool { refusal.code.as_deref() == Some(cotton_core::media::keys::DEAD_KEY_REFUSAL_CODE) } /// What a pass moved. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct DrainPass { pub uploaded: usize, /// Renditions settled without a byte moving ([`Uploaded::Drawn`]). pub drawn: usize, pub failed: usize, } impl DrainPass { /// Rows this pass took off the queue for good: another pass may find more. pub fn moved(&self) -> bool { self.uploaded > 0 || self.drawn > 0 } } /// What a row needs before its bytes can move, read UNDER the lock: the file /// the ledger points at. Everything after this is network, and the lock is /// not held for it. pub struct UploadPlan { local_path: PathBuf, } /// Phase one, under the replica lock: decide whether the row can go up at all. /// /// `Err` is the row's outcome, already written to the ledger; `Ok` is a plan /// whose bytes are still to be carried. pub fn plan_upload(replica: &Replica, row: &MediaRow, clock: &dyn Clock) -> Result { // DEAD BYTES DO NOT GO UP (slice 7). The unlink pass, first on the tick, // takes the entry with its file; one it has not reached yet is left // untouched rather than dropped here, which would forget the file's path // before the file is gone. if crate::media::unlink::bytes_are_dead(&replica.driver, &row.key).unwrap_or(false) { return Err(Uploaded::Retry); } // A key outside this database, or of no shape the object keeps: refused // here before a byte moves, with the sentence that says why. if let Err(error) = media_kind_for(&row.key, replica.file_id()) { let _ = mark_media_failed_as(&replica.driver, &row.key, codes::REFUSED, &error.to_string(), &clock.now_iso()); return Err(Uploaded::Failed); } let local_path = row.local_path.as_deref().map(PathBuf::from).filter(|path| path.is_file()); // A RENDITION THIS DEVICE MADE goes up like any file, sealed (R6): the // object can draw nothing from a sealed original, so the device's own // thumbnail and display copy are the only ones there are. One with no // file here (a key named before anyone drew it) is settled: the object // draws it from a clear original stored before R6, or the device opens // the original in its place. if crate::transport::object::rendition(&row.key).is_some() && local_path.is_none() { let _ = mark_media_synced(&replica.driver, &row.key, &clock.now_iso()); return Err(Uploaded::Drawn); } let Some(local_path) = local_path else { // The ledger names no file here, or the file is gone: nothing on this // device can send these bytes again, so the row is terminal with the // one sentence that explains it. let _ = mark_media_failed_as(&replica.driver, &row.key, codes::FILE_GONE, "these bytes are not on this device any more", &clock.now_iso()); return Err(Uploaded::Failed); }; Ok(UploadPlan { local_path }) } /// Phase two, with NO lock held: the bytes going up. Seconds per picture; /// this is the part a phone read must never wait behind. pub fn carry_bytes(deps: &dyn MediaDrainDeps, row: &MediaRow, plan: &UploadPlan) -> Result { deps.upload(row, &plan.local_path) } /// [`carry_bytes`] with the upload in `watch` for as long as it is in the /// air, and its count moving as the bytes go. Ended by the caller AFTER the /// ledger says how it went ([`finish_upload`]), so a reader never finds the /// file neither in the air nor answered. pub fn carry_bytes_watched(deps: &dyn MediaDrainDeps, row: &MediaRow, plan: &UploadPlan, watch: &Arc) -> Result { watch.begin(&row.key, u64::try_from(row.size_bytes).unwrap_or(0)); let progress: Progress = { let watch = Arc::clone(watch); let key = row.key.clone(); Arc::new(move |sent, total| watch.progress(&key, sent, total)) }; deps.upload_watched(row, &plan.local_path, progress) } /// The word a refusal the object will repeat is filed under. pub fn refusal_code(refusal: &ServerRefusal) -> &'static str { match refusal.code.as_deref() { Some("too_big") => codes::TOO_BIG, Some("object_full") => codes::COTTON_FULL, _ => codes::REFUSED, } } /// Phase three, under the lock again: write what happened to the ledger. pub fn finish_upload( replica: &Replica, row: &MediaRow, carried: Result, clock: &dyn Clock, ) -> Uploaded { match carried { Ok(_) => { let _ = mark_media_synced(&replica.driver, &row.key, &clock.now_iso()); Uploaded::Uploaded } Err(refusal) => { let now = clock.now_iso(); if is_dead_key_refusal(&refusal) { // Retried after the next exchange, never dropped (slice 7): // the server is wrong for as long as this device has not // pushed the row that names the key again. let _ = park_until_exchange(&replica.driver, &row.key, &refusal.message, &now); Uploaded::Retry } else if is_terminal_refusal(&refusal) { let _ = mark_media_failed_as(&replica.driver, &row.key, refusal_code(&refusal), &refusal.message, &now); Uploaded::Failed } else { // A full space is a WAIT with a word; anything else passing is a retry with none. let code = (refusal.code.as_deref() == Some(SPACE_FULL)).then_some(codes::SPACE_FULL); let _ = record_media_attempt_as(&replica.driver, &row.key, code, &refusal.message, &now); Uploaded::Retry } } } } /// ONE row, all the way up, over a replica the caller already holds — the /// three phases in a row for a test that is about the OUTCOME. The drain /// itself never calls this: it takes the lock per phase (`drain_pass`), and /// `a_reader_gets_the_replica_while_the_bytes_are_going_up` is what holds it /// to that. #[cfg(test)] pub(crate) fn upload_one( replica: &Replica, deps: &dyn MediaDrainDeps, row: &MediaRow, clock: &dyn Clock, ) -> Uploaded { match plan_upload(replica, row, clock) { Err(outcome) => outcome, Ok(plan) => finish_upload(replica, row, carry_bytes(deps, row, &plan), clock), } } /// The most rows one pass claims before it lets the tick's other work run (keep-fetch, the budget, the status). pub const MEDIA_DRAIN_PASS_MOST: usize = 1000; /// What is due, under the network rule as it stands now, less what this pass already took. fn claim_due(replica: &Replica, clock: &dyn Clock, taken: &std::collections::HashSet) -> Vec { let wifi = crate::media::network::wifi_only_may_go(); let limit = MEDIA_DRAIN_BATCH + i64::try_from(taken.len()).unwrap_or(i64::MAX - MEDIA_DRAIN_BATCH); claim_due_media_on(&replica.driver, limit, &clock.now_iso(), wifi) .unwrap_or_default() .into_iter() .filter(|row| !taken.contains(&row.key)) .take(usize::try_from(MEDIA_DRAIN_BATCH).unwrap_or(20)) .collect() } /// A pass's queue (MEDIA DRAIN 1 item 1). A worker that finds it empty claims what is due since, so a large file holds /// one slot while small ones keep flowing past it, and the pass is not stalled behind its slowest upload. No key is /// taken twice in a pass (one that waits again is the next pass's), and a pass takes at most [`MEDIA_DRAIN_PASS_MOST`]. struct Due { rows: Vec, taken: std::collections::HashSet, done: bool, } impl Due { fn new(rows: Vec) -> Due { let taken = rows.iter().map(|row| row.key.clone()).collect(); Due { rows, taken, done: false } } fn next(&mut self, replica: &Arc>, clock: &dyn Clock) -> Option { if let Some(row) = self.rows.pop() { return Some(row); } if self.done || self.taken.len() >= MEDIA_DRAIN_PASS_MOST { return None; } // The queue's lock is held while the file is asked: the order is always queue, then file (a worker never // asks for the queue while it holds the file), so the two never wait on each other. let more = claim_due(&held(replica), clock, &self.taken); if more.is_empty() { self.done = true; return None; } self.taken.extend(more.iter().map(|row| row.key.clone())); self.rows = more; self.rows.pop() } } /// One pass: claim what is due, and take it up — at most /// [`MEDIA_DRAIN_CONCURRENCY`] at a time. pub async fn drain_pass( replica: &Arc>, deps: &Arc, clock: &Arc, watch: &Arc, ) -> DrainPass { let due = { let replica = held(replica); claim_due(&replica, clock.as_ref(), &std::collections::HashSet::new()) }; if due.is_empty() { return DrainPass::default(); } let queue = Arc::new(Mutex::new(Due::new(due))); let mut workers = Vec::new(); for _ in 0..MEDIA_DRAIN_CONCURRENCY { let queue = Arc::clone(&queue); let replica = Arc::clone(replica); let deps = Arc::clone(deps); let clock = Arc::clone(clock); let watch = Arc::clone(watch); workers.push(tokio::task::spawn_blocking(move || { let mut pass = DrainPass::default(); loop { let row = { let mut queue = queue.lock().unwrap_or_else(|p| p.into_inner()); queue.next(&replica, clock.as_ref()) }; let Some(row) = row else { return pass }; // The replica is taken TWICE per row and never across the // network: once to read the plan, once to write the outcome. // Between the two the bytes go up with nothing held. So the // three uploads overlap, the sync loop folds between them, and // a phone read (`with_file` takes this same lock) waits on two // indexed statements rather than on a PUT. Build 143 held it // across the PUT: Home never drew and Sync said "Checking…" // for as long as there were pictures to send. let plan = { let replica = held(&replica); plan_upload(&replica, &row, clock.as_ref()) }; let outcome = match plan { Err(outcome) => outcome, Ok(plan) => { let carried = carry_bytes_watched(deps.as_ref(), &row, &plan, &watch); let outcome = { let replica = held(&replica); finish_upload(&replica, &row, carried, clock.as_ref()) }; watch.end(&row.key); outcome } }; // A waiting reader gets its turn before this worker asks for // the file again: `std::sync::Mutex` promises no order, and // three workers re-taking it back to back is the starvation // this comment exists to forbid. std::thread::yield_now(); match outcome { Uploaded::Uploaded => pass.uploaded += 1, Uploaded::Drawn => pass.drawn += 1, Uploaded::Failed => pass.failed += 1, Uploaded::Retry => {} } } })); } let mut total = DrainPass::default(); for worker in workers { if let Ok(pass) = worker.await { total.uploaded += pass.uploaded; total.drawn += pass.drawn; total.failed += pass.failed; } } total } /// The ledger's own counts, or the last ones if the file has been closed. /// /// The replica closes under a disconnect while a pass may still be in the air. /// That is a shutdown, not a failure, and a thrown "database is not open" out of /// a status update would surface as an upload error on a device that is simply /// signing out. pub fn counts_of(replica: &Replica) -> Option { media_counts(&replica.driver, &replica.workspace_id).ok() } /// Told after every pass, with the status as it now stands. pub type DrainStatusListener = Arc; pub struct MediaDrainInput { pub replica: Arc>, pub deps: Arc, pub clock: Arc, pub interval_ms: Option, pub on_status: Option, pub keep_fetch: Option>, /// The BUDGET pass, when this device has a disk it may take files off. /// /// LAST on the tick, after the uploads and keep-fetch, and the /// order is the whole argument: a file this pass is about to delete may be /// one the drain has not sent up yet, and the fence /// (`cotton_media_holdings`) would refuse it anyway — but a pass that ran /// first would spend the tick measuring a directory the other two are /// still changing. `None` is a device with no eviction policy: a Mac, /// which keeps everything, or a test that is not about the budget. pub evict: Option>, /// The UNLINK pass (slice 7): the bytes of erased records leaving this /// device, each database against its own queue and its own folder. /// /// FIRST on the tick, before the uploads: an erased record's entry leaves /// the upload queue with its file, rather than being sent up to a server /// that would refuse it. `None` is a test that is not about erasure. pub unlink: Option>, /// The replica of every OTHER database this device holds at its /// household's server, asked as each tick starts: each has its own `_media` /// queue, and a drain over the attached file alone left a project's /// captures on the device that took them. The keep-fetch pass walks the /// same list after the attached file. /// `None` is a device holding one database. /// /// The shell's list is every database that holds bytes on this device OR /// owes it some (`HeldNote::owes_bytes`) — never every database: one that /// owes nothing stays closed. pub others: Option, /// The held notes a sync pass counts its folded rows in, and in which this /// drain says how far each database is LEVEL — every kept original its /// rows want is on this device /// (`HeldNotes::note_bytes_level`). That mark is what lets a database /// whose bytes all arrived stay closed on the next tick. `None` is a test /// that is not about which files a tick opens. pub held_notes: Option, /// Who to tell when BYTES moved on this device — landed by the sweep, or /// taken off the disk by the budget. /// /// **ONE call per tick, never one per row**, and only for a tick that /// moved something. The shell turns it into the same `data` event a pull /// carries, naming `_media`, so a tile that honestly said "not on this /// phone" asks again the moment the bytes are. `None` is a device that /// draws nothing: a Mac's host, a test that is not about the event. pub on_media: Option, /// Where the uploads in the air are, for the shell's per-file read /// (`media.uploads`). `None` is a drain whose watch nobody reads: it keeps /// one of its own. pub watch: Option>, /// Run on a blocking thread after each tick's uploads, before keep-fetch: /// the shell's release of Photos copies the object now holds /// (`super::release`), which needs the device's id and its writer. /// `None` is a device that copies nothing from Photos. pub after_uploads: Option, } /// What runs after a tick's uploads ([`MediaDrainInput::after_uploads`]). pub type AfterUploads = Arc; /// What moved on this device's disk in one tick IN ONE DATABASE, for /// [`MediaMovedListener`]. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct MediaMoved { /// Kept originals that arrived. pub landed: usize, /// Originals the budget took off the disk. pub evicted: usize, } impl MediaMoved { pub fn is_empty(self) -> bool { self.landed == 0 && self.evicted == 0 } } /// Told once a tick for each database a byte moved in, with that database's /// id: a screen showing a project redraws for the project's bytes and for no /// other database's. pub type MediaMovedListener = Arc; /// The drain, as a task the shell starts and stops. pub struct MediaDrain { inner: Arc, task: Option>, } struct DrainInner { replica: Arc>, deps: Arc, clock: Arc, interval: std::time::Duration, keep_fetch: Option>, evict: Option>, unlink: Option>, others: Option, held_notes: Option, on_media: Option, watch: Arc, after_uploads: Option, status: Mutex, /// Whether a tick has published counts summed over several databases. summed: std::sync::atomic::AtomicBool, turn: tokio::sync::Mutex<()>, wake: tokio::sync::Notify, running: std::sync::atomic::AtomicBool, on_status: Option, } impl MediaDrain { pub fn new(input: MediaDrainInput) -> MediaDrain { MediaDrain { inner: Arc::new(DrainInner { replica: input.replica, deps: input.deps, clock: input.clock, interval: std::time::Duration::from_millis( input.interval_ms.unwrap_or(MEDIA_DRAIN_INTERVAL_MS), ), keep_fetch: input.keep_fetch, evict: input.evict, unlink: input.unlink, others: input.others, held_notes: input.held_notes, on_media: input.on_media, watch: input.watch.unwrap_or_default(), after_uploads: input.after_uploads, status: Mutex::new(MediaDrainStatus::default()), summed: std::sync::atomic::AtomicBool::new(false), turn: tokio::sync::Mutex::new(()), wake: tokio::sync::Notify::new(), running: std::sync::atomic::AtomicBool::new(false), on_status: input.on_status, }), task: None, } } pub fn status(&self) -> MediaDrainStatus { self.inner.status() } /// The uploads this drain has in the air. pub fn watch(&self) -> Arc { Arc::clone(&self.inner.watch) } pub fn start(&mut self) { use std::sync::atomic::Ordering; if self.inner.running.swap(true, Ordering::SeqCst) { return; } self.inner.publish(DrainState::Idle, None); let inner = Arc::clone(&self.inner); self.task = Some(tokio::spawn(async move { inner.run().await })); } pub fn stop(&mut self) { use std::sync::atomic::Ordering; if !self.inner.running.swap(false, Ordering::SeqCst) { return; } self.inner.publish(DrainState::Stopped, None); self.inner.wake.notify_waiters(); if let Some(task) = self.task.take() { task.abort(); } } /// Run passes until nothing moves — what an import calls after it stored a /// batch of files. /// /// Keeps going while a pass moved something: a batch of 20 at a time means /// an import of 57,000 files would otherwise take 47 hours of one-minute /// ticks to drain. pub async fn drain_now(&self) -> DrainPass { self.inner.cycle().await } /// Ask the drain to come back straight away. pub fn wake(&self) { self.inner.wake.notify_one(); } } impl Drop for MediaDrain { fn drop(&mut self) { self.stop(); } } impl DrainInner { fn status(&self) -> MediaDrainStatus { self.status .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } fn publish(&self, state: DrainState, last_error: Option) { self.publish_over(&[], state, last_error); } /// The status, with the counts of EVERY database's queue added up: the /// line a person reads is about this device's uploads, not one file's. /// `others` are the replicas a tick opened beside the attached one; with /// none (a start, a stop) the attached file's counts stand alone. fn publish_over( &self, others: &[Arc>], state: DrainState, last_error: Option, ) { let counts = std::iter::once(&self.replica) .chain(others) .map(|replica| { let replica = replica.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); counts_of(&replica) }) // ALL OR NOTHING: a sum missing one database's rows is not the // total, so a file that would not answer keeps the last counts. .try_fold(MediaCounts::default(), |mut total, counts| { let counts = counts?; total.pending += counts.pending; total.pending_bytes += counts.pending_bytes; total.synced += counts.synced; total.failed += counts.failed; total.delete_pending += counts.delete_pending; Some(total) }); if !others.is_empty() { self.summed.store(true, std::sync::atomic::Ordering::SeqCst); } // A start or a stop after a tick has no other replica in hand: the // tick's sum stands rather than falling back to one file's rows. let counts = counts.filter(|_| { !others.is_empty() || !self.summed.load(std::sync::atomic::Ordering::SeqCst) }); let snapshot = { let mut status = self .status .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); let next = MediaDrainStatus { state, last_error, ..status.clone() }; *status = match counts { Some(counts) => next.with_counts(counts), None => next, }; status.clone() }; if let Some(listener) = &self.on_status { listener(&snapshot); } } /// One tick. async fn cycle(&self) -> DrainPass { let _turn = self.turn.lock().await; let mut total = DrainPass::default(); // HOW MANY PASSES HAD FOLDED ROWS into each database, read BEFORE any // file is opened or swept: a database this tick leaves level is // marked level as of THESE counts, so rows a pass folds while the // sweep runs still owe and the next tick opens the file again. let pulls: std::collections::BTreeMap = self .held_notes .as_ref() .map(|notes| { notes .read_all() .into_iter() .map(|(database, note)| (database, note.pulls)) .collect() }) .unwrap_or_default(); // EVERY DATABASE'S QUEUE, the attached one first. The others are // opened on a blocking thread — an open is SQLite — and one that // would not open is simply not in this tick. let mut replicas = vec![Arc::clone(&self.replica)]; if let Some(others) = self.others.clone() { replicas.extend( tokio::task::spawn_blocking(move || others()) .await .unwrap_or_default(), ); } self.publish_over(&replicas[1..], DrainState::Uploading, None); // A DATABASE MID-MOVE IS LEFT OUT (passivemove rule 1): its media // tables may still be in their old shape, and the sync pass leaves it // alone for the same reason. let all = replicas; let replicas: Vec>> = { let all = all.clone(); tokio::task::spawn_blocking(move || { all.into_iter() .filter(|replica| { let database = replica .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .workspace_id .clone(); crate::moves::left(&database).is_none() }) .collect() }) .await .unwrap_or_default() }; self.unlink_pass(&replicas).await; for replica in &replicas { loop { let pass = drain_pass(replica, &self.deps, &self.clock, &self.watch).await; total.uploaded += pass.uploaded; total.drawn += pass.drawn; total.failed += pass.failed; if !pass.moved() { break; } } } if let Some(after) = self.after_uploads.clone() { let _ = tokio::task::spawn_blocking(move || after()).await; } let kept = self.keep_fetch_pass(&replicas).await; let mut landed: std::collections::BTreeMap = std::collections::BTreeMap::new(); for (database, kept) in &kept { *landed.entry(database.clone()).or_default() += kept.landed; } self.note_level(&replicas, pulls, &kept).await; // AND THEN THE BUDGET, last: what this device may keep is decided after // everything that could have added to it. let evicted = self.evict_pass().await; // ONE word to each database's screens, after both, and only for a // database a byte moved in — the attached one first. if let Some(listener) = &self.on_media { let mut words: Vec<(String, MediaMoved)> = Vec::new(); for (database, landed) in landed { words.push((database, MediaMoved { landed, evicted: 0 })); } for (database, evicted) in evicted { match words.iter_mut().find(|(named, _)| *named == database) { Some((_, moved)) => moved.evicted = evicted, None => words.push((database, MediaMoved { landed: 0, evicted })), } } for (database, moved) in words { if !moved.is_empty() { listener(&database, moved); } } } let state = if self.running.load(std::sync::atomic::Ordering::SeqCst) { DrainState::Idle } else { DrainState::Stopped }; self.publish_over(&all[1..], state, None); total } /// Mark each database whose keep-fetch queue is empty as level at the /// pull count observed before the tick, on a blocking thread. async fn note_level( &self, replicas: &[Arc>], pulls: std::collections::BTreeMap, kept: &std::collections::BTreeMap, ) { let Some(notes) = self.held_notes.clone() else { return; }; let replicas = replicas.to_vec(); let kept_owes: std::collections::BTreeSet = kept .iter() .filter(|(_, kept)| kept.owes) .map(|(database, _)| database.clone()) .collect(); let _ = tokio::task::spawn_blocking(move || { for replica in &replicas { let database = replica .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .workspace_id .clone(); let Some(&at) = pulls.get(&database) else { continue; }; let level = !kept_owes.contains(&database); if !level { continue; } if let Err(error) = notes.note_bytes_level(&database, at) { // The mark is a saving, never a debt: without it the next // tick opens the file and asks again. eprintln!("[cotton-media] {database} was not marked level: {error}"); } } }) .await; } async fn keep_fetch_pass( &self, replicas: &[Arc>], ) -> std::collections::BTreeMap { let Some(sweep) = self.keep_fetch.clone() else { return Default::default(); }; let replicas = replicas.to_vec(); let clock = Arc::clone(&self.clock); tokio::task::spawn_blocking(move || crate::media::keep_fetch::over(&replicas,&sweep,clock.as_ref())) .await.unwrap_or_default() } /// The unlink pass over every database this tick holds, on a blocking /// thread — each replica against its own queue and its own folder. async fn unlink_pass(&self, replicas: &[Arc>]) { let Some(sweep) = self.unlink.clone() else { return; }; let replicas = replicas.to_vec(); let clock = Arc::clone(&self.clock); let _ = tokio::task::spawn_blocking(move || { for replica in &replicas { let pass = crate::media::unlink::unlink_pass(replica, &sweep, clock.as_ref()); if let Some(error) = pass.last_error { eprintln!("[cotton-media] the unlink pass did not finish: {error}"); } } }) .await; } /// The kept Storage-rule pass, on a blocking thread: SQLite and the /// filesystem belong off the runtime's own threads. /// /// Answers how many files left each database, for the same event: a path /// a tile drew a moment ago may be gone, and the ledger is what says so. async fn evict_pass(&self) -> std::collections::BTreeMap { let Some(sweep) = self.evict.clone() else { return Default::default(); }; let replica = Arc::clone(&self.replica); let clock = Arc::clone(&self.clock); tokio::task::spawn_blocking(move || { crate::media::storage::pass(&replica, &sweep, clock.as_ref()) }) .await .map(|pass| pass.removed_in) .unwrap_or_default() } async fn run(self: Arc) { while self.running.load(std::sync::atomic::Ordering::SeqCst) { self.cycle().await; if !self.running.load(std::sync::atomic::Ordering::SeqCst) { break; } tokio::select! { _ = tokio::time::sleep(self.interval) => {}, _ = self.wake.notified() => {}, }; } } } #[cfg(test)] #[path = "drain_tests.rs"] mod tests;