Cotton code
595 lines · 23.0 KB · RustRaw
//! What changes when somebody edits ONE occurrence, cancels ONE occurrence, or//! deletes an event — decided once, in one pure place. The port of//! `packages/core/src/engine/eventEdits.ts`.//!//! There are two writers of `cotton_events`: the phone's service layer//! (`events.service.ts`, through the replica's outbox) and the server's MCP//! (`mcp/records.ts`, straight into the person's file). Two implementations of//! "editing this Tuesday means a new row that claims Tuesday's instant" would//! eventually disagree, and a disagreement here is an appointment that exists//! on one device and not the other — the same class of bug as two//! implementations of who wins in the fold. So the DECISION is here and the two//! writers only carry it out.//!//! Every patch below is keyed by COLUMN NAME. Both writers speak snake_case at//! the point they write, and a planner that spoke camelCase would need a//! translation table on each side — one more thing to disagree about.//!//! A patch is a [`serde_json::Map`] rather than a struct: it is a SPARSE set of//! columns, and the workspace turns on serde_json's `preserve_order`, so it//! serialises in exactly the key order the TypeScript object literal does. An//! op's patch is stored as text, so that order is observable.use serde_json::{Map, Value};use crate::rules::series::{with_exdate, SeriesError};use crate::transforms::zoned_clock::{civil_from_days, day_number, zoned_parts, ZoneError, ZonedParts};use cotton_store::protocol::js::{parse_date_ms, to_iso_string};/// A sparse set of columns to write, keyed by COLUMN NAME.pub type RowPatch = Map<String, Value>;/// Why a plan could not be produced.////// The TypeScript throws in all three cases; a pure library answers instead,/// because every one of them is reachable from a row a stranger's calendar/// wrote.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum EventEditsError {    /// `new Date(NaN).toISOString()` — the runtime's own `RangeError` message,    /// verbatim, so a handler can pass it to the error envelope unchanged. It    /// is reached when the derived `ends_at` would need an instant this crate    /// cannot read: an unparseable `starts_at`/`ends_at` on the master, or an    /// unparseable `startsAt` in the patch.    #[error("Invalid time value")]    InvalidTimeValue,    /// `withExdate` refused the instant being cancelled.    #[error(transparent)]    Series(#[from] SeriesError),    /// The workspace's zone is not one this build's tzdata knows.    #[error(transparent)]    Zone(#[from] ZoneError),}/// The master's fields a plan reads. Snake_case: it is a row on both sides.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct EventRowForPlan {    pub id: String,    /// The calendar the event names, if any: a word about it the object    /// keeps, never what an event belongs to (the database is).    pub collection_id: Option<String>,    pub title: String,    pub notes: Option<String>,    pub location: Option<String>,    pub starts_at: String,    pub ends_at: Option<String>,    pub all_day: bool,    pub rrule: Option<String>,    /// `None` and `[]` read the same — the TypeScript's `readonly string[] |    /// null`.    pub exdates: Option<Vec<String>>,    pub series_id: Option<String>,    pub original_starts_at: Option<String>,    pub gcal_id: Option<String>,    pub sync_state: Option<String>,    pub trashed_at: Option<String>,}impl EventRowForPlan {    /// The two columns [`pending_mark_patch`] reads — the Rust spelling of the    /// TypeScript's `Pick<EventRowForPlan, "gcal_id" | "sync_state">`.    pub fn sync_identity(&self) -> SyncIdentity<'_> {        SyncIdentity {            gcal_id: self.gcal_id.as_deref(),            sync_state: self.sync_state.as_deref(),        }    }}/// A row's Google identity and push state, borrowed.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct SyncIdentity<'a> {    pub gcal_id: Option<&'a str>,    pub sync_state: Option<&'a str>,}/// One editable field of an occurrence edit.////// Three states, not two. The TypeScript distinguishes `undefined` ("leave it/// alone") from `null` ("clear it"), and `Option<Option<String>>` at a call/// site reads as nothing. This is the same correction `moment_split`'s/// `PartChange<T>` makes for the same reason.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub enum FieldChange<T> {    /// The TypeScript's absent key.    #[default]    Unchanged,    /// The TypeScript's explicit `null` — clearing notes is not the same as    /// leaving them.    Cleared,    Set(T),}impl FieldChange<String> {    /// `None` = the key is not written at all; `Some(Null)` = written as null.    fn as_value(&self) -> Option<Value> {        match self {            FieldChange::Unchanged => None,            FieldChange::Cleared => Some(Value::Null),            FieldChange::Set(value) => Some(Value::String(value.clone())),        }    }    /// `patch.x !== undefined ? patch.x : fallback` — the coalescing the    /// TypeScript spells out precisely because `??` would swallow an explicit    /// null.    fn or_row(&self, fallback: Option<&str>) -> Value {        match self {            FieldChange::Unchanged => {                fallback.map_or(Value::Null, |text| Value::String(text.into()))            }            FieldChange::Cleared => Value::Null,            FieldChange::Set(value) => Value::String(value.clone()),        }    }}/// The editable fields an occurrence edit may carry. `Unchanged`/`None` = the/// TypeScript's absent key.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct OccurrencePatch {    pub title: Option<String>,    pub starts_at: Option<String>,    pub ends_at: FieldChange<String>,    pub all_day: Option<bool>,    pub location: FieldChange<String>,    pub notes: FieldChange<String>,}/// What a local edit to a row a calendar door keeps (Google's `gcal_id`, a/// CalDAV server's `sync_state`) marks on it, used by every plan below.////// NOTHING WRITES TO GOOGLE (Days, 20 Nov 2026): the Worker only pulls, and/// no code read a pending mark since write-back was removed (f1d43c1105,/// 26 Oct 2026). A mark saying an edit would be pushed was a quiet lie, so no/// edit is marked; Google's time and title are refused instead/// (`google_read_only`). When write-back is built, this is where it starts.fn pending_if_synced(_row: SyncIdentity<'_>) -> RowPatch {    RowPatch::new()}/// The pending mark on its own — an ordinary edit to a Google-linked row.////// Exported because both writers already had their own copy of this three-line/// rule and one of them will eventually forget it.pub fn pending_mark_patch(row: SyncIdentity<'_>) -> RowPatch {    pending_if_synced(row)}fn merge(into: &mut RowPatch, from: RowPatch) {    for (key, value) in from {        into.insert(key, value);    }}/// Milliseconds an occurrence of this master lasts; 0 when it is open-ended.////// `None` stands for the TypeScript's `NaN`: an unreadable instant on either/// end makes the duration unusable, and every arithmetic that consumed it would/// have produced an `Invalid Date` the caller cannot store.fn duration_of(master: &EventRowForPlan) -> Option<i64> {    let Some(ends_at) = master.ends_at.as_deref() else {        return Some(0);    };    Some(parse_date_ms(ends_at)? - parse_date_ms(&master.starts_at)?)}/// The exception row to write, and whether it is new.#[derive(Debug, Clone, PartialEq)]pub struct OccurrenceEditPlan {    pub exception_id: String,    pub created: bool,    pub patch: RowPatch,    /// The master, when the edit has to mark it pending too. Empty = untouched.    pub master_patch: RowPatch,}/// The arguments of [`plan_occurrence_edit`] — the TypeScript's options object.pub struct OccurrenceEdit<'a> {    pub master: &'a EventRowForPlan,    /// The exception already claiming this instant, if there is one.    pub existing: Option<&'a EventRowForPlan>,    pub occurrence_at: &'a str,    pub patch: &'a OccurrencePatch,    /// Id to mint when there is no exception yet — the caller's id generator.    pub new_id: &'a str,    pub now: &'a str,}/// "This event" on a repeating event.////// The occurrence becomes a ROW — its own title, time, notes and links — that/// claims `occurrence_at` out of the master's expansion. Editing the SAME/// occurrence again patches that row rather than minting a second one, which is/// what keeps the claim single: two rows claiming one instant would drop the/// occurrence from the series and then draw it twice.////// The new row carries NO rrule (an exception does not repeat) and none of the/// master's Google identity: it is a different event up there, materialised by/// the push under the instance id derived from `occurrence_at`.pub fn plan_occurrence_edit(    input: OccurrenceEdit<'_>,) -> Result<OccurrenceEditPlan, EventEditsError> {    let OccurrenceEdit {        master,        existing,        occurrence_at,        patch,        new_id,        now,    } = input;    if let Some(existing) = existing {        let mut update = RowPatch::new();        update.insert("updated_at".into(), Value::String(now.into()));        if let Some(title) = &patch.title {            update.insert("title".into(), Value::String(title.clone()));        }        if let Some(starts_at) = &patch.starts_at {            update.insert("starts_at".into(), Value::String(starts_at.clone()));        }        if let Some(value) = patch.ends_at.as_value() {            update.insert("ends_at".into(), value);        }        if let Some(all_day) = patch.all_day {            update.insert("all_day".into(), Value::Bool(all_day));        }        if let Some(value) = patch.location.as_value() {            update.insert("location".into(), value);        }        if let Some(value) = patch.notes.as_value() {            update.insert("notes".into(), value);        }        merge(&mut update, pending_if_synced(existing.sync_identity()));        return Ok(OccurrenceEditPlan {            exception_id: existing.id.clone(),            created: false,            patch: update,            master_patch: RowPatch::new(),        });    }    // `patch.startsAt ?? occurrenceAt`. The value is stored VERBATIM — an    // offset-bearing spelling is NOT normalised to `…Z`, while the `ends_at`    // derived from it below is, because that one goes through `toISOString`.    let starts_at = patch.starts_at.as_deref().unwrap_or(occurrence_at);    let ends_at = match (&patch.ends_at, master.ends_at.as_deref()) {        (change @ (FieldChange::Cleared | FieldChange::Set(_)), _) => change            .as_value()            .expect("Cleared and Set both carry a value"),        (FieldChange::Unchanged, None) => Value::Null,        (FieldChange::Unchanged, Some(_)) => {            let duration = duration_of(master).ok_or(EventEditsError::InvalidTimeValue)?;            let start = parse_date_ms(starts_at).ok_or(EventEditsError::InvalidTimeValue)?;            Value::String(to_iso_string(start + duration).ok_or(EventEditsError::InvalidTimeValue)?)        }    };    let mut row = RowPatch::new();    row.insert("id".into(), Value::String(new_id.into()));    row.insert(        "collection_id".into(),        master.collection_id.clone().map_or(Value::Null, Value::String),    );    row.insert(        "title".into(),        Value::String(patch.title.clone().unwrap_or_else(|| master.title.clone())),    );    row.insert("notes".into(), patch.notes.or_row(master.notes.as_deref()));    row.insert(        "location".into(),        patch.location.or_row(master.location.as_deref()),    );    row.insert("starts_at".into(), Value::String(starts_at.into()));    row.insert("ends_at".into(), ends_at);    row.insert(        "all_day".into(),        Value::Bool(patch.all_day.unwrap_or(master.all_day)),    );    // An exception does not repeat, and it is not in anybody's bin.    row.insert("rrule".into(), Value::Null);    row.insert("exdates".into(), Value::Null);    row.insert("trashed_at".into(), Value::Null);    row.insert("series_id".into(), Value::String(master.id.clone()));    row.insert(        "original_starts_at".into(),        Value::String(occurrence_at.into()),    );    // Google identity is never copied: the instance is a different resource    // up there, and nothing pushes one (pending_if_synced).    row.insert("gcal_id".into(), Value::Null);    row.insert("gcal_etag".into(), Value::Null);    row.insert("sync_state".into(), Value::Null);    row.insert("organizer_is_self".into(), Value::Bool(true));    row.insert("my_response".into(), Value::Null);    row.insert("created_at".into(), Value::String(now.into()));    row.insert("updated_at".into(), Value::String(now.into()));    Ok(OccurrenceEditPlan {        exception_id: new_id.to_string(),        created: true,        patch: row,        master_patch: RowPatch::new(),    })}/// What a cancelled occurrence changes.#[derive(Debug, Clone, PartialEq)]pub struct OccurrenceCancelPlan {    /// The master's new exdate list, plus its pending mark.    pub master_patch: RowPatch,    /// True when the instant was already cancelled — nothing to write.    pub already_cancelled: bool,    /// An exception standing on that instant, to trash (synced) or remove.    pub trash_exception_id: Option<String>,    pub remove_exception_id: Option<String>,}/// "This event" on a DELETE of a repeating event.////// The instant joins the master's `exdates` and travels to Google inside the/// master's own `recurrence` — one etag-guarded write rather than a second/// resource to keep in step. An exception standing on that instant goes too: a/// cancelled Tuesday whose moved copy survives is the double booking again,/// pointing the other way.pub fn plan_occurrence_cancel(    master: &EventRowForPlan,    exception: Option<&EventRowForPlan>,    occurrence_at: &str,    now: &str,) -> Result<OccurrenceCancelPlan, EventEditsError> {    let exdates = with_exdate(master.exdates.as_deref(), occurrence_at)?;    let already_cancelled =        exdates.len() == master.exdates.as_ref().map_or(0, Vec::len) && exception.is_none();    let mut master_patch = RowPatch::new();    if !already_cancelled {        master_patch.insert(            "exdates".into(),            Value::Array(exdates.into_iter().map(Value::String).collect()),        );        master_patch.insert("updated_at".into(), Value::String(now.into()));        merge(&mut master_patch, pending_if_synced(master.sync_identity()));    }    Ok(OccurrenceCancelPlan {        master_patch,        already_cancelled,        // A synced exception is a real resource on Google; the push DELETEs its        // instance id (a 404 counts as done), so it must be trashed rather than        // dropped. A local one has nowhere else to be.        trash_exception_id: exception            .filter(|row| row.gcal_id.is_some())            .map(|row| row.id.clone()),        remove_exception_id: exception            .filter(|row| row.gcal_id.is_none())            .map(|row| row.id.clone()),    })}/// What deleting a whole event changes.#[derive(Debug, Clone, PartialEq)]pub struct EventDeletePlan {    /// Rows to put in the bin.    pub trash: Vec<String>,    /// The patch each trashed row takes.    pub trash_patch: RowPatch,}/// Deleting a whole event — "All events" on a series, or an ordinary event.////// EVERY event deleted waits in the bin (architect, 5 Oct 2026): a local one/// and a synced one alike are TRASHED, never dropped, and readers hide them./// A row Google knows about also goes `pending`, so the push cancels it up/// there and keeps it in the bin stripped of its Google identity/// (`gcal_sync::push_trashed`); emptying the bin is what erases it here.////// A trashed MASTER takes its exceptions with it and needs no separate mark on/// them: `expand_series` draws nothing for a series whose master is in the bin/// (so no orphan Tuesday survives on the screen), the push DELETEs the master/// at Google — which removes the instances up there in one act — and an erase/// from the bin takes master and exceptions together. Trashing each exception/// as well would put every moved occurrence in the bin as an item of its own,/// which is not what the person deleted.pub fn plan_event_delete(event: &EventRowForPlan, now: &str) -> EventDeletePlan {    let mut trash_patch = RowPatch::new();    trash_patch.insert("trashed_at".into(), Value::String(now.into()));    trash_patch.insert("updated_at".into(), Value::String(now.into()));    merge(&mut trash_patch, pending_if_synced(event.sync_identity()));    EventDeletePlan {        trash: vec![event.id.clone()],        trash_patch,    }}/// Bringing a trashed event back — the Undo of [`plan_event_delete`]. A row/// Google knows about goes `pending` again, so the push hears it is wanted/// rather than deleting it up there; a local one just comes back.pub fn plan_event_untrash(event: &EventRowForPlan, now: &str) -> RowPatch {    let mut patch = RowPatch::new();    patch.insert("trashed_at".into(), Value::Null);    patch.insert("updated_at".into(), Value::String(now.into()));    merge(&mut patch, pending_if_synced(event.sync_identity()));    patch}/// One exception's re-keyed claim.#[derive(Debug, Clone, PartialEq)]pub struct ExceptionPatch {    pub id: String,    pub patch: RowPatch,}/// The re-keying a series move owes everything that points at its occurrences.#[derive(Debug, Clone, PartialEq)]pub struct SeriesMovePlan {    /// The master's re-keyed `exdates`, or empty when it has none to move.    pub master_patch: RowPatch,    /// Each exception's re-keyed claim; empty when nothing moved.    pub exception_patches: Vec<ExceptionPatch>,}/// MOVING A SERIES RE-KEYS EVERYTHING THAT POINTS AT ITS OCCURRENCES.////// `exdates` and an exception's `original_starts_at` are addressed by INSTANT./// Move the master's start and the rule fires at instants that match neither:/// the cancelled occurrence comes back at its new time, and every moved one is/// drawn TWICE — once at its own time, and again by the master at the slot it/// no longer claims. That is precisely the failure schema v32 exists to end, so/// it cannot be left to whichever writer remembers.////// This is the RE-KEYING ONLY. The caller writes the master's own/// `starts_at`/`ends_at` in its ordinary patch and merges `master_patch` into/// it; an exception's own `starts_at` is deliberately untouched, because the/// person put that occurrence where it is on purpose and moving the series is/// not a request to move it again.////// The shift is computed in WALL-CLOCK terms in `zone`, not as a millisecond/// delta: an occurrence's identity is its wall time (a weekly 12:00 stays/// 12:00, which is the whole point of the DST-aware expansion), so a series/// moved across a DST transition would otherwise leave every exdate an hour off/// the occurrence it is meant to remove — and an exdate that misses is a/// cancelled appointment back on somebody's calendar.////// `zone` is the WORKSPACE's IANA zone — never the device's, never the host's.pub fn plan_series_move(    master: &EventRowForPlan,    exceptions: &[EventRowForPlan],    new_starts_at: &str,    zone: &str,) -> Result<SeriesMovePlan, EventEditsError> {    let empty = SeriesMovePlan {        master_patch: RowPatch::new(),        exception_patches: Vec::new(),    };    // `Number.isNaN(from.getTime())` — an unreadable instant on either end is    // "nothing to re-key", not a failure: the caller's own write is still valid.    let (Some(from), Some(to)) = (        parse_date_ms(&master.starts_at),        parse_date_ms(new_starts_at),    ) else {        return Ok(empty);    };    if from == to {        return Ok(empty);    }    let anchor = Reanchor::between(from, to, zone)?;    let had_exdates = !master.exdates.as_deref().unwrap_or(&[]).is_empty();    let mut exdates: Vec<String> = Vec::new();    for iso in master.exdates.as_deref().unwrap_or(&[]) {        if let Some(moved) = anchor.apply(iso)? {            exdates.push(moved);        }    }    // `Array.prototype.sort()` with no comparator: a plain UTF-16 code-unit    // sort, which is what a byte sort is on ASCII ISO instants.    exdates.sort();    let mut master_patch = RowPatch::new();    if had_exdates {        master_patch.insert(            "exdates".into(),            if exdates.is_empty() {                Value::Null            } else {                Value::Array(exdates.into_iter().map(Value::String).collect())            },        );    }    let mut exception_patches = Vec::new();    for exception in exceptions {        let Some(original) = exception.original_starts_at.as_deref() else {            continue;        };        let Some(moved) = anchor.apply(original)? else {            continue;        };        if moved == original {            continue;        }        let mut patch = RowPatch::new();        patch.insert("original_starts_at".into(), Value::String(moved));        exception_patches.push(ExceptionPatch {            id: exception.id.clone(),            patch,        });    }    Ok(SeriesMovePlan {        master_patch,        exception_patches,    })}/// An instant → where it lands once the series' anchor moves from `from` to/// `to`: the same number of days later or earlier, at the anchor's NEW time of/// day.struct Reanchor<'a> {    after: ZonedParts,    /// `Intl` has no sub-second field and milliseconds are zone-invariant, so    /// the anchor's own remainder carries them.    after_ms: i64,    day_delta: i64,    zone: &'a str,}impl<'a> Reanchor<'a> {    fn between(from: i64, to: i64, zone: &'a str) -> Result<Self, EventEditsError> {        let before = zoned_parts(from, zone)?;        let after = zoned_parts(to, zone)?;        Ok(Self {            after,            after_ms: to.rem_euclid(1000),            day_delta: day_of(after) - day_of(before),            zone,        })    }    /// `Ok(None)` for anything that is not an instant, which the caller drops —    /// the TypeScript's `null`.    fn apply(&self, iso: &str) -> Result<Option<String>, EventEditsError> {        let Some(at) = parse_date_ms(iso) else {            return Ok(None);        };        let wall = zoned_parts(at, self.zone)?;        let (year, month, day) = civil_from_days(day_of(wall) + self.day_delta);        let landed = crate::transforms::zoned_clock::instant_from_zoned(            ZonedParts {                year,                month,                day,                hour: self.after.hour,                minute: self.after.minute,                second: self.after.second,            },            self.after_ms,            self.zone,        )?;        Ok(Some(            to_iso_string(landed).ok_or(EventEditsError::InvalidTimeValue)?,        ))    }}/// `Math.floor(Date.UTC(year, month - 1, day) / 86_400_000)` — a wall-clock/// reading's day number, for day arithmetic only.fn day_of(parts: ZonedParts) -> i64 {    day_number(parts.year, parts.month, parts.day)}#[cfg(test)]#[path = "event_edits_tests.rs"]mod tests;