Cotton code
259 lines · 8.4 KB · RustRaw
//! The pure plan for moving records between databases.//!//! A server coordinator obtains the snapshots while it holds the two database//! files, then commits this plan as one operation.  This module deliberately//! knows neither SQLite nor MCP: it decides the complete payload before either//! home is changed, so a refused member refuses the whole batch.use std::collections::BTreeSet;use super::Data;use serde::{Deserialize, Serialize};/// The stable address of a row, including its storage table.#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]pub struct RecordKey {    pub table: String,    pub id: String,}impl RecordKey {    pub fn new(table: impl Into<String>, id: impl Into<String>) -> Self {        Self {            table: table.into(),            id: id.into(),        }    }}/// A row which travels because it belongs to the record being moved.////// The coordinator discovers these from the store's ownership and reference/// manifests.  Fields are deliberately opaque here: provenance such as the/// record's byline and creation time remains exactly as it was read.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct RelatedSnapshot {    pub table: String,    pub id: String,    pub fields: Data,    /// A supporting parent is carried as reference context and stays at source.    pub reference_only: bool,}impl RelatedSnapshot {    pub fn key(&self) -> RecordKey {        RecordKey::new(self.table.clone(), self.id.clone())    }}/// One record and every already-resolved row that must travel with it.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct Snapshot {    pub table: String,    pub id: String,    pub fields: Data,    pub related: Vec<RelatedSnapshot>,}impl Snapshot {    pub fn key(&self) -> RecordKey {        RecordKey::new(self.table.clone(), self.id.clone())    }}/// The source and destination state the server supplies to the pure planner.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct MoveRequest {    /// Database the snapshots were read from.    pub from: String,    /// Database that will own the records after the move.    pub to: String,    pub snapshots: Vec<Snapshot>,    /// Every row key the destination already owns.  A collision makes the    /// whole batch refuse before either home changes.    pub destination: BTreeSet<RecordKey>,    pub moved_at: String,    pub moved_by: String,}/// What remains at the old home after a record moves.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Tombstone {    pub table: String,    pub id: String,    pub destination: String,    pub moved_at: String,    pub moved_by: String,}/// The complete write set for a successful cross-database move.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct MovePlan {    pub source_tombstones: Vec<Tombstone>,    /// Root records retain their ids and their complete field payloads.    pub destination: Vec<Snapshot>,}/// Why a move batch was refused before it made any change.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum MoveError {    #[error("move needs different source and destination databases")]    SameHome,    #[error("move needs at least one record")]    Empty,    #[error("move names {table} {id} more than once")]    Duplicate { table: String, id: String },    #[error("{table} {id} already exists in the destination database")]    DestinationCollision { table: String, id: String },}/// Make a complete all-or-none move plan.////// The returned destination rows are clones of the source snapshots, rather/// than reconstructed values.  That keeps the caller-visible id, byline,/// creation time, links, comments and every other provenance field intact.pub fn plan(request: MoveRequest) -> Result<MovePlan, MoveError> {    if request.from == request.to {        return Err(MoveError::SameHome);    }    if request.snapshots.is_empty() {        return Err(MoveError::Empty);    }    let mut seen = BTreeSet::new();    for snapshot in &request.snapshots {        validate_key(&mut seen, snapshot.key())?;        for related in &snapshot.related {            validate_key(&mut seen, related.key())?;        }    }    for key in &seen {        if request.destination.contains(key) {            return Err(MoveError::DestinationCollision {                table: key.table.clone(),                id: key.id.clone(),            });        }    }    let source_tombstones = request        .snapshots        .iter()        .map(|snapshot| Tombstone {            table: snapshot.table.clone(),            id: snapshot.id.clone(),            destination: request.to.clone(),            moved_at: request.moved_at.clone(),            moved_by: request.moved_by.clone(),        })        .collect();    Ok(MovePlan {        source_tombstones,        destination: request.snapshots,    })}fn validate_key(seen: &mut BTreeSet<RecordKey>, key: RecordKey) -> Result<(), MoveError> {    if seen.insert(key.clone()) {        Ok(())    } else {        Err(MoveError::Duplicate {            table: key.table,            id: key.id,        })    }}#[cfg(test)]mod tests {    use super::*;    use serde_json::{Map, json};    fn snapshot(id: &str) -> Snapshot {        Snapshot {            table: "cotton_notes".into(),            id: id.into(),            fields: Map::from_iter([                ("body".into(), json!("Keep the receipt")),                ("byline".into(), json!("Maya")),                ("created_at".into(), json!("2026-10-14T05:00:00Z")),            ]),            related: vec![RelatedSnapshot {                table: "cotton_comments".into(),                id: format!("comment-{id}"),                fields: Map::from_iter([("record_id".into(), json!(id))]),                reference_only: false,            }],        }    }    fn request(snapshots: Vec<Snapshot>) -> MoveRequest {        MoveRequest {            from: "Personal".into(),            to: "Cotton".into(),            snapshots,            destination: BTreeSet::new(),            moved_at: "2026-10-14T06:00:00Z".into(),            moved_by: "Asha".into(),        }    }    /// RULE: A moved record keeps its id and provenance, and the old home names the exact destination, because references must still resolve.    #[test]    fn move_keeps_the_payload_and_leaves_a_named_tombstone() {        let original = snapshot("note-1");        let plan = plan(request(vec![original.clone()])).expect("plans");        assert_eq!(plan.destination, vec![original]);        assert_eq!(plan.destination[0].id, "note-1");        assert_eq!(plan.destination[0].fields["byline"], json!("Maya"));        assert_eq!(            plan.destination[0].fields["created_at"],            json!("2026-10-14T05:00:00Z")        );        assert_eq!(plan.destination[0].related[0].id, "comment-note-1");        assert_eq!(            plan.source_tombstones,            vec![Tombstone {                table: "cotton_notes".into(),                id: "note-1".into(),                destination: "Cotton".into(),                moved_at: "2026-10-14T06:00:00Z".into(),                moved_by: "Asha".into(),            }]        );    }    /// RULE: A batch is planned whole before either database changes, so one duplicate or destination collision refuses every record together.    #[test]    fn batch_refusals_are_all_or_none() {        let duplicate = plan(request(vec![snapshot("note-1"), snapshot("note-1")])).unwrap_err();        assert_eq!(            duplicate,            MoveError::Duplicate {                table: "cotton_notes".into(),                id: "note-1".into()            }        );        let mut colliding = request(vec![snapshot("note-1"), snapshot("note-2")]);        colliding            .destination            .insert(RecordKey::new("cotton_notes", "note-2"));        assert_eq!(            plan(colliding).unwrap_err(),            MoveError::DestinationCollision {                table: "cotton_notes".into(),                id: "note-2".into()            }        );    }    /// RULE: Moving inside one database is a no-op with misleading history, so the planner refuses it before a tombstone can be made.    #[test]    fn move_requires_another_home() {        let mut same = request(vec![snapshot("note-1")]);        same.to = same.from.clone();        assert_eq!(plan(same), Err(MoveError::SameHome));    }}