//! SEND — a person gives a copy of something they own to one of their people //! (owner, 13 Nov 2026). One rule decides what a send CONTAINS and how it //! LANDS, shared by the phone (natively) and the Worker (as WASM, through the //! asked door: [`crate::import::asked::run`] `send.*`). //! //! **A table declares its send shape** in its kit (`send`, [`SendSpec`]): //! the columns that go, the photo and file columns whose bytes go with them, //! the related rows that travel in their own tables' shapes (`with`), the //! linked records that travel only as enough identity to be found or made at //! the other end (`carry`), and the column sets that say a record is one the //! receiver already holds (`same`). Every column the shape does not name //! stays behind (fail closed): a column added later never travels until the //! kit says so. A table with no shape cannot be sent; a sealed table can //! never declare one ([`validate`]). //! //! **What travels is data**: a [`Payload`], one self-contained, versioned //! JSON value (`format: "cotton.send"`, `version: 1`). It names the sender's //! media keys and their sizes and never carries a byte: the Worker copies //! bytes R2 to R2 at Keep. The same payload can later travel as a file (a zip //! of `send.json` and `media/`, the package's media layout) and land //! through the same [`keep`]. //! //! **How it lands** ([`keep`]): every record gets an id of its own, derived //! from the send's id and its old id (so a Keep run twice lands the same //! rows), its links re-pointed inside the send, its media keys moved under the //! receiver's database (and any path segment that was an old record id, a //! film's folder, renamed with it), and the provenance columns stamped //! ([`PROVENANCE`]). A record the receiver already holds (`same`) is not made //! again: its id maps to the held one, and what hangs off it does not land. A //! carried record found is linked to; one not found is made from what was //! carried. use std::collections::{BTreeMap, BTreeSet, HashMap}; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use sha2::{Digest, Sha256}; /// The payload format's name and the version this build writes and reads. pub const FORMAT: &str = "cotton.send"; pub const VERSION: u32 = 1; /// The columns every sendable table declares, stamped on each record a Keep /// makes: who sent it (their name, as the receiver knows them, else as the /// send says it: text, never a link, so a single-app kit that keeps no /// people still keeps it), the number it came from, when it was sent, and /// the send it came in (what Undo removes by). pub const PROVENANCE: [&str; 4] = ["sent_by", "sent_by_number", "sent_at", "send_id"]; /// At most this many records in one send: a list of books, an album's songs, /// a series' episodes all fit; a whole library is a package, not a send. pub const RECORDS_MAX: usize = 2_000; /// How deep `with` reaches: a film, its seasons, their episodes. pub const DEPTH_MAX: usize = 4; // ── the shape a kit declares ──────────────────────────────────────────── /// A table's `send` block. /// /// ```json /// "send": { /// "columns": ["title", "author", "cover", "file", "isbn"], /// "files": ["cover", "file"], /// "same": [["file"], ["isbn"]], /// "with": [{ "table": "recipe_ingredient", "by": "recipe" }], /// "carry": { "book": ["title", "author", "isbn"] } /// } /// ``` #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SendSpec { /// The columns that travel. Every other column stays with the sender. pub columns: Vec, /// Photo and file columns (named in `columns`) whose bytes travel. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub files: Vec, /// File columns (named in `files`) whose key names one file of a folder /// that travels whole: a film's HLS folder, under its master playlist. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub folders: Vec, /// Column sets: a record whose every column in one set equals a held /// record's is that record (the same file, the same ISBN). Media keys /// compare as the receiver's. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub same: Vec>, /// Related rows that travel in their own tables' send shapes. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub with: Vec, /// Link columns whose record travels only as these of its columns: found /// at the other end by its table's `same`, else made from them. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub carry: BTreeMap>, } /// Rows of `table` that link to the sent record by `by`. With `record` (and /// the sent record's `table_of` column naming a table), each such row is a /// join naming a record of that table by id: the join row travels, and so /// does the record it names, in its own shape (a list's members). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct With { pub table: String, pub by: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub record: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub table_of: Option, } /// What the rule knows of one table: its columns and its shape. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct TableShape { pub columns: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub send: Option, /// The table's rows are sealed on the object (a `seal` block or /// `sealed: true`): never sendable. #[serde(default)] pub sealed: bool, } #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct ColumnShape { pub key: String, #[serde(rename = "type")] pub column_type: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub link_to: Option, #[serde(default)] pub computed: bool, } impl TableShape { fn column(&self, key: &str) -> Option<&ColumnShape> { self.columns.iter().find(|c| c.key == key) } } /// The tables a send reads, by id. pub type Tables = BTreeMap; /// Why a shape, a send or a payload is refused, in words. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Refused { pub words: String, pub code: &'static str, } fn refused(code: &'static str, words: impl Into) -> Refused { Refused { words: words.into(), code } } /// `refusal.` in the kit's words, each `{name}` filled: the phone and the /// Worker refuse a send in the same words, and a rewording is a line. fn say(key: &str, fills: &[(&str, &str)]) -> String { crate::lines::resolve("refusal", key, fills) } /// Is `table`'s shape sound against its own columns and the other tables? pub fn validate(table: &str, tables: &Tables) -> Result<(), Refused> { let Some(shape) = tables.get(table) else { return Err(refused("no_table", say("send.no_table", &[("table", table)]))) }; let Some(spec) = &shape.send else { return Ok(()) }; let bad = |words: String| Err(refused("bad_send", format!("{table}.send: {words}"))); if shape.sealed { return bad(say("send.shape.sealed", &[])); } if spec.columns.is_empty() { return bad(say("send.shape.no_columns", &[])); } for name in PROVENANCE { if shape.column(name).is_none() { return bad(say("send.shape.no_provenance", &[("name", name)])); } } for name in &spec.columns { let Some(column) = shape.column(name) else { return bad(say("send.shape.not_a_column", &[("name", name)])) }; if column.computed { return bad(say("send.shape.worked_out", &[("name", name)])); } if PROVENANCE.contains(&name.as_str()) { return bad(say("send.shape.provenance_sent", &[("name", name)])); } } for name in &spec.files { let typed = shape.column(name).map(|c| c.column_type.as_str()); if !spec.columns.contains(name) || !matches!(typed, Some("photo" | "file")) { return bad(say("send.shape.files", &[("name", name)])); } } for name in &spec.folders { if !spec.files.contains(name) { return bad(say("send.shape.folders", &[("name", name)])); } } for set in &spec.same { if set.is_empty() || set.iter().any(|k| !spec.columns.contains(k) && !spec.carry.contains_key(k)) { return bad(say("send.shape.same", &[])); } } for with in &spec.with { let Some(other) = tables.get(&with.table) else { return bad(say("send.shape.with_not_a_table", &[("with", &with.table)])) }; if other.send.is_none() { return bad(say("send.shape.with_no_shape", &[("with", &with.table)])); } if other.column(&with.by).and_then(|c| c.link_to.as_deref()) != Some(table) { return bad(say("send.shape.with_not_a_link", &[("with", &with.table), ("by", &with.by), ("table", table)])); } match (&with.record, &with.table_of) { (None, None) => {} (Some(record), Some(table_of)) => { if other.column(record).is_none() || shape.column(table_of).is_none() || !spec.columns.contains(table_of) { return bad(say("send.shape.with_record", &[("with", &with.table), ("record", record), ("table_of", table_of)])); } } _ => return bad(say("send.shape.with_together", &[])), } } for (link, carried) in &spec.carry { let Some(target) = shape.column(link).and_then(|c| c.link_to.clone()) else { return bad(say("send.shape.carry_not_a_link", &[("link", link)])) }; let Some(other) = tables.get(&target) else { return bad(say("send.shape.carry_not_a_table", &[("link", link), ("target", &target)])) }; if other.send.is_none() { return bad(say("send.shape.carry_no_shape", &[("target", &target)])); } if carried.is_empty() || carried.iter().any(|k| other.column(k).is_none_or(|c| c.computed)) { return bad(say("send.shape.carry_columns", &[("link", link), ("target", &target)])); } } Ok(()) } // ── the payload ───────────────────────────────────────────────────────── /// What travels: everything one send is, self-contained. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Payload { pub format: String, pub version: u32, /// The send's own id: what the receiver's rows name in `send_id`. pub id: String, pub from: From, pub made_at: String, /// The database the records were written in: their media keys start `/`. pub source_database: String, pub root: Ref, /// The root record's title, as its table's `title` column says. pub title: String, pub records: Vec, pub files: Vec, /// Every file's bytes together. pub bytes: u64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct From { pub number: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct Ref { pub table: String, pub id: String, } /// One record that travels, in its table's shape. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SentRecord { pub table: String, pub id: String, pub data: Map, pub role: Role, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Role { /// What was sent. Root, /// A related row, or a list's member. With, /// A linked record, as identity only: found, or made. Carried, } /// One media key a record names, and what it weighs. `folder`: the key is /// one file of a folder that travels whole (its every file is counted in /// `bytes`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SentFile { pub key: String, pub bytes: u64, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub folder: bool, } /// Reads a rule asks of the store it runs against: the sender's object at /// [`contents`], the receiver's at [`keep`] and [`held`]. pub trait Reads { /// One live record, or none. fn row(&self, table: &str, id: &str) -> Result>, String>; /// Live records of `table` whose `column` holds `id`, each with its `id`. fn linked(&self, table: &str, column: &str, id: &str) -> Result>, String>; /// Ids of live records of `table` whose every column in `equals` holds /// that value. fn find(&self, table: &str, equals: &Map) -> Result, String>; /// The bytes held under a media key (`folder`: every file under the /// key's folder together), or none. fn weigh(&self, key: &str, folder: bool) -> Result, String>; } /// What the sender's object hands [`contents`] beside the reads. #[derive(Debug, Clone, Deserialize)] pub struct Make { pub id: String, pub table: String, pub record: String, pub from: From, pub made_at: String, pub source_database: String, pub tables: Tables, } /// Is `table` sendable at all: a shape, on a table that is not sealed. pub fn sendable(table: &str, tables: &Tables) -> Result<(), Refused> { let shape = tables.get(table).ok_or_else(|| refused("no_table", say("send.no_table", &[("table", table)])))?; if shape.sealed { return Err(refused("not_sendable", say("send.sealed", &[]))); } if shape.send.is_none() { return Err(refused("not_sendable", say("send.not_sendable", &[]))); } validate(table, tables) } /// Everything one record sends: itself in its shape, its `with` rows, its /// list's members and their own, and its carried identities. pub fn contents(make: &Make, reads: &dyn Reads) -> Result { sendable(&make.table, &make.tables)?; let read = |e: String| refused("read_failed", e); let root = reads.row(&make.table, &make.record).map_err(read)?.ok_or_else(|| refused("not_found", say("send.gone", &[])))?; let mut gather = Gather { tables: &make.tables, reads, records: Vec::new(), seen: BTreeSet::new(), files: BTreeMap::new() }; gather.record(&make.table, &make.record, &root, Role::Root, 0, None)?; let title = title_of(&make.tables, &make.table, &root); let mut files: Vec = Vec::new(); for ((key, folder), ()) in gather.files { let bytes = reads.weigh(&key, folder).map_err(read)?.ok_or_else(|| refused("missing_media", say("send.missing_media", &[("title", &title)])))?; files.push(SentFile { key, bytes, folder }); } let bytes = files.iter().map(|f| f.bytes).sum(); Ok(Payload { format: FORMAT.into(), version: VERSION, id: make.id.clone(), from: make.from.clone(), made_at: make.made_at.clone(), source_database: make.source_database.clone(), root: Ref { table: make.table.clone(), id: make.record.clone() }, title, records: gather.records, files, bytes, }) } struct Gather<'a> { tables: &'a Tables, reads: &'a dyn Reads, records: Vec, seen: BTreeSet, files: BTreeMap<(String, bool), ()>, } impl Gather<'_> { fn record(&mut self, table: &str, id: &str, row: &Map, role: Role, depth: usize, by: Option<&str>) -> Result<(), Refused> { let at = Ref { table: table.into(), id: id.into() }; if !self.seen.insert(at) { return Ok(()); } if self.records.len() >= RECORDS_MAX { return Err(refused("too_many", say("send.too_many", &[("max", &RECORDS_MAX.to_string())]))); } let shape = &self.tables[table]; let spec = shape.send.as_ref().ok_or_else(|| refused("not_sendable", say("send.table_not_sendable", &[("table", table)])))?; let mut data = Map::new(); for key in &spec.columns { if let Some(value) = row.get(key).filter(|v| !v.is_null()) { data.insert(key.clone(), value.clone()); } } // A with row keeps its link to what it hangs off, re-pointed at Keep. if let Some(by) = by { if let Some(value) = row.get(by) { data.insert(by.to_string(), value.clone()); } } for key in &spec.files { if let Some(Value::String(media)) = data.get(key) { if !media.is_empty() { self.files.insert((media.clone(), spec.folders.contains(key)), ()); } } } // The carried links travel as their target's id, and the target as identity. let mut carried = Vec::new(); for (link, columns) in &spec.carry { if let Some(Value::String(target)) = row.get(link) { data.insert(link.clone(), json!(target)); let target_table = shape.column(link).and_then(|c| c.link_to.clone()).unwrap_or_default(); carried.push((target_table, target.clone(), columns.clone())); } } self.records.push(SentRecord { table: table.into(), id: id.into(), data, role }); for (target_table, target, columns) in carried { if self.seen.contains(&Ref { table: target_table.clone(), id: target.clone() }) { continue; } let Some(linked) = self.reads.row(&target_table, &target).map_err(|e| refused("read_failed", e))? else { continue }; self.seen.insert(Ref { table: target_table.clone(), id: target.clone() }); let mut data = Map::new(); for key in &columns { if let Some(value) = linked.get(key).filter(|v| !v.is_null()) { data.insert(key.clone(), value.clone()); } } // A carried photo travels with it (a book's cover beside a highlight's words): its bytes are counted. let target_shape = &self.tables[&target_table]; for key in &columns { let photo = target_shape.column(key).is_some_and(|c| c.column_type == "photo"); if let (true, Some(Value::String(media))) = (photo, data.get(key)) { self.files.insert((media.clone(), false), ()); } } self.records.push(SentRecord { table: target_table, id: target, data, role: Role::Carried }); } if depth >= DEPTH_MAX { return Ok(()); } for with in &spec.with { let rows = self.reads.linked(&with.table, &with.by, id).map_err(|e| refused("read_failed", e))?; for child in rows { let Some(child_id) = child.get("id").and_then(Value::as_str).map(str::to_string) else { continue }; if let (Some(record), Some(table_of)) = (&with.record, &with.table_of) { let member_table = row.get(table_of).and_then(Value::as_str).unwrap_or_default().to_string(); let member_id = child.get(record).and_then(Value::as_str).unwrap_or_default().to_string(); let Some(member_shape) = self.tables.get(&member_table) else { continue }; if member_shape.sealed || member_shape.send.is_none() { return Err(refused("not_sendable", say("send.list_not_sendable", &[]))); } let Some(member) = self.reads.row(&member_table, &member_id).map_err(|e| refused("read_failed", e))? else { continue }; self.record(&member_table, &member_id, &member, Role::With, depth + 1, None)?; } self.record(&with.table, &child_id, &child, Role::With, depth + 1, Some(&with.by))?; } } Ok(()) } } fn title_of(tables: &Tables, table: &str, row: &Map) -> String { let spec = tables.get(table).and_then(|t| t.send.as_ref()); let first_text = spec .and_then(|s| s.columns.iter().find(|k| tables[table].column(k).is_some_and(|c| c.column_type == "text" || c.column_type == "longtext"))) .and_then(|k| row.get(k)) .and_then(Value::as_str); ["title", "name", "full_name", "text"] .iter() .find_map(|k| row.get(*k).and_then(Value::as_str)) .or(first_text) .unwrap_or("") .chars() .take(200) .collect() } /// A payload as read from the wire or a file: the format and version this /// build reads, and records only of tables that are sendable here. pub fn read_payload(value: Value, tables: &Tables) -> Result { let payload: Payload = serde_json::from_value(value).map_err(|e| refused("bad_payload", say("send.payload.unreadable", &[("error", &e.to_string())])))?; if payload.format != FORMAT || payload.version != VERSION { return Err(refused("bad_payload", say("send.payload.version", &[("format", &payload.format), ("version", &payload.version.to_string()), ("reads_format", FORMAT), ("reads_version", &VERSION.to_string())]))); } if payload.records.len() > RECORDS_MAX || !payload.records.iter().any(|r| r.role == Role::Root && r.table == payload.root.table && r.id == payload.root.id) { return Err(refused("bad_payload", say("send.payload.no_root", &[]))); } for record in &payload.records { let shape = tables.get(&record.table).ok_or_else(|| refused("not_sendable", say("send.payload.not_a_table", &[("table", &record.table)])))?; let spec = shape.send.as_ref().filter(|_| !shape.sealed).ok_or_else(|| refused("not_sendable", say("send.payload.not_received", &[("table", &record.table)])))?; let allowed: BTreeSet<&str> = spec.columns.iter().chain(spec.carry.keys()).map(String::as_str).chain(spec.with.iter().map(|w| w.by.as_str())).collect(); if record.role != Role::Carried { if let Some(name) = record.data.keys().find(|k| !allowed.contains(k.as_str()) && !is_by_of_some_with(tables, &record.table, k)) { return Err(refused("bad_payload", say("send.payload.does_not_travel", &[("table", &record.table), ("name", name)]))); } } } Ok(payload) } fn is_by_of_some_with(tables: &Tables, table: &str, column: &str) -> bool { tables.values().filter_map(|t| t.send.as_ref()).any(|s| s.with.iter().any(|w| w.table == table && (w.by == column || w.record.as_deref() == Some(column)))) } // ── landing ───────────────────────────────────────────────────────────── /// What the receiver's object hands [`keep`] and [`held`] beside the reads. #[derive(Debug, Clone, Deserialize)] pub struct Land { pub payload: Value, pub tables: Tables, /// The receiver's database: media keys move under `/`. pub database: String, /// The sender's name as the receiver knows them, when the host knows it; /// else the name the send carries. #[serde(default)] pub sent_by: Option, /// When the send arrived (provenance `sent_at`). pub sent_at: String, } /// What a Keep makes: the rows to create in order (each one's links already /// inside the send, or held), the bytes to copy, and what was already held. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Landing { pub creates: Vec, pub copies: Vec, /// Records the receiver already held, each with the held id. pub held: Vec, /// The bytes the copies add (a copy onto a key already holding its bytes is the host's to skip). pub bytes: u64, /// The root record as it lands: its new id, or the held one. pub root: Ref, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Create { pub table: String, pub id: String, pub data: Map, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Copy { pub from: String, pub to: String, pub bytes: u64, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub folder: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Held { pub table: String, pub sent: String, pub id: String, } /// The id a sent record lands under: derived from the send and its old id, /// so the same send kept twice makes the same rows. pub fn landed_id(send: &str, table: &str, old: &str) -> String { let digest = Sha256::digest(format!("cotton.send.v1\0{send}\0{table}\0{old}").as_bytes()); let h = hex::encode(&digest[..16]); format!("{}-{}-5{}-{}{}-{}", &h[0..8], &h[8..12], &h[13..16], ['8', '9', 'a', 'b'][usize::from(digest[8] & 3)], &h[17..20], &h[20..32]) } /// What the receiver already holds of a send, before anything lands: each /// record `same` finds, sent id to held id. pub fn held(land: &Land, reads: &dyn Reads) -> Result, Refused> { let payload = read_payload(land.payload.clone(), &land.tables)?; let moved = Moves::of(&payload, &land.database); let mut ids = HashMap::new(); let mut out = Vec::new(); for record in order(&payload, &land.tables) { if let Some(id) = find_held(&land.tables, record, &moved, &ids, reads)? { ids.insert((record.table.clone(), record.id.clone()), id.clone()); out.push(Held { table: record.table.clone(), sent: record.id.clone(), id }); } } Ok(out) } /// The Keep: what lands, in order, and the bytes it copies. pub fn keep(land: &Land, reads: &dyn Reads) -> Result { let payload = read_payload(land.payload.clone(), &land.tables)?; let moved = Moves::of(&payload, &land.database); // Each record found held maps to the held one; the rest land under fresh ids. let mut ids: HashMap<(String, String), String> = HashMap::new(); let mut held_out = Vec::new(); for record in order(&payload, &land.tables) { if let Some(id) = find_held(&land.tables, record, &moved, &ids, reads)? { held_out.push(Held { table: record.table.clone(), sent: record.id.clone(), id: id.clone() }); ids.insert((record.table.clone(), record.id.clone()), id); } } let held_keys: BTreeSet<(String, String)> = held_out.iter().map(|h| (h.table.clone(), h.sent.clone())).collect(); // What hangs off a held record (its with rows) does not land: the receiver's own stay as they are. let skipped = hanging_off(&payload, &land.tables, &held_keys); for record in &payload.records { let key = (record.table.clone(), record.id.clone()); if !ids.contains_key(&key) && !skipped.contains(&key) { ids.insert(key, landed_id(&payload.id, &record.table, &record.id)); } } let mut creates = Vec::new(); let mut used_media: BTreeSet = BTreeSet::new(); for record in order(&payload, &land.tables) { let key = (record.table.clone(), record.id.clone()); if held_keys.contains(&key) || skipped.contains(&key) { continue; } let shape = &land.tables[&record.table]; let mut data = Map::new(); for (column, value) in &record.data { let Some(col) = shape.column(column) else { continue }; if col.computed { continue; } let value = match (col.column_type.as_str(), &col.link_to) { ("link", Some(target)) => match value.as_str().and_then(|old| ids.get(&(target.clone(), old.to_string()))) { Some(new) => json!(new), // A link to nothing that travelled is dropped: the receiver's records are theirs. None => continue, }, ("photo" | "file", _) => match value.as_str() { Some(media) => { let to = moved.key(media); used_media.insert(media.to_string()); json!(to) } None => continue, }, _ => value.clone(), }; data.insert(column.clone(), value); } // A join row's record id (a list's member) is re-pointed as a link is; one naming nothing that landed or is held is not made. let mut lost = false; for with in land.tables.values().filter_map(|t| t.send.as_ref()).flat_map(|s| s.with.iter()) { if with.table != record.table { continue; } if let Some(column) = &with.record { let member = payload.records.iter().find(|r| Some(&r.id) == record.data.get(column).and_then(Value::as_str).map(str::to_string).as_ref() && r.table != record.table); match member.and_then(|m| ids.get(&(m.table.clone(), m.id.clone()))) { Some(new) => { data.insert(column.clone(), json!(new)); } None => lost = true, } } } if lost { continue; } data.insert("sent_by".into(), land.sent_by.clone().or_else(|| payload.from.name.clone()).map(Value::String).unwrap_or(Value::Null)); data.insert("sent_by_number".into(), json!(payload.from.number)); data.insert("sent_at".into(), json!(land.sent_at)); data.insert("send_id".into(), json!(payload.id)); let id = ids[&key].clone(); creates.push(Create { table: record.table.clone(), id, data }); } let mut copies = Vec::new(); for file in &payload.files { if !used_media.contains(&file.key) { continue; } copies.push(Copy { from: file.key.clone(), to: moved.key(&file.key), bytes: file.bytes, folder: file.folder }); } copies.sort_by(|a, b| a.to.cmp(&b.to)); copies.dedup_by(|a, b| a.to == b.to); let bytes = copies.iter().map(|c| c.bytes).sum(); let root_id = ids.get(&(payload.root.table.clone(), payload.root.id.clone())).cloned().unwrap_or_default(); Ok(Landing { creates, copies, held: held_out, bytes, root: Ref { table: payload.root.table.clone(), id: root_id } }) } /// A sent media key as the receiver keeps it: under their database, with /// each path segment that was a sent record's id renamed to its new id. struct Moves { from: String, to: String, renames: HashMap, } impl Moves { fn of(payload: &Payload, database: &str) -> Self { let renames = payload.records.iter().map(|r| (r.id.clone(), landed_id(&payload.id, &r.table, &r.id))).collect(); Self { from: format!("{}/", payload.source_database), to: format!("{database}/"), renames } } fn key(&self, key: &str) -> String { let rest = key.strip_prefix(&self.from).unwrap_or(key); let rest: Vec = rest.split('/').map(|segment| self.renames.get(segment).cloned().unwrap_or_else(|| segment.to_string())).collect(); format!("{}{}", self.to, rest.join("/")) } /// The key as compared for `same`: content-addressed keys compare by /// their bytes' name alone, whatever folder renaming would give. fn compared(&self, key: &str) -> String { let rest = key.strip_prefix(&self.from).unwrap_or(key); format!("{}{rest}", self.to) } } fn find_held(tables: &Tables, record: &SentRecord, moved: &Moves, ids: &HashMap<(String, String), String>, reads: &dyn Reads) -> Result, Refused> { let shape = &tables[&record.table]; let Some(spec) = &shape.send else { return Ok(None) }; for set in &spec.same { let mut equals = Map::new(); for column in set { let Some(value) = record.data.get(column).filter(|v| !v.is_null() && v.as_str() != Some("")) else { equals.clear(); break; }; let is_media = shape.column(column).is_some_and(|c| c.column_type == "photo" || c.column_type == "file"); let link = shape.column(column).and_then(|c| c.link_to.clone()); let value = match (is_media, link, value.as_str()) { (true, _, Some(key)) => json!(moved.compared(key)), // A link compares as the receiver's record it maps to: one held already (a carried book found). (_, Some(target), Some(old)) => match ids.get(&(target, old.to_string())) { Some(id) => json!(id), None => { equals.clear(); break; } }, _ => value.clone(), }; equals.insert(column.clone(), value); } if equals.is_empty() { continue; } let found = reads.find(&record.table, &equals).map_err(|e| refused("read_failed", e))?; if let Some(id) = found.into_iter().next() { return Ok(Some(id)); } } Ok(None) } /// The with rows (to any depth) of records already held: they stay behind. fn hanging_off(payload: &Payload, tables: &Tables, held: &BTreeSet<(String, String)>) -> BTreeSet<(String, String)> { let mut out: BTreeSet<(String, String)> = BTreeSet::new(); let mut grew = true; while grew { grew = false; for record in &payload.records { let key = (record.table.clone(), record.id.clone()); if record.role != Role::With || out.contains(&key) || held.contains(&key) { continue; } let shape = &tables[&record.table]; let parent_gone = record.data.iter().any(|(column, value)| { let Some(target) = shape.column(column).and_then(|c| c.link_to.clone()) else { return false }; let is_by = tables.get(&target).and_then(|t| t.send.as_ref()).is_some_and(|s| s.with.iter().any(|w| w.table == record.table && &w.by == column && w.record.is_none())); let parent = (target, value.as_str().unwrap_or_default().to_string()); is_by && (held.contains(&parent) || out.contains(&parent)) }); if parent_gone { out.insert(key); grew = true; } } } out } /// The records in an order where everything a record links to comes first. fn order<'a>(payload: &'a Payload, tables: &Tables) -> Vec<&'a SentRecord> { let index: HashMap<(&str, &str), usize> = payload.records.iter().enumerate().map(|(i, r)| ((r.table.as_str(), r.id.as_str()), i)).collect(); let deps: Vec> = payload .records .iter() .map(|record| { let shape = &tables[&record.table]; let mut out = Vec::new(); for (column, value) in &record.data { let Some(old) = value.as_str() else { continue }; if let Some(target) = shape.column(column).and_then(|c| c.link_to.as_deref()) { if let Some(&i) = index.get(&(target, old)) { out.push(i); } } // A join row waits for the member it names. if let Some(i) = payload.records.iter().position(|r| r.id == old && r.table != record.table && r.role != Role::Root) { if !out.contains(&i) && is_by_of_some_with(tables, &record.table, column) { out.push(i); } } } out }) .collect(); let mut done = vec![false; payload.records.len()]; let mut out = Vec::new(); fn visit<'a>(i: usize, payload: &'a Payload, deps: &[Vec], done: &mut [bool], on: &mut BTreeSet, out: &mut Vec<&'a SentRecord>) { if done[i] || !on.insert(i) { return; } for &d in &deps[i] { visit(d, payload, deps, done, on, out); } done[i] = true; out.push(&payload.records[i]); } for i in 0..payload.records.len() { visit(i, payload, &deps, &mut done, &mut BTreeSet::new(), &mut out); } out } /// The shape a send's offer is drawn from, before anything lands: what it is, /// who it is from, how much it weighs, and how many records come with it. pub fn summary(payload: &Payload) -> Value { let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); for record in &payload.records { *counts.entry(record.table.as_str()).or_default() += 1; } json!({ "id": payload.id, "title": payload.title, "root": payload.root, "from": payload.from, "bytes": payload.bytes, "records": counts, "made_at": payload.made_at }) } // ── the doors ─────────────────────────────────────────────────────────── /// [`Reads`] over the asked door's host: `send.row {table, id}`, /// `send.linked {table, column, id}`, `send.find {table, equals}` and /// `send.weigh {key, folder}`, each answered in JSON. pub struct AskedReads<'a, A: crate::import::asked::Ask + ?Sized>(pub &'a A); impl Reads for AskedReads<'_, A> { fn row(&self, table: &str, id: &str) -> Result>, String> { answer(self.0.ask("send.row", json!({ "table": table, "id": id }))?) } fn linked(&self, table: &str, column: &str, id: &str) -> Result>, String> { answer(self.0.ask("send.linked", json!({ "table": table, "column": column, "id": id }))?) } fn find(&self, table: &str, equals: &Map) -> Result, String> { answer(self.0.ask("send.find", json!({ "table": table, "equals": equals }))?) } fn weigh(&self, key: &str, folder: bool) -> Result, String> { answer(self.0.ask("send.weigh", json!({ "key": key, "folder": folder }))?) } } fn answer(value: Value) -> Result { serde_json::from_value(value).map_err(|e| say("send.answer_unreadable", &[("error", &e.to_string())])) } /// The asked runs (`send.contents` → the [`Payload`], `send.keep` → the /// [`Landing`], `send.held` → the [`Held`] list), for the Worker's `plan`. pub fn run(name: &str, input: &str, asker: &A) -> Result { let reads = AskedReads(asker); let bad = |e: serde_json::Error| refused("bad_input", say("send.input_unreadable", &[("name", name), ("error", &e.to_string())])); match name { "send.contents" => { let make: Make = serde_json::from_str(input).map_err(bad)?; Ok(json!(contents(&make, &reads)?)) } "send.keep" => { let land: Land = serde_json::from_str(input).map_err(bad)?; Ok(json!(keep(&land, &reads)?)) } "send.held" => { let land: Land = serde_json::from_str(input).map_err(bad)?; Ok(json!(held(&land, &reads)?)) } _ => Err(refused("bad_input", say("send.no_run", &[("name", name)]))), } } /// The plain rules (no reads), for the boundary: `send.sendable {table, /// tables}` → `{sendable, code?, words?}`, `send.summary {payload, tables}` /// → the offer's summary, `send.landed_id {send, table, id}`. pub fn call(name: &str, input: Value) -> Result { #[derive(Deserialize)] struct Which { table: String, tables: Tables, } #[derive(Deserialize)] struct Read { payload: Value, tables: Tables, } #[derive(Deserialize)] struct Landed { send: String, table: String, id: String, } let bad = |e: serde_json::Error| say("send.input_unreadable", &[("name", name), ("error", &e.to_string())]); match name { "send.sendable" => { let i: Which = serde_json::from_value(input).map_err(bad)?; Ok(match sendable(&i.table, &i.tables) { Ok(()) => json!({ "sendable": true }), Err(r) => json!({ "sendable": false, "code": r.code, "words": r.words }), }) } "send.summary" => { let i: Read = serde_json::from_value(input).map_err(bad)?; read_payload(i.payload, &i.tables).map(|p| summary(&p)).map_err(|r| r.words) } "send.landed_id" => { let i: Landed = serde_json::from_value(input).map_err(bad)?; Ok(json!(landed_id(&i.send, &i.table, &i.id))) } _ => Err(say("send.no_rule", &[("name", name)])), } } #[cfg(test)] #[path = "send_tests.rs"] mod tests;