//! Reading this Mac: the iPhone's call history, the Photos library, and //! WhatsApp as a linked device. //! //! **A client of the server, never a second writer.** Everything here produces //! batches; the queue applies them through the ONE engine that owns each kind of //! row, into the replica, and the sync loop pushes them. Nothing in this module //! tree writes into a served file. //! //! Four rules hold across every source, and each is a measurement: //! //! * **Copy before you read** — the live database plus its `-wal`/`-shm` into //! `/client/snapshots/`, because the call-history daemon and Photos //! hold theirs open and write to them continuously. //! * **A permission failure is a STATE, not an error.** `probe()` answers //! [`SourceState::NoPermission`], Swift draws the button that opens the right //! pane of System Settings, and NOTHING retries in a loop against a decision //! only the person can make. Full Disk Access cannot be requested //! programmatically and never will be (design M7). //! * **Idempotency is per ROW, by the source's own stable id** — `ZUNIQUE_ID`, //! a stanza id, an asset's uuid — so a re-read writes nothing twice. //! * **A cursor is an OPTIMISATION**, kept in `_ingest_cursors` inside the //! replica so deleting the file forgets the positions with it. pub mod apple_schema; pub mod attributed_body; pub mod media_leg; pub mod messages_schema; pub mod profile_pictures; pub mod snapshot; pub mod sources; use cotton_core::import::envelope::ImportBatch; use serde::{Deserialize, Serialize}; pub use snapshot::{classify_read_failure, open_live_copy}; /// The readers this Mac has. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "camelCase")] pub enum SourceId { CallHistory, Messages, Photos, WhatsappLink, } impl SourceId { pub const ALL: [SourceId; 4] = [ SourceId::CallHistory, SourceId::Messages, SourceId::Photos, SourceId::WhatsappLink, ]; pub const fn as_str(self) -> &'static str { match self { SourceId::CallHistory => "callHistory", SourceId::Messages => "messages", SourceId::Photos => "photos", SourceId::WhatsappLink => "whatsappLink", } } pub fn parse(value: &str) -> Option { SourceId::ALL.into_iter().find(|id| id.as_str() == value) } /// The source position on the device that read it. A served snapshot can /// carry this table to another Mac, whose source has a different position. /// Old unscoped keys are ignored; source row ids make rereads idempotent. pub fn cursor_key(self, device_id: &str) -> String { format!("ingest:{device_id}:{}:cursor", self.as_str()) } } /// Whether this Mac can read the source right now. /// /// A permission failure is a STATE, never an error: `EPERM` on /// `~/Library/Application Support/CallHistoryDB` means the person has not granted Full Disk Access, and /// the answer is a button that opens the right pane of System Settings — not a /// retry loop against a decision only they can make. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum SourceState { Ready, NoPermission, NotFound, Error, } impl SourceState { pub const fn as_str(self) -> &'static str { match self { SourceState::Ready => "ready", SourceState::NoPermission => "no_permission", SourceState::NotFound => "not_found", SourceState::Error => "error", } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct SourceStatus { pub state: SourceState, /// One sentence for the person, when there is something to say. #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option, /// How many rows the source holds, when the probe could count them cheaply. #[serde(skip_serializing_if = "Option::is_none")] pub total: Option, } impl SourceStatus { pub fn ready(total: i64) -> SourceStatus { SourceStatus { state: SourceState::Ready, detail: None, total: Some(total), } } pub fn not_found(detail: impl Into) -> SourceStatus { SourceStatus { state: SourceState::NotFound, detail: Some(detail.into()), total: None, } } pub fn no_permission(detail: impl Into) -> SourceStatus { SourceStatus { state: SourceState::NoPermission, detail: Some(detail.into()), total: None, } } pub fn error(detail: impl Into) -> SourceStatus { SourceStatus { state: SourceState::Error, detail: Some(detail.into()), total: None, } } } /// Where a reader got to, as the reader itself spells it. /// /// OPAQUE to everything but its own source: Messages carries a ROWID per file /// (two files, one reader), call history carries a `Z_PK`, and the WhatsApp /// backup carries the backup's own identity beside a `Z_PK`. The queue stores /// the string and never reads it. pub type SourceCursor = String; pub use crate::messages_import::MediaFile as IngestMediaFile; /// One call as a DEVICE reports it — the reader's vocabulary, not the row's. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DeviceCall { pub source: String, /// The source's own stable id. Two readers must never invent one. pub external_id: String, pub provider: String, pub direction: String, pub outcome: String, /// ISO-8601 UTC. pub started_at: String, pub duration_s: i64, /// The number or address as dialled. Resolved to a contact and a person by /// the applier, never by the reader: a reader knows a number, and only the /// file knows whose it is. pub handle: Option, /// How to read `handle`. `phone`, which is what a call log holds, or /// `email` for an Apple ID. pub handle_kind: String, /// The name the phone showed for the number, when it knew one. Used only /// to find the person when the number matches nobody in the file — never /// stored, never a new person. pub name: Option, /// The ingesting machine's label. pub device: Option, pub meta: serde_json::Map, } /// One voter's whole choice on a poll: the poll by its own id on the channel, the voter as the import keys an actor /// (`owner`, else their number), and the options picked as WhatsApp hashes them (hex SHA-256 of the words). #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PollVote { pub external_id: String, pub actor: String, pub options: Vec, pub at: String, } /// One unit of work a source hands the queue. /// /// A UNION, and it is the seam bytes arrive through. Attachments are NOT a third /// arm, because the offline-first media rule says a row is written with its /// object key and a `_media` ledger row is queued in the SAME beat. So bytes /// ride along with the messages that reference them. #[derive(Debug, Clone, PartialEq)] pub enum IngestWork { Messages { request: Box, media: Vec, }, Calls { calls: Vec, }, /// One page of the Photos library — assets, their faces, and the clusters /// those faces name. /// /// Boxed because it is much the largest arm: a hundred assets each carrying /// twenty-odd Apple columns would otherwise set the size of EVERY batch, /// including a batch of two calls. Photos(Box), /// Changes to messages already written: edits, deletes for everyone, /// reactions — keyed by the message's own id on `channel`. MessageChanges { workspace_id: String, channel: String, changes: Vec, }, /// Votes on polls already written (WhatsApp's), each a voter's whole choice: `meta.poll` of the poll message /// named by its own id is counted again (`cotton_core::import::poll::apply_vote`). PollVotes { workspace_id: String, channel: String, votes: Vec, }, /// WhatsApp profile pictures, each for the person or group it belongs to. /// Applying one stores it only where the picture is empty or still /// WhatsApp's: see `ingest::profile_pictures`. ProfilePictures { workspace_id: String, pictures: Vec, }, } #[derive(Debug, Clone, PartialEq)] pub struct IngestBatch { pub work: IngestWork, /// How many SOURCE rows this batch stands for — what the "read" count /// counts. pub read: i64, /// Where the source has got to, once this batch is safely written. /// /// Optional because not every reader can say so at every batch. When it is /// absent the run's final cursor is the only one persisted, and an /// interrupted pass re-reads — which costs time and writes nothing, because /// every row carries its own id. pub cursor: Option, } /// What the panel draws while a source runs. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)] #[serde(rename_all = "camelCase")] pub struct IngestProgress { /// Rows read out of the source. pub read: i64, /// Rows the import engine actually wrote (a re-run writes none). pub written: i64, /// Rows it skipped because this file already had them. pub skipped: i64, /// Rows the reader itself dropped, with `notes` saying why. pub dropped: i64, /// How many rows the source holds in total, when it could be counted. #[serde(skip_serializing_if = "Option::is_none")] pub total: Option, } pub use crate::messages_import::{count, Notes as IngestNotes}; /// How many envelopes go in one batch — the engine's transaction size. pub const MAX_ENVELOPES_PER_BATCH: usize = 500; /// What a source emits a batch through. Fallible, because the applier is. pub type Emit<'a> = &'a mut dyn FnMut(IngestBatch) -> Result<(), String>; /// What one pass over a source read, and how it got there. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct ReadOutcome { pub cursor: SourceCursor, pub notes: IngestNotes, } /// How a source wakes. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Triggers { /// Paths to watch. A change here runs the source after a debounce. pub watch: Vec, /// The poll floor under a watch macOS can drop on its own. pub every_ms: u64, } /// One reader. pub trait IngestSource: Send { fn id(&self) -> SourceId; /// Can this Mac read it right now? Tells "no permission" from "not set up". fn probe(&self) -> SourceStatus; /// Read everything past `cursor`, emitting batches, and answer the new /// cursor. /// /// The cursor is an OPTIMISATION, not a correctness device: every row /// carries the source's own stable id, so a re-read after a crash re-emits /// rows the import engine already has and it skips them. fn read(&self, cursor: Option<&str>, emit: Emit<'_>) -> Result; /// Take in the source's own settings from the file it writes into, just /// before a read: a switch on its connection row reaches the very next /// pass, on a serving Mac and a replica alike. Most sources have none. fn read_settings(&self, _db: &cotton_store::Driver, _workspace_id: &str) -> Result<(), String> { Ok(()) } fn triggers(&self) -> Triggers; } /// How many rows the reader itself threw away. /// /// Two prefixes are excluded, each for its own reason. `read:` is a count /// of rows LOOKED at rather than dropped. `media:` is about a FILE, not /// a row: an attachment this Mac could not find, or the server would not sign, /// is a message that lands with its words and without its picture, and counting /// it as a dropped row would tell a person they lost messages they did not lose. /// Both are excluded by name rather than by a prefix rule nobody would remember. pub fn dropped_from(notes: &IngestNotes) -> i64 { notes .iter() .filter(|(key, _)| !key.starts_with("read:") && !key.starts_with("media:")) .map(|(_, value)| *value) .sum() } #[cfg(test)] #[path = "mod_tests.rs"] mod tests; #[cfg(test)] #[path = "import_fixtures_tests.rs"] mod import_fixtures_tests; /// Live Apple data sources have no Linux counterpart. Portable readers of /// explicitly supplied backup files remain usable by callers on every OS. pub const APPLE_SOURCES_UNAVAILABLE: &str = "Local call history and Photos sources are not available on Linux: these libraries are maintained by macOS. Synced records and media remain available.";