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