Skip to main content

syncular_client/
api.rs

1//! Driver-facing API shapes (JSON-able), mirroring the conformance
2//! `ClientInstance` contract: sync reports, conflicts, rejections, row
3//! states, unit states. Serialized as camelCase to cross the shim
4//! boundary unchanged.
5
6use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::previous_version::PreviousVersionContextConfig;
12/// Stable dynamic value boundary used by generated named queries.
13pub type QueryValue = Value;
14/// One dynamic query result row, keyed by QueryIR runtime projection name.
15pub type QueryRow = Map<String, QueryValue>;
16
17/// An owned blob body returned by the Rust client without driver encoding.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct FetchedBlob {
20    pub blob_id: String,
21    pub byte_length: i64,
22    pub bytes: Vec<u8>,
23    pub media_type: Option<String>,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum TimeBucketUnit {
28    Month,
29}
30
31const MAX_TIME_BUCKET_MS: i64 = 253_402_300_799_999;
32
33fn utc_year_month(timestamp_ms: i64) -> Result<(i64, i64), String> {
34    if !(0..=MAX_TIME_BUCKET_MS).contains(&timestamp_ms) {
35        return Err(
36            "sync.invalid_request: time bucket timestamps must fall from 1970 through 9999"
37                .to_owned(),
38        );
39    }
40    let z = timestamp_ms / 86_400_000 + 719_468;
41    let era = z.div_euclid(146_097);
42    let day_of_era = z - era * 146_097;
43    let year_of_era =
44        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
45    let mut year = year_of_era + era * 400;
46    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
47    let month_prime = (5 * day_of_year + 2) / 153;
48    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
49    if month <= 2 {
50        year += 1;
51    }
52    Ok((year, month))
53}
54
55/// Derive the immutable UTC scope value stored when a row is created.
56pub fn creation_time_bucket(created_at_ms: i64, unit: TimeBucketUnit) -> Result<String, String> {
57    match unit {
58        TimeBucketUnit::Month => {
59            let (year, month) = utc_year_month(created_at_ms)?;
60            Ok(format!("{year:04}-{month:02}"))
61        }
62    }
63}
64
65/// Return a rolling UTC month window ordered from oldest to newest.
66pub fn last(count: usize, unit: TimeBucketUnit, now_ms: i64) -> Result<Vec<String>, String> {
67    if !(1..=1_200).contains(&count) {
68        return Err(
69            "sync.invalid_request: time bucket count must be from 1 through 1200".to_owned(),
70        );
71    }
72    match unit {
73        TimeBucketUnit::Month => {
74            let (year, month) = utc_year_month(now_ms)?;
75            let current = year * 12 + month - 1;
76            if current - (count as i64 - 1) < 1970 * 12 {
77                return Err(
78                    "sync.invalid_request: every returned UTC month must fall from 1970 through 9999"
79                        .to_owned(),
80                );
81            }
82            Ok((0..count)
83                .rev()
84                .map(|offset| {
85                    let value = current - offset as i64;
86                    format!(
87                        "{:04}-{:02}",
88                        value.div_euclid(12),
89                        value.rem_euclid(12) + 1
90                    )
91                })
92                .collect())
93        }
94    }
95}
96
97/// §4.1: a unit's scope map, one value per requested scope variable.
98pub type UnitScopes = BTreeMap<String, String>;
99
100/// §4.1 persisted unit status.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(rename_all = "lowercase")]
103pub enum UnitStatus {
104    Active,
105    Revoked,
106    Failed,
107}
108
109impl UnitStatus {
110    pub fn name(self) -> &'static str {
111        match self {
112            UnitStatus::Active => "active",
113            UnitStatus::Revoked => "revoked",
114            UnitStatus::Failed => "failed",
115        }
116    }
117}
118
119/// §4.4 one fenced record of a persisted echo: the effective lists the
120/// wildcard fence added for a covered table, or its revocation.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct EchoRecord {
123    pub table: String,
124    /// `active` or `revoked`.
125    pub status: String,
126    pub scopes: BTreeMap<String, Vec<String>>,
127}
128
129/// §7.4.3 a unit's restriction: the kept cursor `C` through which its other
130/// covered tables hold every change, and the tables it bootstraps, in
131/// ascending code-unit order. It travels as `RESTRICT` (§4.3).
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct UnitRestriction {
134    pub cursor: i64,
135    pub tables: Vec<String>,
136}
137
138/// §4.1 one registered unit as the client persists it.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct UnitRecord {
142    /// §4.1: derived from the scope map.
143    pub id: String,
144    pub scopes: UnitScopes,
145    /// An explicit `subscribe` holds the unit; window bases hold it through
146    /// the window registry (§4.1 references).
147    pub explicit: bool,
148    pub status: UnitStatus,
149    /// §10 code when not active, or `sync.cursor_expired` after a reset.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub reason_code: Option<String>,
152    /// Absent while the unit is live (§4.5); otherwise `-1`, the pin, or the
153    /// post-bootstrap cursor `P`.
154    #[serde(skip_serializing_if = "Option::is_none")]
155    pub cursor: Option<i64>,
156    /// Opaque resume token from `SUB_END` (§4.7); present mid-bootstrap.
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub bootstrap_state: Option<String>,
159    /// Tables that received a segment in the current bootstrap (§5.6).
160    pub seeded: Vec<String>,
161    /// The echo persisted at the last `SUB_END` (§4.4).
162    #[serde(skip_serializing_if = "Option::is_none")]
163    pub echo: Option<Vec<EchoRecord>>,
164    /// §7.4.3: the restriction a schema bump gave the unit, while it holds one.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub restriction: Option<UnitRestriction>,
167}
168
169impl UnitRecord {
170    /// §4.1: a catching-up unit holding cursor `-1` or a resume token.
171    pub fn bootstrapping(&self) -> bool {
172        self.cursor
173            .is_some_and(|cursor| cursor < 0 || self.bootstrap_state.is_some())
174    }
175}
176
177/// §4.8 window base: the selected scope variable plus the fixed scope values
178/// every unit of its family shares. A base names no table: each unit covers
179/// every table declaring its variables (§4.1).
180#[derive(Debug, Clone, Default)]
181pub struct WindowBase {
182    pub variable: String,
183    /// One value per other variable, shared by every unit.
184    pub fixed_scopes: UnitScopes,
185}
186
187/// §4.8 completeness oracle (I3): the windowed-in units for a base, plus
188/// the subset whose bootstrap has not yet completed. Registration alone is
189/// not completeness — a `pending` unit's local replica may be empty or
190/// partial (it still has `cursor: -1` or holds a resume token), and MUST NOT
191/// be rendered as complete. A unit with zero server
192/// rows still completes once its bootstrap round finishes.
193#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
194#[serde(rename_all = "camelCase")]
195pub struct WindowState {
196    /// Windowed-in units for this base, ordered by value.
197    pub units: Vec<String>,
198    /// Registered units whose bootstrap has not yet completed.
199    pub pending: Vec<String>,
200}
201
202#[cfg(test)]
203mod time_bucket_tests {
204    use super::{creation_time_bucket, last, TimeBucketUnit};
205
206    #[test]
207    fn utc_month_buckets_cross_year_boundaries() {
208        let now = 1_770_508_800_000; // 2026-02-08T00:00:00Z
209        assert_eq!(
210            creation_time_bucket(now, TimeBucketUnit::Month).unwrap(),
211            "2026-02"
212        );
213        assert_eq!(
214            last(3, TimeBucketUnit::Month, now).unwrap(),
215            vec!["2025-12", "2026-01", "2026-02"]
216        );
217    }
218
219    #[test]
220    fn utc_month_buckets_reject_unbounded_input() {
221        assert!(last(0, TimeBucketUnit::Month, 0).is_err());
222        assert!(last(1_201, TimeBucketUnit::Month, 0).is_err());
223        assert!(last(2, TimeBucketUnit::Month, 0).is_err());
224        assert!(creation_time_bucket(-1, TimeBucketUnit::Month).is_err());
225    }
226}
227
228#[derive(Debug, Clone, Serialize)]
229#[serde(rename_all = "camelCase")]
230pub struct TableChange {
231    pub table: String,
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub scope_keys: Option<Vec<String>>,
234}
235
236#[derive(Debug, Clone, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct WindowChange {
239    pub base_key: String,
240    /// Changed values of the base.
241    pub units: Vec<String>,
242}
243
244#[derive(Debug, Clone, Serialize)]
245#[serde(rename_all = "camelCase")]
246pub struct SyncStatusSnapshot {
247    pub current_schema_version: i32,
248    pub outbox: usize,
249    pub upgrading: bool,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub lease_state: Option<LeaseState>,
252    #[serde(skip_serializing_if = "Option::is_none")]
253    pub schema_floor: Option<SchemaFloor>,
254    pub sync_needed: bool,
255    /// RFC 0005 A2: container presence, so a host can enforce the downgrade
256    /// precondition (`previousVersionDiscard`) instead of documenting it.
257    pub previous_version_context: PreviousVersionStatus,
258    /// §5.11: "preflight" while protected reads, claims and sync are refused;
259    /// a change batch carries the snapshot at each transition.
260    pub security_lifecycle: &'static str,
261}
262
263/// RFC 0005 A2: presence of the previous-version container file.
264#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
265#[serde(rename_all = "camelCase")]
266pub struct PreviousVersionStatus {
267    pub present: bool,
268    #[serde(skip_serializing_if = "Option::is_none")]
269    pub created_at_ms: Option<i64>,
270}
271
272pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 2;
273pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;
274
275/// §8.8 client-local code: the `required` policy refused a sync round because
276/// the realtime socket is not connected. Never a wire code (§10.3).
277pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
278/// §8.8 client-local code: a connected socket ended without a deliberate
279/// disconnect and the round reported no transport code. Never a wire code.
280pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
281/// §12 client-local code: a local-authority call or config on a host that
282/// has no local authority (the build lacks the `local-authority` feature, the
283/// config names no `localAuthorityPath`, or attach has no remote server).
284pub const LOCAL_AUTHORITY_UNCONFIGURED_CODE: &str = "client.local_authority_unconfigured";
285
286#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
287#[serde(rename_all = "camelCase")]
288pub struct ClientDiagnosticsHost {
289    pub kind: String,
290    pub role: String,
291    pub connectivity: String,
292    pub realtime: RealtimeState,
293    pub realtime_policy: RealtimePolicy,
294    #[serde(skip_serializing_if = "Option::is_none")]
295    pub realtime_reason_code: Option<String>,
296    #[serde(skip_serializing_if = "Option::is_none")]
297    pub realtime_retry_delay_ms: Option<u64>,
298}
299
300/// §7.6: registered units per state; a unit id never enters diagnostics.
301#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
302#[serde(rename_all = "camelCase")]
303pub struct DiagnosticUnits {
304    pub bootstrapping: usize,
305    pub complete: usize,
306    pub reset: usize,
307    pub revoked: usize,
308    pub failed: usize,
309    /// Distinct stable reason codes of registered units, ascending.
310    pub reason_codes: Vec<String>,
311}
312
313#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
314#[serde(rename_all = "camelCase")]
315pub struct DiagnosticRoundCounters {
316    pub pushed: u32,
317    pub applied: usize,
318    pub rejected: usize,
319    pub retryable: usize,
320    pub conflicts: u32,
321    pub commits_applied: u32,
322    pub segment_rows_applied: u32,
323    pub bootstrapping: usize,
324    pub resets: usize,
325    pub revoked: usize,
326    pub failed: usize,
327    pub deferred_commits: usize,
328}
329
330/// Bounded transport classification for progress and diagnostics (§1.8).
331#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
332#[serde(rename_all = "snake_case")]
333pub enum TransportCauseKind {
334    Network,
335    Connect,
336    Tls,
337    Io,
338    Request,
339    Protocol,
340    Timeout,
341    RoundDeadline,
342    Aborted,
343    Body,
344    Status,
345    Redirect,
346    Unknown,
347}
348
349#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
350#[serde(rename_all = "camelCase")]
351pub struct DiagnosticLastRound {
352    /// §7.6: (`epoch`, `attempt`) identifies the round; it equals its §7.7 progress pair.
353    pub epoch: String,
354    pub attempt: u64,
355    pub status: String,
356    pub started_at_ms: i64,
357    pub completed_at_ms: i64,
358    pub duration_ms: i64,
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub counters: Option<DiagnosticRoundCounters>,
361    #[serde(skip_serializing_if = "Option::is_none")]
362    pub error_code: Option<String>,
363    #[serde(skip_serializing_if = "Option::is_none")]
364    pub cause_kind: Option<TransportCauseKind>,
365    #[serde(skip_serializing_if = "Option::is_none")]
366    pub http_status: Option<u16>,
367}
368
369#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
370#[serde(rename_all = "camelCase")]
371pub struct DiagnosticLastChange {
372    pub revision: String,
373    pub recorded_at_ms: i64,
374    pub tables: Vec<String>,
375    pub windows: Vec<String>,
376    pub domains_truncated: bool,
377    pub status_changed: bool,
378    pub conflicts_changed: bool,
379    pub rejections_changed: bool,
380    pub outcomes_changed: bool,
381}
382
383#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
384#[serde(rename_all = "camelCase")]
385pub struct ClientDiagnosticsStorage {
386    pub status: String,
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub database_bytes_approx: Option<i64>,
389    #[serde(skip_serializing_if = "Option::is_none")]
390    pub pending_outbox_bytes_approx: Option<i64>,
391    #[serde(skip_serializing_if = "Option::is_none")]
392    pub retained_outcome_bytes_approx: Option<i64>,
393    #[serde(skip_serializing_if = "Option::is_none")]
394    pub retained_outcome_entries: Option<i64>,
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub blob_cache_bytes_approx: Option<i64>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub pressure_reason_code: Option<String>,
399}
400
401/// §7.6: the latest owned snapshot read of one query id failed.
402#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
403#[serde(rename_all = "camelCase")]
404pub struct DiagnosticQueryFailure {
405    pub id: String,
406    /// Distinct generated table names, ascending.
407    pub tables: Vec<String>,
408    /// `client.storage_corrupt`, `client.storage_io`, or `client.query_failed`.
409    pub code: String,
410    /// SQLite extended result code, when the driver exposed one.
411    #[serde(skip_serializing_if = "Option::is_none")]
412    pub sqlite_code: Option<i32>,
413    /// First failure since this id's last successful read.
414    pub at_ms: i64,
415}
416
417#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
418#[serde(rename_all = "camelCase")]
419pub struct ClientDiagnosticsSnapshot {
420    pub version: u8,
421    pub captured_at_ms: i64,
422    pub host: ClientDiagnosticsHost,
423    pub security_lifecycle: String,
424    pub schema: ClientDiagnosticsSchema,
425    pub replica: ClientDiagnosticsReplica,
426    pub lease: ClientDiagnosticsLease,
427    pub units: DiagnosticUnits,
428    /// Units the next registration list carries; the server limit counts
429    /// these (§4.1).
430    pub active_units: usize,
431    /// §4.5 replica cursor; `-1` while no unit is live.
432    pub replica_cursor: i64,
433    #[serde(skip_serializing_if = "Option::is_none")]
434    pub last_round: Option<DiagnosticLastRound>,
435    #[serde(skip_serializing_if = "Option::is_none")]
436    pub last_change: Option<DiagnosticLastChange>,
437    pub storage: ClientDiagnosticsStorage,
438    pub query_failures: Vec<DiagnosticQueryFailure>,
439}
440
441#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
442#[serde(rename_all = "camelCase")]
443pub struct ClientDiagnosticsSchema {
444    pub current_version: i32,
445    pub upgrading: bool,
446    #[serde(skip_serializing_if = "Option::is_none")]
447    pub required_version: Option<i32>,
448    #[serde(skip_serializing_if = "Option::is_none")]
449    pub latest_version: Option<i32>,
450}
451
452#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
453#[serde(rename_all = "camelCase")]
454pub struct ClientDiagnosticsReplica {
455    pub local_revision: String,
456    pub sync_needed: bool,
457    pub pending_outbox: usize,
458}
459
460/// §8.8: how this client treats the realtime binding for sync rounds.
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
462#[serde(rename_all = "lowercase")]
463pub enum RealtimePolicy {
464    Required,
465    #[default]
466    Optional,
467    Off,
468}
469
470impl RealtimePolicy {
471    #[must_use]
472    pub fn as_str(self) -> &'static str {
473        match self {
474            RealtimePolicy::Required => "required",
475            RealtimePolicy::Optional => "optional",
476            RealtimePolicy::Off => "off",
477        }
478    }
479}
480
481/// §8.8: the explicit availability state of the realtime binding. The
482/// TypeScript host adds `unsupported` (no connector configured) and `unknown`
483/// (a wrapper without evidence); the Rust core reaches neither because a
484/// transport always carries a connect path.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
486#[serde(rename_all = "lowercase")]
487pub enum RealtimeState {
488    Connected,
489    Connecting,
490    #[default]
491    Disconnected,
492    Lost,
493    Refused,
494    Disabled,
495}
496
497#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
498#[serde(rename_all = "camelCase")]
499pub struct ClientDiagnosticsLease {
500    pub state: String,
501    #[serde(skip_serializing_if = "Option::is_none")]
502    pub expires_at_ms: Option<i64>,
503    #[serde(skip_serializing_if = "Option::is_none")]
504    pub error_code: Option<String>,
505}
506
507/// JSON bindings carry the u64 revision as a decimal string (§7.5).
508#[derive(Debug, Clone, Serialize)]
509#[serde(rename_all = "camelCase")]
510pub struct AppliedServerCommit {
511    pub table: String,
512    pub commit_seq: i64,
513    pub source: AppliedServerCommitSource,
514}
515
516#[derive(Debug, Clone, Copy, Serialize)]
517#[serde(rename_all = "camelCase")]
518pub enum AppliedServerCommitSource {
519    Delta,
520    Pull,
521}
522
523#[derive(Debug, Clone, Serialize)]
524#[serde(rename_all = "camelCase")]
525pub struct ClientChangeBatch {
526    pub revision: String,
527    pub tables: Vec<TableChange>,
528    pub windows: Vec<WindowChange>,
529    #[serde(skip_serializing_if = "Option::is_none")]
530    pub status: Option<SyncStatusSnapshot>,
531    pub conflicts_changed: bool,
532    pub rejections_changed: bool,
533    pub outcomes_changed: bool,
534    #[serde(skip_serializing_if = "Vec::is_empty")]
535    pub applied_commits: Vec<AppliedServerCommit>,
536}
537
538#[derive(Debug, Clone, Serialize)]
539#[serde(tag = "kind", rename_all = "camelCase")]
540pub enum SyncIntent {
541    None,
542    Interactive,
543    Background {
544        #[serde(rename = "delayMs")]
545        delay_ms: u64,
546    },
547}
548
549#[derive(Debug, Clone, Serialize)]
550pub struct CommandEffects {
551    pub sync: SyncIntent,
552}
553
554impl CommandEffects {
555    #[must_use]
556    pub fn none() -> Self {
557        Self {
558            sync: SyncIntent::None,
559        }
560    }
561
562    #[must_use]
563    pub fn interactive() -> Self {
564        Self {
565            sync: SyncIntent::Interactive,
566        }
567    }
568}
569
570#[derive(Debug, Clone)]
571pub struct WindowCoverage {
572    pub base: WindowBase,
573    pub units: Vec<String>,
574}
575
576#[derive(Debug, Clone, Serialize)]
577#[serde(rename_all = "camelCase")]
578pub struct WindowUnitRef {
579    pub base_key: String,
580    pub unit: String,
581}
582
583#[derive(Debug, Clone, Serialize)]
584#[serde(rename_all = "camelCase")]
585pub struct CoverageSnapshot {
586    pub complete: bool,
587    pub pending: Vec<WindowUnitRef>,
588    pub missing: Vec<WindowUnitRef>,
589}
590
591/// §7.5: the query that owns a snapshot read. The id is application-owned,
592/// stable, and PHI-free; generated named queries pass their `ID` and `TABLES`.
593#[derive(Debug, Clone, Copy)]
594pub struct QueryOwner<'a> {
595    pub id: &'a str,
596    pub tables: &'a [&'a str],
597}
598
599/// §7.5: a failed snapshot read or a failed local authoring write. `code` is
600/// `client.storage_corrupt`, `client.storage_io`, `client.storage_full`, or
601/// `client.storage_busy` when SQLite reported that condition, and `None` for
602/// every other failure, which keeps its existing message.
603#[derive(Debug, Clone, PartialEq, Eq)]
604pub struct QueryReadFailure {
605    pub code: Option<&'static str>,
606    pub sqlite_code: Option<i32>,
607    pub sqlite_message: Option<String>,
608    pub rollback_failure: Option<Box<QueryReadFailure>>,
609    pub message: String,
610}
611
612impl std::fmt::Display for QueryReadFailure {
613    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
614        match self.code {
615            Some(code) => write!(f, "{code}: {}", self.message),
616            None => f.write_str(&self.message),
617        }
618    }
619}
620
621impl From<String> for QueryReadFailure {
622    fn from(message: String) -> Self {
623        Self {
624            code: None,
625            sqlite_code: None,
626            sqlite_message: None,
627            rollback_failure: None,
628            message,
629        }
630    }
631}
632
633impl From<rusqlite::Error> for QueryReadFailure {
634    /// Classify by SQLite's primary result code, never by message text.
635    fn from(error: rusqlite::Error) -> Self {
636        let sqlite_code = match &error {
637            rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
638            _ => None,
639        };
640        match sqlite_code.map(|code| code & 0xff) {
641            Some(11 | 26) => Self {
642                code: Some("client.storage_corrupt"),
643                sqlite_code,
644                sqlite_message: Some(error.to_string()),
645                rollback_failure: None,
646                message: "local SQLite storage is corrupt".to_owned(),
647            },
648            Some(13) => Self {
649                code: Some("client.storage_full"),
650                sqlite_code,
651                sqlite_message: Some(error.to_string()),
652                rollback_failure: None,
653                message: "local SQLite storage is full".to_owned(),
654            },
655            Some(10) => Self {
656                code: Some("client.storage_io"),
657                sqlite_code,
658                sqlite_message: Some(error.to_string()),
659                rollback_failure: None,
660                message: "local SQLite storage I/O failed".to_owned(),
661            },
662            // SQLITE_BUSY (5) and SQLITE_LOCKED (6), including every extended
663            // code, are transient lock contention: the same operation can
664            // succeed after the conflicting operation releases its lock.
665            Some(5 | 6) => Self {
666                code: Some("client.storage_busy"),
667                sqlite_code,
668                sqlite_message: Some(error.to_string()),
669                rollback_failure: None,
670                message: "local SQLite storage is busy".to_owned(),
671            },
672            _ => Self {
673                code: None,
674                sqlite_code,
675                sqlite_message: Some(error.to_string()),
676                rollback_failure: None,
677                message: error.to_string(),
678            },
679        }
680    }
681}
682
683impl QueryReadFailure {
684    /// The operation can be retried after lock contention is resolved.
685    /// SQLITE_LOCKED can involve another statement on the same connection.
686    pub fn retryable(&self) -> bool {
687        self.code == Some("client.storage_busy")
688    }
689
690    pub fn details(&self) -> Option<Value> {
691        self.sqlite_code.map(|code| {
692            let mut details =
693                serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
694            if let Some(rollback) = &self.rollback_failure {
695                details["rollbackFailure"] = serde_json::json!({
696                    "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
697                });
698            }
699            details
700        })
701    }
702}
703
704/// A structured failure from a local authoring API (`mutate`/`patch`). `code`
705/// is always a stable `client.*`/`sync.*` identity, `message` is static text
706/// with no table/row/column values, `details` carries SQLite classification
707/// evidence or the preserved legacy cause, and `retryable` is true only for
708/// transient storage contention. Callers read these fields instead of parsing
709/// a `"<code>: "` prefix.
710#[derive(Debug, Clone, PartialEq, Eq)]
711pub struct ClientError {
712    pub code: String,
713    pub message: String,
714    pub details: Option<Value>,
715    pub retryable: bool,
716}
717
718/// The stable default for an authoring failure with no recognized code.
719const DEFAULT_CLIENT_ERROR_CODE: &str = "client.failed";
720
721/// The static text used when no specific static authoring message exists.
722const GENERIC_AUTHORING_MESSAGE: &str = "the local authoring operation failed";
723
724/// The fixed user-facing text for a known authoring code. Dynamic values from
725/// a legacy cause string move to `details.legacyCause` instead.
726fn static_authoring_message(code: &str) -> Option<&'static str> {
727    match code {
728        "sync.unknown_table" => Some("the commit targets an unknown table"),
729        "sync.invalid_request" => Some("the authoring request is invalid"),
730        "sync.row_missing" => Some("a sparse patch requires a local row"),
731        "sync.constraint_violation" => Some("local write violates a unique constraint"),
732        DEFAULT_CLIENT_ERROR_CODE => Some(GENERIC_AUTHORING_MESSAGE),
733        _ => None,
734    }
735}
736
737fn is_client_code(candidate: &str) -> bool {
738    candidate.starts_with("client.") || candidate.starts_with("sync.")
739}
740
741impl std::fmt::Display for ClientError {
742    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743        write!(f, "{}: {}", self.code, self.message)
744    }
745}
746
747impl std::error::Error for ClientError {}
748
749impl From<QueryReadFailure> for ClientError {
750    fn from(failure: QueryReadFailure) -> Self {
751        match failure.code {
752            // Classified storage messages are already static.
753            Some(code) => {
754                let details = failure.details();
755                let retryable = failure.retryable();
756                Self {
757                    code: code.to_owned(),
758                    message: failure.message,
759                    details,
760                    retryable,
761                }
762            }
763            None => {
764                let mut details = failure.details().unwrap_or_else(|| serde_json::json!({}));
765                if let Some(object) = details.as_object_mut() {
766                    object.insert("legacyCause".to_owned(), Value::String(failure.message));
767                }
768                Self {
769                    code: DEFAULT_CLIENT_ERROR_CODE.to_owned(),
770                    message: GENERIC_AUTHORING_MESSAGE.to_owned(),
771                    details: Some(details),
772                    retryable: false,
773                }
774            }
775        }
776    }
777}
778
779impl From<String> for ClientError {
780    /// Split a core error into structured fields. A recognized code identity
781    /// is preserved and gets static text; any dynamic cause stays in
782    /// `details.legacyCause`. Everything else defaults to `client.failed` with
783    /// the generic message.
784    fn from(message: String) -> Self {
785        // A code-only identity, e.g. `sync.unknown_table`.
786        if !message.contains(": ") && is_client_code(&message) {
787            return Self {
788                code: message.clone(),
789                message: static_authoring_message(&message)
790                    .unwrap_or(GENERIC_AUTHORING_MESSAGE)
791                    .to_owned(),
792                details: None,
793                retryable: false,
794            };
795        }
796        let (code, rest) = match message.split_once(": ") {
797            Some((code, rest)) if is_client_code(code) => (code, Some(rest)),
798            _ => (DEFAULT_CLIENT_ERROR_CODE, None),
799        };
800        match static_authoring_message(code) {
801            Some(fixed) => Self {
802                code: code.to_owned(),
803                message: fixed.to_owned(),
804                details: (rest != Some(fixed))
805                    .then(|| serde_json::json!({ "legacyCause": message })),
806                retryable: false,
807            },
808            None => Self {
809                code: code.to_owned(),
810                message: GENERIC_AUTHORING_MESSAGE.to_owned(),
811                details: Some(serde_json::json!({ "legacyCause": message })),
812                retryable: false,
813            },
814        }
815    }
816}
817
818#[derive(Debug, Clone, Serialize)]
819#[serde(rename_all = "camelCase")]
820pub struct QuerySnapshot {
821    pub revision: String,
822    pub rows: Vec<QueryRow>,
823    pub coverage: CoverageSnapshot,
824}
825
826impl WindowState {
827    /// The per-unit verdict: registered AND bootstrap-complete.
828    #[must_use]
829    pub fn complete(&self, unit: &str) -> bool {
830        self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
831    }
832}
833
834/// One local mutation (§6.1 shapes, schema-agnostic local form per §0).
835#[derive(Debug, Clone)]
836pub enum Mutation {
837    Patch {
838        table: String,
839        values: Map<String, Value>,
840        base_version: Option<i64>,
841    },
842    Upsert {
843        table: String,
844        values: Map<String, Value>,
845        base_version: Option<i64>,
846    },
847    Delete {
848        table: String,
849        row_id: String,
850        base_version: Option<i64>,
851    },
852}
853
854#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
855#[serde(rename_all = "camelCase")]
856pub struct SchemaFloor {
857    #[serde(skip_serializing_if = "Option::is_none")]
858    pub required_schema_version: Option<i32>,
859    #[serde(skip_serializing_if = "Option::is_none")]
860    pub latest_schema_version: Option<i32>,
861}
862
863/// §7.3.5: the client's opaque auth-lease state — `leaseId`/`expiresAtMs`
864/// from the last `LEASE` frame, and `errorCode` once a round was rejected
865/// with a request-level lease code (stop-and-surface; no data purge).
866#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
867#[serde(rename_all = "camelCase")]
868pub struct LeaseState {
869    #[serde(skip_serializing_if = "Option::is_none")]
870    pub lease_id: Option<String>,
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub expires_at_ms: Option<i64>,
873    #[serde(skip_serializing_if = "Option::is_none")]
874    pub error_code: Option<String>,
875}
876
877/// §8.6 a peer's ephemeral presence document on a scope key.
878#[derive(Debug, Clone, Serialize)]
879#[serde(rename_all = "camelCase")]
880pub struct PresencePeer {
881    pub actor_id: String,
882    pub client_id: String,
883    pub doc: serde_json::Value,
884}
885
886#[derive(Debug, Clone, Serialize, Default)]
887#[serde(rename_all = "camelCase")]
888pub struct SyncReport {
889    pub pushed: u32,
890    pub applied: Vec<String>,
891    pub rejected: Vec<String>,
892    pub retryable: Vec<String>,
893    pub conflicts: u32,
894    pub commits_applied: u32,
895    pub segment_rows_applied: u32,
896    pub bootstrapping: Vec<String>,
897    pub resets: Vec<String>,
898    pub revoked: Vec<String>,
899    pub failed: Vec<String>,
900    pub deferred_commits: usize,
901    #[serde(skip_serializing_if = "Option::is_none")]
902    pub schema_floor: Option<SchemaFloor>,
903}
904
905impl SyncReport {
906    /// Aggregate completed rounds. Historical counters and outcome lists
907    /// accumulate; current readiness (`bootstrapping`, `deferred_commits`,
908    /// `schema_floor`) describes the latest round. A schema floor stops the
909    /// loop, so it can only arrive from the latest round.
910    pub fn merge(&mut self, report: &Self) {
911        self.pushed += report.pushed;
912        self.applied.extend(report.applied.iter().cloned());
913        self.rejected.extend(report.rejected.iter().cloned());
914        self.retryable.extend(report.retryable.iter().cloned());
915        self.conflicts += report.conflicts;
916        self.commits_applied += report.commits_applied;
917        self.segment_rows_applied += report.segment_rows_applied;
918        self.bootstrapping = report.bootstrapping.clone();
919        self.resets.extend(report.resets.iter().cloned());
920        self.revoked.extend(report.revoked.iter().cloned());
921        self.failed.extend(report.failed.iter().cloned());
922        self.deferred_commits = report.deferred_commits;
923        self.schema_floor = report.schema_floor.clone();
924    }
925}
926
927/// `sync()` never panics or errors out-of-band: transport and protocol
928/// failures come back as `Failed` (the driver's `{ ok: false }`).
929#[derive(Debug, Clone)]
930pub enum SyncOutcome {
931    Ok(SyncReport),
932    Failed {
933        error_code: String,
934        message: String,
935        details: Option<Value>,
936        /// §10.1 `recommendedAction` from the server's error body, when the
937        /// transport preserved one. Client-local and storage failures carry
938        /// `None`.
939        recommended_action: Option<String>,
940    },
941    /// §8.8: the `required` policy refused a round because the socket is not
942    /// connected. `reason_code` is present for `lost` and `refused` states,
943    /// and `retry_delay_ms` is the delay of the background retry intent this
944    /// outcome scheduled.
945    RealtimeUnavailable {
946        state: RealtimeState,
947        reason_code: Option<String>,
948        retry_delay_ms: u64,
949    },
950    /// §7.8: the round budget ran out while the client was still not idle.
951    /// The aggregate report of every round that ran is retained. This is a
952    /// partial success, not a failure, and MUST NOT be read as idle.
953    BudgetExhausted(SyncReport),
954}
955
956impl SyncOutcome {
957    pub fn to_json(&self) -> Value {
958        match self {
959            SyncOutcome::Ok(report) => {
960                let mut map = Map::new();
961                map.insert("ok".to_owned(), Value::Bool(true));
962                map.insert(
963                    "report".to_owned(),
964                    serde_json::to_value(report).expect("report serializes"),
965                );
966                Value::Object(map)
967            }
968            SyncOutcome::Failed {
969                error_code,
970                message,
971                details,
972                recommended_action,
973            } => {
974                let mut map = Map::new();
975                map.insert("ok".to_owned(), Value::Bool(false));
976                map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
977                map.insert("message".to_owned(), Value::from(message.clone()));
978                if let Some(details) = details {
979                    map.insert("details".to_owned(), details.clone());
980                }
981                if let Some(recommended_action) = recommended_action {
982                    map.insert(
983                        "recommendedAction".to_owned(),
984                        Value::from(recommended_action.clone()),
985                    );
986                }
987                Value::Object(map)
988            }
989            SyncOutcome::RealtimeUnavailable {
990                state,
991                reason_code,
992                retry_delay_ms,
993            } => {
994                let mut map = Map::new();
995                map.insert("ok".to_owned(), Value::Bool(false));
996                map.insert(
997                    "errorCode".to_owned(),
998                    Value::from(REALTIME_UNAVAILABLE_CODE),
999                );
1000                map.insert(
1001                    "message".to_owned(),
1002                    Value::from("realtime is required and the realtime socket is not connected"),
1003                );
1004                map.insert(
1005                    "realtimeState".to_owned(),
1006                    serde_json::to_value(state).expect("state serializes"),
1007                );
1008                if let Some(reason_code) = reason_code {
1009                    map.insert(
1010                        "realtimeReasonCode".to_owned(),
1011                        Value::from(reason_code.clone()),
1012                    );
1013                }
1014                map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
1015                Value::Object(map)
1016            }
1017            SyncOutcome::BudgetExhausted(report) => {
1018                let mut map = Map::new();
1019                map.insert("ok".to_owned(), Value::Bool(true));
1020                map.insert("budgetExhausted".to_owned(), Value::Bool(true));
1021                map.insert(
1022                    "report".to_owned(),
1023                    serde_json::to_value(report).expect("report serializes"),
1024                );
1025                Value::Object(map)
1026            }
1027        }
1028    }
1029}
1030
1031#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1032#[serde(rename_all = "camelCase")]
1033pub struct ConflictRecord {
1034    pub client_commit_id: String,
1035    pub op_index: i32,
1036    pub table: String,
1037    pub row_id: String,
1038    pub code: String,
1039    pub message: String,
1040    pub server_version: i64,
1041    /// Driver row (bytes as `{"$bytes": hex}`), decoded from the conflict
1042    /// record's `serverRow` (§6.3).
1043    pub server_row: Map<String, Value>,
1044    /// §6.3 `conflictColumns`: the present columns whose `column_version`
1045    /// exceeded `baseVersion`, decoded from the bitmap into column names in
1046    /// declaration order. Absent on a legacy journal entry, which reads as an
1047    /// empty list.
1048    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1049    pub conflict_columns: Vec<String>,
1050    #[serde(skip_serializing_if = "Option::is_none")]
1051    pub operation: Option<CommitOperation>,
1052}
1053
1054/// Bounded code-like metadata explicitly declared safe for authorized client
1055/// recovery UI. Diagnostic prose remains in `RejectionRecord.message`.
1056#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1057#[serde(rename_all = "camelCase", deny_unknown_fields)]
1058pub struct RejectionDetails {
1059    #[serde(skip_serializing_if = "Option::is_none")]
1060    pub field_paths: Option<Vec<String>>,
1061    #[serde(skip_serializing_if = "Option::is_none")]
1062    pub reason: Option<String>,
1063    #[serde(skip_serializing_if = "Option::is_none")]
1064    pub required_action: Option<String>,
1065    #[serde(skip_serializing_if = "Option::is_none")]
1066    pub references: Option<BTreeMap<String, String>>,
1067}
1068
1069impl RejectionDetails {
1070    pub(crate) fn parse(raw: &str) -> Result<Self, String> {
1071        if raw.len() > 4_096 {
1072            return Err("rejection details exceed 4096 encoded bytes".to_owned());
1073        }
1074        let details: Self = serde_json::from_str(raw)
1075            .map_err(|error| format!("invalid rejection details: {error}"))?;
1076        details.validate()?;
1077        Ok(details)
1078    }
1079
1080    fn validate(&self) -> Result<(), String> {
1081        let mut members = 0;
1082        if let Some(paths) = &self.field_paths {
1083            members += 1;
1084            if paths.is_empty() || paths.len() > 32 {
1085                return Err("fieldPaths must contain 1-32 paths".to_owned());
1086            }
1087            let mut seen = std::collections::BTreeSet::new();
1088            for path in paths {
1089                if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
1090                {
1091                    return Err("fieldPaths contains an invalid or duplicate path".to_owned());
1092                }
1093            }
1094        }
1095        if let Some(reason) = &self.reason {
1096            members += 1;
1097            if !valid_token(reason, 96) {
1098                return Err("reason must be a lowercase stable token".to_owned());
1099            }
1100        }
1101        if let Some(action) = &self.required_action {
1102            members += 1;
1103            if !valid_token(action, 96) {
1104                return Err("requiredAction must be a lowercase stable token".to_owned());
1105            }
1106        }
1107        if let Some(references) = &self.references {
1108            members += 1;
1109            if references.is_empty() || references.len() > 16 {
1110                return Err("references must contain 1-16 entries".to_owned());
1111            }
1112            for (key, value) in references {
1113                if !valid_token(key, 64)
1114                    || value.is_empty()
1115                    || value.len() > 256
1116                    || value.trim() != value
1117                    || value.chars().any(char::is_control)
1118                {
1119                    return Err("references contains an invalid key or value".to_owned());
1120                }
1121            }
1122        }
1123        if members == 0 {
1124            return Err("rejection details must not be empty".to_owned());
1125        }
1126        Ok(())
1127    }
1128}
1129
1130fn valid_identifier(segment: &str) -> bool {
1131    let mut chars = segment.chars();
1132    matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
1133        && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1134}
1135
1136fn valid_token(token: &str, max: usize) -> bool {
1137    if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
1138    {
1139        return false;
1140    }
1141    let mut previous_separator = false;
1142    for character in token.chars() {
1143        if character.is_ascii_lowercase() || character.is_ascii_digit() {
1144            previous_separator = false;
1145        } else if matches!(character, '.' | '_' | '-') && !previous_separator {
1146            previous_separator = true;
1147        } else {
1148            return false;
1149        }
1150    }
1151    !previous_separator
1152}
1153
1154#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1155#[serde(rename_all = "camelCase")]
1156pub struct RejectionRecord {
1157    pub client_commit_id: String,
1158    pub op_index: i32,
1159    pub code: String,
1160    pub message: String,
1161    pub retryable: bool,
1162    #[serde(skip_serializing_if = "Option::is_none")]
1163    pub details: Option<RejectionDetails>,
1164    #[serde(skip_serializing_if = "Option::is_none")]
1165    pub operation: Option<CommitOperation>,
1166}
1167
1168/// Schema-agnostic local operation retained with a failed final outcome.
1169#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1170#[serde(rename_all = "camelCase")]
1171pub struct CommitOperation {
1172    pub table: String,
1173    pub row_id: String,
1174    pub op: String,
1175    #[serde(skip_serializing_if = "Option::is_none")]
1176    pub base_version: Option<i64>,
1177    #[serde(skip_serializing_if = "Option::is_none")]
1178    pub values: Option<Map<String, Value>>,
1179    /// §7.1 insert intent: serialized as `"insert": true`, absent otherwise.
1180    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1181    pub insert: bool,
1182}
1183
1184/// One pending outbox commit (§7.1), in the shape the TypeScript client's
1185/// `pendingCommits()` returns.
1186#[derive(Debug, Clone, Serialize, PartialEq)]
1187#[serde(rename_all = "camelCase")]
1188pub struct PendingCommit {
1189    /// The outbox sequence number; FIFO send order.
1190    pub seq: i64,
1191    pub client_commit_id: String,
1192    /// Local clock at `mutate`; 0 for a commit queued before 0.89.
1193    pub created_at_ms: i64,
1194    pub operations: Vec<CommitOperation>,
1195}
1196
1197#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1198#[serde(rename_all = "snake_case")]
1199pub enum CommitOutcomeStatus {
1200    Applied,
1201    Cached,
1202    Conflict,
1203    Rejected,
1204}
1205
1206#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1207#[serde(rename_all = "snake_case")]
1208pub enum CommitOutcomeResolution {
1209    Active,
1210    ResolvedKeepServer,
1211    Superseded,
1212    Dismissed,
1213}
1214
1215#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1216#[serde(tag = "status", rename_all = "snake_case")]
1217pub enum CommitOperationOutcome {
1218    Applied {
1219        #[serde(rename = "opIndex")]
1220        op_index: i32,
1221    },
1222    Conflict {
1223        conflict: ConflictRecord,
1224    },
1225    Error {
1226        rejection: RejectionRecord,
1227    },
1228}
1229
1230#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1231#[serde(rename_all = "camelCase")]
1232pub struct RetainedUniqueConflict {
1233    pub index: String,
1234    pub columns: Vec<String>,
1235    pub row_id: String,
1236    pub server_row: Map<String, Value>,
1237    pub server_version: i64,
1238}
1239
1240#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1241#[serde(rename_all = "camelCase")]
1242pub struct RetainedCommitRow {
1243    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1244    pub unique_conflicts: Vec<RetainedUniqueConflict>,
1245    pub table: String,
1246    pub row_id: String,
1247    pub local_row: Option<Map<String, Value>>,
1248    /// The latest delivered authorized base; rejection can precede the pull.
1249    pub server_row: Option<Map<String, Value>>,
1250    pub server_version: Option<i64>,
1251}
1252
1253/// Result of proving every retained base after a completed pull (§7.2.1).
1254#[derive(Debug, Clone, Serialize, PartialEq)]
1255#[serde(rename_all = "camelCase")]
1256pub struct CurrentBaseProof {
1257    pub proven: bool,
1258    #[serde(skip_serializing_if = "Option::is_none")]
1259    pub rows: Option<Vec<RetainedCommitRow>>,
1260    #[serde(skip_serializing_if = "Option::is_none")]
1261    pub reason: Option<CurrentBaseProofReason>,
1262}
1263
1264#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1265#[serde(rename_all = "snake_case")]
1266pub enum CurrentBaseProofReason {
1267    Offline,
1268    SyncFailed,
1269    SchemaFloor,
1270    BudgetExhausted,
1271    SnapshotFailed,
1272    MissingCoverage,
1273    Revoked,
1274    OutcomeUnavailable,
1275}
1276
1277impl CurrentBaseProof {
1278    pub fn failure(reason: CurrentBaseProofReason) -> Self {
1279        Self {
1280            proven: false,
1281            rows: None,
1282            reason: Some(reason),
1283        }
1284    }
1285}
1286
1287#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1288#[serde(rename_all = "camelCase")]
1289pub struct CommitOutcome {
1290    pub sequence: i64,
1291    pub client_commit_id: String,
1292    pub status: CommitOutcomeStatus,
1293    pub recorded_at_ms: i64,
1294    pub results: Vec<CommitOperationOutcome>,
1295    /// Complete local failed-commit envelope retained after outbox drain.
1296    /// Absent for successful and historical outcomes; never sent over wire.
1297    #[serde(skip_serializing_if = "Option::is_none")]
1298    pub operations: Option<Vec<CommitOperation>>,
1299    #[serde(skip_serializing_if = "Option::is_none")]
1300    pub retained_rows: Option<Vec<RetainedCommitRow>>,
1301    pub resolution: CommitOutcomeResolution,
1302    #[serde(skip_serializing_if = "Option::is_none")]
1303    pub resolved_at_ms: Option<i64>,
1304    #[serde(skip_serializing_if = "Option::is_none")]
1305    pub replacement_client_commit_id: Option<String>,
1306}
1307
1308#[derive(Debug, Clone, Deserialize, Default)]
1309#[serde(rename_all = "camelCase")]
1310pub struct CommitOutcomeQuery {
1311    pub limit: Option<usize>,
1312    #[serde(default)]
1313    pub active_only: bool,
1314}
1315
1316/// §7.5: the catch-up state of one unit as persisted in the snapshot, never
1317/// the mutable owner cache. `Unknown` means the client does not currently
1318/// hold the unit (never registered, released, or removed).
1319#[derive(Debug, Clone, Serialize)]
1320#[serde(
1321    tag = "state",
1322    rename_all = "camelCase",
1323    rename_all_fields = "camelCase"
1324)]
1325pub enum UnitCatchup {
1326    Unknown {
1327        id: String,
1328    },
1329    Known {
1330        id: String,
1331        status: UnitStatus,
1332        live: bool,
1333        /// The unit's cursor while it catches up, the replica cursor while live.
1334        cursor: i64,
1335        has_resume_token: bool,
1336        /// True only for an `active` unit that is live or post-bootstrap.
1337        bootstrap_complete: bool,
1338        /// True only for an `active` unit with cursor `-1` or a resume token.
1339        known_pending_pages: bool,
1340        #[serde(skip_serializing_if = "Option::is_none")]
1341        reason_code: Option<String>,
1342    },
1343}
1344
1345/// §7.5: delivery status for one client commit id. A commit still in the
1346/// outbox is `pending`; a drained commit carries its persisted retained
1347/// outcome; an id the client never held, or whose outcome was pruned by
1348/// retention, is `unknown`. The outcome preserves every operation result,
1349/// rejection code, and conflict. This is the persisted-journal view in both
1350/// cores: it omits the owner-derived `retained_rows` images that
1351/// `SyncClient::commit_outcome` attaches from its in-memory failed-commit
1352/// cache.
1353#[derive(Debug, Clone, Serialize)]
1354#[serde(tag = "status", rename_all = "snake_case")]
1355pub enum CommitDelivery {
1356    Pending {
1357        #[serde(rename = "clientCommitId")]
1358        client_commit_id: String,
1359    },
1360    Known {
1361        #[serde(rename = "clientCommitId")]
1362        client_commit_id: String,
1363        outcome: CommitOutcome,
1364    },
1365    Unknown {
1366        #[serde(rename = "clientCommitId")]
1367        client_commit_id: String,
1368    },
1369}
1370
1371/// §7.5: the result of one atomic snapshot read over a single SQLite read
1372/// transaction: one revision, every requested read-only statement's rows,
1373/// requested window coverage, requested unit catch-up states, and requested
1374/// commit deliveries.
1375#[derive(Debug, Clone, Serialize)]
1376#[serde(rename_all = "camelCase")]
1377pub struct SnapshotRead {
1378    pub revision: String,
1379    pub queries: Vec<Vec<QueryRow>>,
1380    pub coverage: CoverageSnapshot,
1381    pub units: Vec<UnitCatchup>,
1382    pub deliveries: Vec<CommitDelivery>,
1383}
1384
1385#[derive(Debug, Clone, Deserialize)]
1386#[serde(rename_all = "camelCase")]
1387pub struct ResolveCommitOutcomeInput {
1388    pub client_commit_id: String,
1389    pub resolution: CommitOutcomeResolution,
1390    pub replacement_client_commit_id: Option<String>,
1391}
1392
1393#[derive(Debug, Clone, Serialize)]
1394#[serde(rename_all = "camelCase")]
1395pub struct RowState {
1396    pub row_id: String,
1397    /// Local synced version: `-1` = optimistic, else the server version
1398    /// (from a `COMMIT` change or a segment row record, §5.2/§5.6).
1399    pub version: i64,
1400    pub values: Map<String, Value>,
1401    /// §5.11 `_sync_sealed_key` of a sealed row; absent on an unsealed row.
1402    #[serde(skip_serializing_if = "Option::is_none")]
1403    pub sealed_key: Option<String>,
1404}
1405
1406/// One AND-combined application-authorized local purge target. Targets in
1407/// one input are OR-combined. Selector columns must compile to plaintext
1408/// strings; values are bounded code-like routing identifiers.
1409#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1410#[serde(rename_all = "camelCase", deny_unknown_fields)]
1411pub struct LocalDataPurgeTarget {
1412    pub table: String,
1413    pub selectors: BTreeMap<String, Vec<String>>,
1414}
1415
1416/// Durable local idempotency key plus exact routing targets. The host owns
1417/// directive authenticity and subscription gating; the client owns SQLite.
1418#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1419#[serde(rename_all = "camelCase", deny_unknown_fields)]
1420pub struct LocalDataPurgeInput {
1421    pub purge_id: String,
1422    pub targets: Vec<LocalDataPurgeTarget>,
1423}
1424
1425/// Privacy-safe local purge acknowledgement; row ids never cross the bridge.
1426#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1427#[serde(rename_all = "camelCase")]
1428pub struct LocalDataPurgeResult {
1429    pub already_applied: bool,
1430    pub purged_rows: usize,
1431    pub dropped_commits: usize,
1432}
1433
1434/// Durable application repair id. Reusing the id is an exact no-op.
1435#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1436#[serde(rename_all = "camelCase", deny_unknown_fields)]
1437pub struct LocalDataRebootstrapInput {
1438    pub rebootstrap_id: String,
1439}
1440
1441/// Privacy-safe acknowledgement for a replicated-projection recovery.
1442#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1443#[serde(rename_all = "camelCase")]
1444pub struct LocalDataRebootstrapResult {
1445    pub already_applied: bool,
1446    pub retained_commits: usize,
1447    pub reset_subscriptions: usize,
1448}
1449
1450/// Client limits (§4.2 request knobs).
1451#[derive(Debug, Clone, Default)]
1452pub struct ClientLimits {
1453    pub limit_commits: Option<i32>,
1454    pub limit_snapshot_rows: Option<i32>,
1455    pub max_snapshot_pages: Option<i32>,
1456    /// §4.2 accept bitmask; this client defaults to `0b0111` (rows
1457    /// baseline + sqlite images, §5.3 — rusqlite can always import).
1458    pub accept: Option<u8>,
1459    /// §5.9.7 B1 blob-cache size cap (bytes). When set and the sum of cached
1460    /// body sizes exceeds it, unreferenced bodies without pending work are
1461    /// evicted by creation timestamp after each cache write. `None` retains bodies
1462    /// until storage pressure (default).
1463    pub blob_cache_max_bytes: Option<i64>,
1464    /// Maximum durable final outcomes. Active conflicts/rejections are never
1465    /// pruned to satisfy the cap. Defaults to 1,000.
1466    pub outcome_retention_max_entries: Option<usize>,
1467    /// §7.1: maximum whole commits in one push request. `None` is unbounded.
1468    pub max_push_commits_per_request: Option<usize>,
1469    /// §7.1: maximum operations across the push commits in one request. `None`
1470    /// uses the reference default of 500. A first commit that alone exceeds it
1471    /// is a typed `client.push_request_too_large` capacity error and stays
1472    /// queued.
1473    pub max_push_operations_per_request: Option<usize>,
1474    /// §7.1: maximum bytes of the complete encoded SSP2 request (8-byte
1475    /// envelope, request header, push commits, pull header, units and progress frames,
1476    /// framing, and any §5.11 ciphertext). `None` is unbounded. A request whose
1477    /// fixed frames alone exceed it, or whose first commit alone does not fit,
1478    /// fails with `client.push_request_too_large` and keeps its intent.
1479    pub max_push_request_bytes: Option<usize>,
1480    /// RFC 0005 D8: the previous-version capture config. Absent or
1481    /// `enabled: false` runs the feature off (default); the descriptor write
1482    /// and the container orphan sweep still happen.
1483    pub previous_version_context: Option<PreviousVersionContextConfig>,
1484    /// Immutable, explicit preflight authority read policy.
1485    pub authority_reads: Vec<AuthorityReadDeclaration>,
1486}
1487
1488/// Static read policy; never accepted as snapshot parameters.
1489#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
1490#[serde(rename_all = "camelCase", deny_unknown_fields)]
1491pub struct AuthorityReadDeclaration {
1492    pub table: String,
1493    pub columns: Vec<String>,
1494    pub scopes: std::collections::BTreeMap<String, Vec<String>>,
1495}