Cotton code
340 lines · 13.6 KB · RustRaw
//! A repeating event is a SERIES — the port of//! `packages/core/src/engine/series.ts`.//!//! [`crate::transforms::rrule`] answers "when does this rule fire" and nothing//! more. That was the whole model until schema v32, and it is why the owner's//! calendar was wrong on the screen: a weekly "Vicky" moved from Friday to the//! following Tuesday drew itself on BOTH days (the moved copy had arrived as a//! brand-new standalone event), and a cancelled "Call with Bella" kept drawing//! itself for ever (Google's cancellation matched no local row at all).//!//! THREE FACTS, ONE FUNCTION. [`expand_series`] is the only thing that knows an//! occurrence can be claimed://!//! 1. `exdates` — instants the master skips. A cancelled occurrence, from//!    either side.//! 2. an EXCEPTION ROW — a real `cotton_events` row with its own title, time,//!    notes and links, whose `original_starts_at` names the instant of the//!    series it stands in for. It is a row rather than a diff on the master//!    precisely because it has all of that; a patch blob would have left an//!    occurrence's notes and attendees homeless.//! 3. `trashed_at` — a soft delete. A trashed row draws nothing, here, once,//!    rather than in every reader that ever asks for a day.//!//! A reader that expands a master and ignores the other two IS the bug this//! module exists to fix, which is why//! [`crate::transforms::rrule::expand_event`] has exactly one caller — this file —//! and why `series_tests.rs` carries the source-tree guard that keeps it that//! way.//!//! The zone is the WORKSPACE's, never the device's, for the reason stated at//! length in `rrule.rs`: two zones mean two instants for the same occurrence,//! and an occurrence's identity here is its instant.use cotton_store::protocol::js::{json_stringify, parse_date_ms, to_iso_string};use crate::transforms::rrule::{expand_event, DateRange, EventForExpansion, RruleError};/// What the expansion needs off a `cotton_events` row.////// Deliberately structural: the server reads rows straight out of its own store/// and must be able to hand them here without a model layer. Instants stay as/// the STRINGS the row holds, because an exception's own `starts_at` is passed/// through to the caller verbatim.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct SeriesRow {    pub id: String,    pub starts_at: String,    pub ends_at: Option<String>,    pub rrule: Option<String>,    /// ISO instants the master does not produce. `None` and `[]` read the same.    pub exdates: Option<Vec<String>>,    /// The master this row is an exception of, or `None` for an ordinary row.    pub series_id: Option<String>,    /// The instant of the master's expansion this row replaces.    pub original_starts_at: Option<String>,    /// Set = in the bin. It draws nothing.    pub trashed_at: Option<String>,}/// One concrete occurrence, and which row draws it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SeriesOccurrence {    /// The row to open when this occurrence is tapped — the exception, if any.    pub event_id: String,    /// The master's id when this occurrence belongs to a series; `None`    /// otherwise.    pub series_id: Option<String>,    /// The instant in the SERIES this occupies — the address an assistant    /// passes back as `occurrenceAt`. For an exception it is the instant the    /// row REPLACES, not the time it was moved to: that is the only address the    /// master's rule and Google's instance id both agree on.    pub occurrence_at: String,    /// When it actually happens.    pub starts_at: String,    pub ends_at: Option<String>,    pub is_exception: bool,}/// Why an expansion could not be answered.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum SeriesError {    /// The TypeScript's `withExdate` sentence, verbatim.    #[error("not an instant: {0}")]    NotAnInstant(String),    #[error(transparent)]    Rrule(#[from] RruleError),}/// Milliseconds of an ISO instant, or `None` — used only for set membership,/// where the TypeScript's `NaN` is the same "matches nothing".fn instant_of(iso: &str) -> Option<i64> {    parse_date_ms(iso)}fn overlaps_range(starts_at: &str, ends_at: Option<&str>, range: DateRange) -> bool {    // Every comparison against a `NaN` is false in JavaScript, so an    // unparseable instant overlaps nothing. `None` here reads the same way.    let Some(start) = instant_of(starts_at) else {        return false;    };    let end = match ends_at {        Some(iso) => match instant_of(iso) {            Some(end) => end,            None => return false,        },        None => start,    };    start <= range.to && end >= range.from}/// One series → its occurrences inside `range`, chronologically.////// An exception is placed by its OWN times, so a moved occurrence appears on/// the day it moved to and not on the day it left — which is exactly the double/// booking this replaces. An exception whose `original_starts_at` names an/// instant the rule never produces still draws itself: Google allows one, and a/// row the person can see is better than a row silently swallowed.pub fn expand_series(    master: &SeriesRow,    exceptions: &[SeriesRow],    range: DateRange,    zone: &str,) -> Result<Vec<SeriesOccurrence>, SeriesError> {    // A trashed master takes its whole series with it — including exceptions    // that are not themselves trashed yet. The push loop deletes those rows at    // Google before removing them, and until it has, nobody should be looking    // at an occurrence of an event that is in the bin.    if master.trashed_at.is_some() {        return Ok(Vec::new());    }    let mut out: Vec<SeriesOccurrence> = Vec::new();    let is_series = master.rrule.is_some();    let mut skipped: std::collections::BTreeSet<i64> = std::collections::BTreeSet::new();    for iso in master.exdates.as_deref().unwrap_or(&[]) {        // A malformed exdate is ignored rather than losing the whole series.        if let Some(at) = instant_of(iso) {            skipped.insert(at);        }    }    // EVERY exception claims its instant, TRASHED ONES INCLUDED. A trashed    // exception is on its way out of Google, not on its way back into the    // series: restoring the master's original instant because the moved copy    // went into the bin would put an appointment back on a day the person    // already emptied.    for exception in exceptions {        let Some(claims) = exception.original_starts_at.as_deref() else {            continue;        };        if let Some(at) = instant_of(claims) {            skipped.insert(at);        }    }    for occurrence in expand_master(master, range, zone)? {        if skipped.contains(&occurrence.starts_at) {            continue;        }        let starts_iso = iso_or_refuse(occurrence.starts_at)?;        out.push(SeriesOccurrence {            event_id: master.id.clone(),            series_id: if is_series {                Some(master.id.clone())            } else {                None            },            occurrence_at: starts_iso.clone(),            starts_at: starts_iso,            ends_at: occurrence.ends_at.map(iso_or_refuse).transpose()?,            is_exception: false,        });    }    for exception in exceptions {        if exception.trashed_at.is_some() {            continue;        }        if !overlaps_range(&exception.starts_at, exception.ends_at.as_deref(), range) {            continue;        }        out.push(SeriesOccurrence {            event_id: exception.id.clone(),            series_id: Some(master.id.clone()),            // The row's OWN strings, passed through: an exception's times are            // whatever the row holds, never a re-rendering of them.            occurrence_at: exception                .original_starts_at                .clone()                .unwrap_or_else(|| exception.starts_at.clone()),            starts_at: exception.starts_at.clone(),            ends_at: exception.ends_at.clone(),            is_exception: true,        });    }    sort_by_starts_at(&mut out);    Ok(out)}/// The master's own rule, expanded — the one call to/// [`crate::transforms::rrule::expand_event`] in the whole crate.fn expand_master(    master: &SeriesRow,    range: DateRange,    zone: &str,) -> Result<Vec<crate::transforms::rrule::ExpandedOccurrence>, SeriesError> {    let recurring = master.rrule.as_deref().is_some_and(|rule| !rule.is_empty());    let starts_at = match instant_of(&master.starts_at) {        Some(at) => at,        // `new Date("nonsense")` is `NaN`, and every comparison against it is        // false — so a non-recurring master with an unreadable start overlaps        // nothing and draws nothing. A RECURRING one throws in the TypeScript        // (the zone reader refuses an invalid time value), which is this        // refusal.        None if !recurring => return Ok(Vec::new()),        None => return Err(SeriesError::NotAnInstant(json_quote(&master.starts_at))),    };    let ends_at = match master.ends_at.as_deref() {        None => None,        Some(iso) => {            Some(instant_of(iso).ok_or_else(|| SeriesError::NotAnInstant(json_quote(iso)))?)        }    };    Ok(expand_event(        &EventForExpansion {            starts_at,            ends_at,            rrule: master.rrule.clone(),        },        range,        zone,    )?)}fn iso_or_refuse(ms: i64) -> Result<String, SeriesError> {    to_iso_string(ms).ok_or(SeriesError::NotAnInstant(ms.to_string()))}/// `out.sort((a, b) => a.startsAt.localeCompare(b.startsAt))`.////// **A stated approximation.** `localeCompare` is ICU collation, not byte/// order, and the two DO disagree on one shape: `"…+05:30"` sorts AFTER/// `"….000Z"` under ICU and before it by bytes. Every string sorted here is/// either produced by `to_iso_string` (always `…Z`, always millisecond/// precision) or read from a `timestamp`-coded column, which the store/// normalises to the same shape — so the two orders coincide on every input/// this function can actually see. A caller that starts storing an/// offset-bearing ISO instant in `starts_at` breaks that, and would have to/// bring a real collator with it.////// Rust's `sort_by` is stable and so is JavaScript's `sort`, so equal keys keep/// their order on both sides.fn sort_by_starts_at(out: &mut [SeriesOccurrence]) {    out.sort_by(|a, b| a.starts_at.cmp(&b.starts_at));}/// A whole calendar's rows → every occurrence inside `range`, chronologically.////// The grouping is the part every caller would otherwise re-derive: a row with/// `series_id` is an exception and belongs to its master's expansion, never to/// its own — draw it twice and the moved "Vicky" is back on two days.////// An ORPHAN exception — one whose master is not in `events` — is drawn as an/// ordinary event. That happens when the master sits outside the read's window/// or when Google sent an instance whose series Cotton has never seen; the row/// is real either way, and hiding it would lose an appointment.pub fn expand_calendar(    events: &[SeriesRow],    range: DateRange,    zone: &str,) -> Result<Vec<SeriesOccurrence>, SeriesError> {    let known: std::collections::BTreeSet<&str> =        events.iter().map(|row| row.id.as_str()).collect();    let mut masters: Vec<&SeriesRow> = Vec::new();    let mut exceptions_of: std::collections::BTreeMap<&str, Vec<SeriesRow>> =        std::collections::BTreeMap::new();    for row in events {        let parent = row.series_id.as_deref().filter(|id| known.contains(id));        if let Some(parent) = parent {            exceptions_of.entry(parent).or_default().push(row.clone());            continue;        }        masters.push(row);    }    let mut out: Vec<SeriesOccurrence> = Vec::new();    for master in masters {        let exceptions = exceptions_of            .get(master.id.as_str())            .map(Vec::as_slice)            .unwrap_or(&[]);        out.extend(expand_series(master, exceptions, range, zone)?);    }    sort_by_starts_at(&mut out);    Ok(out)}/// `exdates` with `instant` added once — the local cancel of one occurrence,/// and the same call the Google pull makes when a cancellation arrives.////// Idempotent by INSTANT rather than by string: `2026-09-23T09:00:00Z` and/// `2026-09-23T09:00:00.000Z` are the same moment, and a sweep that re-ran/// would otherwise grow the list for ever. The result is sorted so two devices/// that cancelled two different occurrences converge on the same JSON.pub fn with_exdate(exdates: Option<&[String]>, instant: &str) -> Result<Vec<String>, SeriesError> {    let at = instant_of(instant).ok_or_else(|| SeriesError::NotAnInstant(json_quote(instant)))?;    let mut kept: Vec<String> = exdates        .unwrap_or(&[])        .iter()        .filter(|iso| instant_of(iso) != Some(at))        .cloned()        .collect();    kept.push(iso_or_refuse(at)?);    // `Array.prototype.sort()` with no comparator sorts by code unit, NOT by    // locale — so this one really is a plain string sort on both sides.    kept.sort();    Ok(kept)}/// True when `instant` is already one of `exdates` — compared as instants.pub fn has_exdate(exdates: Option<&[String]>, instant: &str) -> bool {    let Some(at) = instant_of(instant) else {        // `NaN !== NaN`, so an unreadable instant is never present.        return false;    };    exdates        .unwrap_or(&[])        .iter()        .any(|iso| instant_of(iso) == Some(at))}fn json_quote(value: &str) -> String {    json_stringify(&serde_json::Value::String(value.to_string()))}#[cfg(test)]#[path = "series_tests.rs"]mod tests;