//! The event stream: one JSON line per event, delivered to the ONE subscriber//! Swift registers at open.//!//! Design M2. Anything unbounded — an import pass, an export, a restore, a//! snapshot bootstrap, a media drain — is a command that returns immediately and//! reports here, so no call across the boundary is ever a long call. The stream//! carries what the Electron window used to learn from seven separate IPC notify//! channels.//!//! Two rules make it safe://!//! * **The callback is invoked with the lock released.** Holding it across a//! callback into Swift would deadlock the moment that callback asked the core//! a question, which is exactly what a status line does.//! * **The string is borrowed for the duration of the call.** Swift copies it//! (`String(cString:)` does), and nothing has to be freed — the one place in//! this ABI where a string does not cross as an owned `CString`.use std::ffi::{c_char, c_void, CString};use std::sync::Mutex;use serde::Serialize;use serde_json::{json, Value};/// The kinds the stream carries, all eleven of them, declared once.////// The sub-step that starts emitting each is named beside it — a kind nobody/// emits yet is a shape already agreed, not a promise mislaid.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pubenumEventKind {/// The server's own state changed (3b).Status,/// The served file moved on, carrying `serverSeq` (3c).Data,/// A line for the Activity page and `server.log` (3a).Log,/// The sync loop said something (3e).Client,/// A device was approved, revoked or seen (3d).Devices,/// A share, an invitation or a peer (3d).Sharing,/// The photo-analysis worker (3f).Analyze,/// An import pass (3e).Ingest,/// The relay line came up or went down (3f).Tunnel,/// This Mac's host settings changed (`device.setHost`) — the app applies/// the four switches the answer carries.Host,/// A session's terminal output, base64 — `{ session, bytes }`.////// DOTTED, where every kind above it is one word. The two names are the/// contract Cotton note "The Code tool — why a Mac holds the sessions" fixed so phases 3 and 4 could be/// built in parallel, and a kind called `terminal` with a `type` inside its/// payload would be this table telling the app a different story from the/// design of record. They are the only two, and a third belongs with them/// or not at all. #[serde(rename = "terminal.data")]TerminalData,/// What a terminal view draws besides the bytes — `{ session, state }`,/// where the state is `attached`, `catchingUp` or `closed`. #[serde(rename = "terminal.state")]TerminalState,}/// Where an event goes: a C function pointer and the context Swift handed with/// it.implEventKind {/// Whether the event tells a reader its file moved on (a list reads/// again): every kind but a log line, the sync loop's word, the relay's/// line and a terminal's bytes and state.fn moves_reads(self) -> bool { !matches!(self, EventKind::Log | EventKind::Client | EventKind::Tunnel | EventKind::TerminalData | EventKind::TerminalState) }}#[derive(Clone, Copy)]structSubscriber { ctx: *mut c_void, on_event: extern"C"fn(*mut c_void, *const c_char),}/// SAFETY: `ctx` is an opaque pointer Swift owns and keeps alive until/// `cotton_close`; the core never dereferences it, it only hands it back. The/// callback may therefore be invoked from any thread, which is the contract/// Swift's side honours by hopping to its actor.unsafeimplSendforSubscriber {}#[derive(Default)]structInner { subscriber: Option<Subscriber>,/// Events emitted before anyone was listening — the early log's rule, one/// layer up: a one-time move that happened during `cotton_open` must not be/// the one line nobody ever sees. buffered: Vec<String>,}pubstructEventBus { inner: Mutex<Inner>,/// This bus among every bus the process opened: what a reader's kept/// answer names its file by, so a later handle never reads another's. id: u64,/// How many times this file has said it moved on: every event that tells/// the shell to read again (data, definitions, devices, sharing, an/// import's or the worker's pass). An answer kept beside the count it was/// read at stands while the count does ([`Self::moved`]). moved: std::sync::atomic::AtomicU64,/// What each move named: the count each table last moved the file to,/// and the count of the last move that named no table. Held under one/// lock with the count's step, so a reader never sees the count without/// the tables that moved it. touched: Mutex<Touched>,}#[derive(Default)]structTouched { tables: std::collections::HashMap<String, u64>, blind: u64,/// The count each table last moved to by a move that named no row of/// it (a pull, a bulk write, a rebuild): what moved there is unknown. unrowed: std::collections::HashMap<String, u64>,/// The rows moves named, `(count, table, id)`, oldest first: every/// named row of every move past `floor`, at most [`ROWS_KEPT`]. rows: std::collections::VecDeque<(u64, String, String)>,/// The count of the newest move whose named rows are no longer all held. floor: u64,}/// How many named rows the bus holds for a kept read to be patched by.const ROWS_KEPT: usize = 4096;implDefaultforEventBus {fn default() -> Self {static BUSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);EventBus { inner: Mutex::default(), id: BUSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed), moved: std::sync::atomic::AtomicU64::new(0), touched: Mutex::default(), } }}implEventBus {pubfn new() -> Self {Self::default() }/// This bus's id and how often its file has moved on: a kept read is/// current while both are the ones it was read at.pubfn moved(&self) -> (u64, u64) { (self.id, self.moved.load(std::sync::atomic::Ordering::Acquire)) }/// Whether the file moved on past count `at` in a way a read that leaves/// out the store tables `aside` names would see: a move naming no table,/// or one naming a table not aside.pubfn moved_since(&self, at: u64, aside: &dynFn(&str) -> bool) -> bool {let touched = self.touched.lock().unwrap_or_else(std::sync::PoisonError::into_inner); touched.blind > at || touched.tables.iter().any(|(table, count)| *count > at && !aside(table)) }/// Whether a read kept at `at` (this bus's id and count) still stands for/// a read that leaves out the store tables in `aside`: the one rule every/// kept shell read (`shell_kept`, `shell_list_kept`) is kept by.pubfn stands(&self, at: (u64, u64), aside: &std::collections::HashSet<String>) -> bool { at.0 == self.id && !self.moved_since(at.1, &|table| aside.contains(table)) }/// The rows that moved since a read kept at `at`, `(table, id)` once/// each, leaving out the store tables in `aside`: what a kept cut is/// patched for. None where it cannot be told: another bus, a move naming/// no table, a table moved with no rows named, or rows older than the/// bus still holds.pubfn rows_since(&self, at: (u64, u64), aside: &std::collections::HashSet<String>) -> Option<Vec<(String, String)>> {if at.0 != self.id { returnNone; }let touched = self.touched.lock().unwrap_or_else(std::sync::PoisonError::into_inner);if touched.blind > at.1 || touched.floor > at.1 { returnNone; }if touched.unrowed.iter().any(|(table, count)| *count > at.1 && !aside.contains(table)) { returnNone; }letmut rows: Vec<(String, String)> = Vec::new();for (_, table, id) in touched.rows.iter().filter(|(count, table, _)| *count > at.1 && !aside.contains(table)) {if !rows.iter().any(|(held, row)| held == table && row == id) { rows.push((table.clone(), id.clone())); } }Some(rows) }/// Emit one event. Delivered now if someone is listening, buffered if not.pubfn emit(&self, kind: EventKind, payload: Value) {if kind.moves_reads() {letmut touched = self.touched.lock().unwrap_or_else(std::sync::PoisonError::into_inner);let count = self.moved.load(std::sync::atomic::Ordering::Acquire) + 1;// Only a data event names what moved; every other kind, and a data// event naming nothing, moves every read.let named: Vec<&str> = match kind {EventKind::Data => payload["tables"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(), _ => Vec::new(), };if named.is_empty() { touched.blind = count; }// The rows a write named (`authoring::rows_touched`); a table// named with none of its rows moved whole.let rows: Option<Vec<(&str, &str)>> = match kind {EventKind::Data => payload["rows"].as_array().map(|rows| rows.iter().filter_map(|row| Some((row["table"].as_str()?, row["id"].as_str()?))).collect()), _ => None, };for table in named { touched.tables.insert(table.to_string(), count);if !rows.as_ref().is_some_and(|rows| rows.iter().any(|(held, _)| *held == table)) { touched.unrowed.insert(table.to_string(), count); } }for (table, id) in rows.into_iter().flatten() { touched.rows.push_back((count, table.to_string(), id.to_string())); }while touched.rows.len() > ROWS_KEPT {ifletSome((gone, _, _)) = touched.rows.pop_front() { touched.floor = touched.floor.max(gone); } }self.moved.store(count, std::sync::atomic::Ordering::Release); }let line = match serde_json::to_string(&json!({ "kind": kind, "payload": payload })) {Ok(line) => line,// A payload that cannot be serialised is a bug in the emitter, and// saying so out loud beats dropping the event silently.Err(error) => format!(r#"{{"kind":"log","payload":{{"level":"error","message":"an event could not be serialised: {error}"}}}}"# ), };let subscriber = {letmut inner = self.lock();match inner.subscriber {Some(subscriber) => Some(subscriber),None => { inner.buffered.push(line.clone());None } } };ifletSome(subscriber) = subscriber { deliver(subscriber, &line); } }/// A convenience for the commonest kind.pubfn log(&self, message: implInto<String>) {self.emit(EventKind::Log, json!({ "message": message.into() })); }/// Register the subscriber and replay everything buffered, in order, exactly/// once. A null callback clears the subscriber — an honest "stop sending".pubfn subscribe( &self, ctx: *mut c_void, on_event: Option<extern"C"fn(*mut c_void, *const c_char)>, ) {let (subscriber, replay) = {letmut inner = self.lock();match on_event {None => { inner.subscriber = None;return; }Some(on_event) => {let subscriber = Subscriber { ctx, on_event }; inner.subscriber = Some(subscriber);// Drained BEFORE the first delivery, so a subscriber that// emits from inside its own callback is not replayed by this// same flush.let replay: Vec<String> = std::mem::take(&mut inner.buffered); (subscriber, replay) } } };for line in &replay { deliver(subscriber, line); } }/// How many events are waiting for a subscriber. For tests and for the/// status method; never a queue anybody drains by hand.pubfn buffered(&self) -> usize {self.lock().buffered.len() }/// How many waiting events are of one kind. A test asking what ONE act/// emitted counts that act's kind: an open handle's background work (the/// vault's first placement pass, a sample) logs through the tracing bridge/// at its own moment, and every such line is a `log` event on this bus. #[cfg(test)] #[cfg(test)]pubfn buffered_of(&self, kind: EventKind) -> usize {let name = serde_json::to_value(kind).unwrap_or(Value::Null);self.lock() .buffered .iter() .filter(|line| serde_json::from_str::<Value>(line).is_ok_and(|event| event["kind"] == name)) .count() }/// Every waiting event, as it would be delivered. For tests. #[cfg(test)] #[cfg(test)]pubfn buffered_events(&self) -> Vec<Value> {self.lock().buffered.iter().filter_map(|line| serde_json::from_str(line).ok()).collect() }fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {// A poisoned lock means a previous emit panicked mid-way. The event// stream is not state anybody's data depends on, so it recovers rather// than taking the app down with it.self.inner .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) }}fn deliver(subscriber: Subscriber, line: &str) {letOk(text) = CString::new(line) else {return; }; (subscriber.on_event)(subscriber.ctx, text.as_ptr());}#[cfg(test)]mod tests {usesuper::*;use std::sync::{Arc, MutexasStdMutex};/// The test's own C callback: everything it is handed, in order.////// A C function pointer cannot carry a closure's captures, so the record is/// a static — which means these tests share it and must not run at the same/// time. `serial()` is that lock, held for the length of each test.static SEEN: StdMutex<Vec<String>> = StdMutex::new(Vec::new());static ORDER: StdMutex<()> = StdMutex::new(());fn serial() -> std::sync::MutexGuard<'static, ()> { ORDER .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) }extern"C"fn collect(_ctx: *mut c_void, line: *const c_char) {let text = unsafe { std::ffi::CStr::from_ptr(line) } .to_string_lossy() .to_string(); SEEN.lock().expect("the record").push(text); }fn drain_seen() -> Vec<String> { std::mem::take(&mut *SEEN.lock().expect("the record")) } #[test]fn an_event_emitted_before_anyone_listens_is_replayed_when_someone_does() {let _serial = serial();let _ = drain_seen();let bus = EventBus::new(); bus.log("moved the data folder from A to B"); bus.log("pointed 3 stored file path(s) at the new folder"); assert_eq!(bus.buffered(), 2); bus.subscribe(std::ptr::null_mut(), Some(collect));let seen = drain_seen(); assert_eq!(seen.len(), 2); assert!(seen[0].contains("moved the data folder from A to B")); assert!(seen[1].contains("pointed 3 stored file path(s)")); assert_eq!(bus.buffered(), 0); } #[test]fn a_second_subscribe_replays_nothing_the_first_already_took() {let _serial = serial();let _ = drain_seen();let bus = EventBus::new(); bus.log("one"); bus.subscribe(std::ptr::null_mut(), Some(collect)); assert_eq!(drain_seen().len(), 1); bus.subscribe(std::ptr::null_mut(), Some(collect)); assert!(drain_seen().is_empty()); } #[test]fn a_move_says_the_tables_it_named_and_a_move_naming_none_moves_every_read() {let bus = EventBus::new();let (_, at) = bus.moved(); bus.emit(EventKind::Data, json!({ "tables": ["cotton_notes"] })); assert!(!bus.moved_since(at, &|table| table == "cotton_notes"), "a read leaving notes aside still stands"); assert!(bus.moved_since(at, &|_| false), "a read of notes moved"); bus.log("a line moves no read"); assert!(!bus.moved_since(at, &|table| table == "cotton_notes")); bus.emit(EventKind::Data, json!({ "tables": [] })); assert!(bus.moved_since(at, &|_| true), "a move naming nothing moves every read");let (_, after) = bus.moved(); bus.emit(EventKind::Status, json!({ "state": "stopped" })); assert!(bus.moved_since(after, &|_| true), "so does every other kind that moves reads"); } #[test]fn a_move_naming_its_rows_says_them_and_one_naming_none_says_nothing_can_be_told() {let bus = EventBus::new();let at = bus.moved();let aside: std::collections::HashSet<String> = ["cotton_notes".to_string()].into(); bus.emit(EventKind::Data, json!({ "tables": ["cotton_todos", "cotton_notes"], "rows": [ {"table": "cotton_todos", "id": "a", "kind": "upsert"}, {"table": "cotton_notes", "id": "n", "kind": "upsert"}] })); bus.emit(EventKind::Data, json!({ "tables": ["cotton_todos"], "rows": [{"table": "cotton_todos", "id": "b", "kind": "delete"}, {"table": "cotton_todos", "id": "a", "kind": "upsert"}] })); assert_eq!(bus.rows_since(at, &aside), Some(vec![("cotton_todos".to_string(), "a".to_string()), ("cotton_todos".to_string(), "b".to_string())]));let later = bus.moved(); assert_eq!(bus.rows_since(later, &aside), Some(Vec::new()), "nothing moved since"); bus.emit(EventKind::Data, json!({ "tables": ["cotton_notes"] })); assert_eq!(bus.rows_since(later, &aside), Some(Vec::new()), "a table aside moved whole: nothing it reads"); bus.emit(EventKind::Data, json!({ "tables": ["cotton_todos"], "rows": null })); assert_eq!(bus.rows_since(later, &aside), None, "a bulk write names no rows");let after = bus.moved(); bus.emit(EventKind::Data, json!({ "tables": [], "rows": [] })); assert_eq!(bus.rows_since(after, &aside), None, "a move naming no table");let other = EventBus::new(); assert_eq!(other.rows_since(after, &aside), None, "another bus");let full = EventBus::new();let at = full.moved();for round in0..=ROWS_KEPT { full.emit(EventKind::Data, json!({ "tables": ["t"], "rows": [{"table": "t", "id": format!("r{round}"), "kind": "upsert"}] })); } assert_eq!(full.rows_since(at, &aside), None, "rows older than the bus holds"); } #[test]fn a_null_callback_stops_the_stream_rather_than_crashing() {let _serial = serial();let _ = drain_seen();let bus = EventBus::new(); bus.subscribe(std::ptr::null_mut(), Some(collect)); bus.subscribe(std::ptr::null_mut(), None); bus.log("nobody is listening"); assert!(drain_seen().is_empty()); assert_eq!(bus.buffered(), 1); } #[test]fn the_line_is_one_json_object_carrying_its_kind_and_its_payload() {let _serial = serial();let _ = drain_seen();let bus = EventBus::new(); bus.subscribe(std::ptr::null_mut(), Some(collect)); bus.emit(EventKind::Status, json!({ "state": "stopped" }));let seen = drain_seen();let parsed: Value = serde_json::from_str(&seen[0]).expect("one JSON object"); assert_eq!(parsed["kind"], "status"); assert_eq!(parsed["payload"]["state"], "stopped"); assert!(!seen[0].contains('\n'), "one line per event"); } #[test]fn emitting_from_inside_the_callback_does_not_deadlock() {let _serial = serial();let _ = drain_seen();let bus = Arc::new(EventBus::new());// A callback that asks the core something, which emits: the case that// would deadlock if the lock were held across the delivery.static NESTED: StdMutex<Option<Arc<EventBus>>> = StdMutex::new(None); *NESTED.lock().expect("the slot") = Some(Arc::clone(&bus));extern"C"fn reentrant(_ctx: *mut c_void, line: *const c_char) {let text = unsafe { std::ffi::CStr::from_ptr(line) } .to_string_lossy() .to_string();let first = !text.contains("echo of"); SEEN.lock().expect("the record").push(text.clone());if first {ifletSome(bus) = NESTED.lock().expect("the slot").clone() { bus.log("echo of the first"); } } } bus.subscribe(std::ptr::null_mut(), Some(reentrant)); bus.log("the first");let seen = drain_seen(); assert_eq!(seen.len(), 2); assert!(seen[1].contains("echo of the first")); *NESTED.lock().expect("the slot") = None; }}