1use std::collections::BTreeMap;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::previous_version::PreviousVersionContextConfig;
12pub type QueryValue = Value;
14pub type QueryRow = Map<String, QueryValue>;
16
17#[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(×tamp_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
55pub 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
65pub 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
97pub type UnitScopes = BTreeMap<String, String>;
99
100#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct EchoRecord {
123 pub table: String,
124 pub status: String,
126 pub scopes: BTreeMap<String, Vec<String>>,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct UnitRestriction {
134 pub cursor: i64,
135 pub tables: Vec<String>,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct UnitRecord {
142 pub id: String,
144 pub scopes: UnitScopes,
145 pub explicit: bool,
148 pub status: UnitStatus,
149 #[serde(skip_serializing_if = "Option::is_none")]
151 pub reason_code: Option<String>,
152 #[serde(skip_serializing_if = "Option::is_none")]
155 pub cursor: Option<i64>,
156 #[serde(skip_serializing_if = "Option::is_none")]
158 pub bootstrap_state: Option<String>,
159 pub seeded: Vec<String>,
161 #[serde(skip_serializing_if = "Option::is_none")]
163 pub echo: Option<Vec<EchoRecord>>,
164 #[serde(skip_serializing_if = "Option::is_none")]
166 pub restriction: Option<UnitRestriction>,
167}
168
169impl UnitRecord {
170 pub fn bootstrapping(&self) -> bool {
172 self.cursor
173 .is_some_and(|cursor| cursor < 0 || self.bootstrap_state.is_some())
174 }
175}
176
177#[derive(Debug, Clone, Default)]
181pub struct WindowBase {
182 pub variable: String,
183 pub fixed_scopes: UnitScopes,
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
194#[serde(rename_all = "camelCase")]
195pub struct WindowState {
196 pub units: Vec<String>,
198 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; 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 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 pub upgrade_kept_tables: bool,
252 #[serde(skip_serializing_if = "Option::is_none")]
253 pub lease_state: Option<LeaseState>,
254 #[serde(skip_serializing_if = "Option::is_none")]
255 pub schema_floor: Option<SchemaFloor>,
256 pub sync_needed: bool,
257 pub previous_version_context: PreviousVersionStatus,
260 pub security_lifecycle: &'static str,
263}
264
265#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
267#[serde(rename_all = "camelCase")]
268pub struct PreviousVersionStatus {
269 pub present: bool,
270 #[serde(skip_serializing_if = "Option::is_none")]
271 pub created_at_ms: Option<i64>,
272}
273
274pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 2;
275pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;
276
277pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
280pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
283pub const LOCAL_AUTHORITY_UNCONFIGURED_CODE: &str = "client.local_authority_unconfigured";
287
288#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
289#[serde(rename_all = "camelCase")]
290pub struct ClientDiagnosticsHost {
291 pub kind: String,
292 pub role: String,
293 pub connectivity: String,
294 pub realtime: RealtimeState,
295 pub realtime_policy: RealtimePolicy,
296 #[serde(skip_serializing_if = "Option::is_none")]
297 pub realtime_reason_code: Option<String>,
298 #[serde(skip_serializing_if = "Option::is_none")]
299 pub realtime_retry_delay_ms: Option<u64>,
300}
301
302#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
304#[serde(rename_all = "camelCase")]
305pub struct DiagnosticUnits {
306 pub bootstrapping: usize,
307 pub complete: usize,
308 pub reset: usize,
309 pub revoked: usize,
310 pub failed: usize,
311 pub reason_codes: Vec<String>,
313}
314
315#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
316#[serde(rename_all = "camelCase")]
317pub struct DiagnosticRoundCounters {
318 pub pushed: u32,
319 pub applied: usize,
320 pub rejected: usize,
321 pub retryable: usize,
322 pub conflicts: u32,
323 pub commits_applied: u32,
324 pub segment_rows_applied: u32,
325 pub bootstrapping: usize,
326 pub resets: usize,
327 pub revoked: usize,
328 pub failed: usize,
329 pub deferred_commits: usize,
330}
331
332#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
334#[serde(rename_all = "snake_case")]
335pub enum TransportCauseKind {
336 Network,
337 Connect,
338 Tls,
339 Io,
340 Request,
341 Protocol,
342 Timeout,
343 RoundDeadline,
344 Aborted,
345 Body,
346 Status,
347 Redirect,
348 Unknown,
349}
350
351#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
352#[serde(rename_all = "camelCase")]
353pub struct DiagnosticLastRound {
354 pub epoch: String,
356 pub attempt: u64,
357 pub status: String,
358 pub started_at_ms: i64,
359 pub completed_at_ms: i64,
360 pub duration_ms: i64,
361 #[serde(skip_serializing_if = "Option::is_none")]
362 pub counters: Option<DiagnosticRoundCounters>,
363 #[serde(skip_serializing_if = "Option::is_none")]
364 pub error_code: Option<String>,
365 #[serde(skip_serializing_if = "Option::is_none")]
366 pub cause_kind: Option<TransportCauseKind>,
367 #[serde(skip_serializing_if = "Option::is_none")]
368 pub http_status: Option<u16>,
369}
370
371#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
372#[serde(rename_all = "camelCase")]
373pub struct DiagnosticLastChange {
374 pub revision: String,
375 pub recorded_at_ms: i64,
376 pub tables: Vec<String>,
377 pub windows: Vec<String>,
378 pub domains_truncated: bool,
379 pub status_changed: bool,
380 pub conflicts_changed: bool,
381 pub rejections_changed: bool,
382 pub outcomes_changed: bool,
383}
384
385#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
386#[serde(rename_all = "camelCase")]
387pub struct ClientDiagnosticsStorage {
388 pub status: String,
389 #[serde(skip_serializing_if = "Option::is_none")]
390 pub database_bytes_approx: Option<i64>,
391 #[serde(skip_serializing_if = "Option::is_none")]
392 pub pending_outbox_bytes_approx: Option<i64>,
393 #[serde(skip_serializing_if = "Option::is_none")]
394 pub retained_outcome_bytes_approx: Option<i64>,
395 #[serde(skip_serializing_if = "Option::is_none")]
396 pub retained_outcome_entries: Option<i64>,
397 #[serde(skip_serializing_if = "Option::is_none")]
398 pub blob_cache_bytes_approx: Option<i64>,
399 #[serde(skip_serializing_if = "Option::is_none")]
400 pub pressure_reason_code: Option<String>,
401}
402
403#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
405#[serde(rename_all = "camelCase")]
406pub struct DiagnosticQueryFailure {
407 pub id: String,
408 pub tables: Vec<String>,
410 pub code: String,
412 #[serde(skip_serializing_if = "Option::is_none")]
414 pub sqlite_code: Option<i32>,
415 pub at_ms: i64,
417}
418
419#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
420#[serde(rename_all = "camelCase")]
421pub struct ClientDiagnosticsSnapshot {
422 pub version: u8,
423 pub captured_at_ms: i64,
424 pub host: ClientDiagnosticsHost,
425 pub security_lifecycle: String,
426 pub schema: ClientDiagnosticsSchema,
427 pub replica: ClientDiagnosticsReplica,
428 pub lease: ClientDiagnosticsLease,
429 pub units: DiagnosticUnits,
430 pub active_units: usize,
433 pub replica_cursor: i64,
435 #[serde(skip_serializing_if = "Option::is_none")]
436 pub last_round: Option<DiagnosticLastRound>,
437 #[serde(skip_serializing_if = "Option::is_none")]
438 pub last_change: Option<DiagnosticLastChange>,
439 pub storage: ClientDiagnosticsStorage,
440 pub query_failures: Vec<DiagnosticQueryFailure>,
441}
442
443#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
444#[serde(rename_all = "camelCase")]
445pub struct ClientDiagnosticsSchema {
446 pub current_version: i32,
447 pub upgrading: bool,
448 #[serde(skip_serializing_if = "Option::is_none")]
449 pub required_version: Option<i32>,
450 #[serde(skip_serializing_if = "Option::is_none")]
451 pub latest_version: Option<i32>,
452}
453
454#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
455#[serde(rename_all = "camelCase")]
456pub struct ClientDiagnosticsReplica {
457 pub local_revision: String,
458 pub sync_needed: bool,
459 pub pending_outbox: usize,
460}
461
462#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
464#[serde(rename_all = "lowercase")]
465pub enum RealtimePolicy {
466 Required,
467 #[default]
468 Optional,
469 Off,
470}
471
472impl RealtimePolicy {
473 #[must_use]
474 pub fn as_str(self) -> &'static str {
475 match self {
476 RealtimePolicy::Required => "required",
477 RealtimePolicy::Optional => "optional",
478 RealtimePolicy::Off => "off",
479 }
480 }
481}
482
483#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
488#[serde(rename_all = "lowercase")]
489pub enum RealtimeState {
490 Connected,
491 Connecting,
492 #[default]
493 Disconnected,
494 Lost,
495 Refused,
496 Disabled,
497}
498
499#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
500#[serde(rename_all = "camelCase")]
501pub struct ClientDiagnosticsLease {
502 pub state: String,
503 #[serde(skip_serializing_if = "Option::is_none")]
504 pub expires_at_ms: Option<i64>,
505 #[serde(skip_serializing_if = "Option::is_none")]
506 pub error_code: Option<String>,
507}
508
509#[derive(Debug, Clone, Serialize)]
511#[serde(rename_all = "camelCase")]
512pub struct AppliedServerCommit {
513 pub table: String,
514 pub commit_seq: i64,
515 pub source: AppliedServerCommitSource,
516}
517
518#[derive(Debug, Clone, Copy, Serialize)]
519#[serde(rename_all = "camelCase")]
520pub enum AppliedServerCommitSource {
521 Delta,
522 Pull,
523}
524
525#[derive(Debug, Clone, Serialize)]
526#[serde(rename_all = "camelCase")]
527pub struct ClientChangeBatch {
528 pub revision: String,
529 pub tables: Vec<TableChange>,
530 pub windows: Vec<WindowChange>,
531 #[serde(skip_serializing_if = "Option::is_none")]
532 pub status: Option<SyncStatusSnapshot>,
533 pub conflicts_changed: bool,
534 pub rejections_changed: bool,
535 pub outcomes_changed: bool,
536 #[serde(skip_serializing_if = "Vec::is_empty")]
537 pub applied_commits: Vec<AppliedServerCommit>,
538}
539
540#[derive(Debug, Clone, Serialize)]
541#[serde(tag = "kind", rename_all = "camelCase")]
542pub enum SyncIntent {
543 None,
544 Interactive,
545 Background {
546 #[serde(rename = "delayMs")]
547 delay_ms: u64,
548 },
549}
550
551#[derive(Debug, Clone, Serialize)]
552pub struct CommandEffects {
553 pub sync: SyncIntent,
554}
555
556impl CommandEffects {
557 #[must_use]
558 pub fn none() -> Self {
559 Self {
560 sync: SyncIntent::None,
561 }
562 }
563
564 #[must_use]
565 pub fn interactive() -> Self {
566 Self {
567 sync: SyncIntent::Interactive,
568 }
569 }
570}
571
572#[derive(Debug, Clone)]
573pub struct WindowCoverage {
574 pub base: WindowBase,
575 pub units: Vec<String>,
576}
577
578#[derive(Debug, Clone, Serialize)]
579#[serde(rename_all = "camelCase")]
580pub struct WindowUnitRef {
581 pub base_key: String,
582 pub unit: String,
583}
584
585#[derive(Debug, Clone, Serialize)]
586#[serde(rename_all = "camelCase")]
587pub struct CoverageSnapshot {
588 pub complete: bool,
589 pub pending: Vec<WindowUnitRef>,
590 pub missing: Vec<WindowUnitRef>,
591}
592
593#[derive(Debug, Clone, Copy)]
596pub struct QueryOwner<'a> {
597 pub id: &'a str,
598 pub tables: &'a [&'a str],
599}
600
601#[derive(Debug, Clone, PartialEq, Eq)]
606pub struct QueryReadFailure {
607 pub code: Option<&'static str>,
608 pub sqlite_code: Option<i32>,
609 pub sqlite_message: Option<String>,
610 pub rollback_failure: Option<Box<QueryReadFailure>>,
611 pub message: String,
612}
613
614impl std::fmt::Display for QueryReadFailure {
615 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616 match self.code {
617 Some(code) => write!(f, "{code}: {}", self.message),
618 None => f.write_str(&self.message),
619 }
620 }
621}
622
623impl From<String> for QueryReadFailure {
624 fn from(message: String) -> Self {
625 Self {
626 code: None,
627 sqlite_code: None,
628 sqlite_message: None,
629 rollback_failure: None,
630 message,
631 }
632 }
633}
634
635impl From<rusqlite::Error> for QueryReadFailure {
636 fn from(error: rusqlite::Error) -> Self {
638 let sqlite_code = match &error {
639 rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
640 _ => None,
641 };
642 match sqlite_code.map(|code| code & 0xff) {
643 Some(11 | 26) => Self {
644 code: Some("client.storage_corrupt"),
645 sqlite_code,
646 sqlite_message: Some(error.to_string()),
647 rollback_failure: None,
648 message: "local SQLite storage is corrupt".to_owned(),
649 },
650 Some(13) => Self {
651 code: Some("client.storage_full"),
652 sqlite_code,
653 sqlite_message: Some(error.to_string()),
654 rollback_failure: None,
655 message: "local SQLite storage is full".to_owned(),
656 },
657 Some(10) => Self {
658 code: Some("client.storage_io"),
659 sqlite_code,
660 sqlite_message: Some(error.to_string()),
661 rollback_failure: None,
662 message: "local SQLite storage I/O failed".to_owned(),
663 },
664 Some(5 | 6) => Self {
668 code: Some("client.storage_busy"),
669 sqlite_code,
670 sqlite_message: Some(error.to_string()),
671 rollback_failure: None,
672 message: "local SQLite storage is busy".to_owned(),
673 },
674 _ => Self {
675 code: None,
676 sqlite_code,
677 sqlite_message: Some(error.to_string()),
678 rollback_failure: None,
679 message: error.to_string(),
680 },
681 }
682 }
683}
684
685impl QueryReadFailure {
686 pub fn retryable(&self) -> bool {
689 self.code == Some("client.storage_busy")
690 }
691
692 pub fn details(&self) -> Option<Value> {
693 self.sqlite_code.map(|code| {
694 let mut details =
695 serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
696 if let Some(rollback) = &self.rollback_failure {
697 details["rollbackFailure"] = serde_json::json!({
698 "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
699 });
700 }
701 details
702 })
703 }
704}
705
706#[derive(Debug, Clone, PartialEq, Eq)]
713pub struct ClientError {
714 pub code: String,
715 pub message: String,
716 pub details: Option<Value>,
717 pub retryable: bool,
718}
719
720const DEFAULT_CLIENT_ERROR_CODE: &str = "client.failed";
722
723const GENERIC_AUTHORING_MESSAGE: &str = "the local authoring operation failed";
725
726fn static_authoring_message(code: &str) -> Option<&'static str> {
729 match code {
730 "sync.unknown_table" => Some("the commit targets an unknown table"),
731 "sync.invalid_request" => Some("the authoring request is invalid"),
732 "sync.row_missing" => Some("a sparse patch requires a local row"),
733 "sync.constraint_violation" => Some("local write violates a unique constraint"),
734 DEFAULT_CLIENT_ERROR_CODE => Some(GENERIC_AUTHORING_MESSAGE),
735 _ => None,
736 }
737}
738
739fn is_client_code(candidate: &str) -> bool {
740 candidate.starts_with("client.") || candidate.starts_with("sync.")
741}
742
743impl std::fmt::Display for ClientError {
744 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
745 write!(f, "{}: {}", self.code, self.message)
746 }
747}
748
749impl std::error::Error for ClientError {}
750
751impl From<QueryReadFailure> for ClientError {
752 fn from(failure: QueryReadFailure) -> Self {
753 match failure.code {
754 Some(code) => {
756 let details = failure.details();
757 let retryable = failure.retryable();
758 Self {
759 code: code.to_owned(),
760 message: failure.message,
761 details,
762 retryable,
763 }
764 }
765 None => {
766 let mut details = failure.details().unwrap_or_else(|| serde_json::json!({}));
767 if let Some(object) = details.as_object_mut() {
768 object.insert("legacyCause".to_owned(), Value::String(failure.message));
769 }
770 Self {
771 code: DEFAULT_CLIENT_ERROR_CODE.to_owned(),
772 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
773 details: Some(details),
774 retryable: false,
775 }
776 }
777 }
778 }
779}
780
781impl From<String> for ClientError {
782 fn from(message: String) -> Self {
787 if !message.contains(": ") && is_client_code(&message) {
789 return Self {
790 code: message.clone(),
791 message: static_authoring_message(&message)
792 .unwrap_or(GENERIC_AUTHORING_MESSAGE)
793 .to_owned(),
794 details: None,
795 retryable: false,
796 };
797 }
798 let (code, rest) = match message.split_once(": ") {
799 Some((code, rest)) if is_client_code(code) => (code, Some(rest)),
800 _ => (DEFAULT_CLIENT_ERROR_CODE, None),
801 };
802 match static_authoring_message(code) {
803 Some(fixed) => Self {
804 code: code.to_owned(),
805 message: fixed.to_owned(),
806 details: (rest != Some(fixed))
807 .then(|| serde_json::json!({ "legacyCause": message })),
808 retryable: false,
809 },
810 None => Self {
811 code: code.to_owned(),
812 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
813 details: Some(serde_json::json!({ "legacyCause": message })),
814 retryable: false,
815 },
816 }
817 }
818}
819
820#[derive(Debug, Clone, Serialize)]
821#[serde(rename_all = "camelCase")]
822pub struct QuerySnapshot {
823 pub revision: String,
824 pub rows: Vec<QueryRow>,
825 pub coverage: CoverageSnapshot,
826}
827
828impl WindowState {
829 #[must_use]
831 pub fn complete(&self, unit: &str) -> bool {
832 self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
833 }
834}
835
836#[derive(Debug, Clone)]
838pub enum Mutation {
839 Patch {
840 table: String,
841 values: Map<String, Value>,
842 base_version: Option<i64>,
843 },
844 Upsert {
845 table: String,
846 values: Map<String, Value>,
847 base_version: Option<i64>,
848 },
849 Delete {
850 table: String,
851 row_id: String,
852 base_version: Option<i64>,
853 },
854}
855
856#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
857#[serde(rename_all = "camelCase")]
858pub struct SchemaFloor {
859 #[serde(skip_serializing_if = "Option::is_none")]
860 pub required_schema_version: Option<i32>,
861 #[serde(skip_serializing_if = "Option::is_none")]
862 pub latest_schema_version: Option<i32>,
863}
864
865#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
869#[serde(rename_all = "camelCase")]
870pub struct LeaseState {
871 #[serde(skip_serializing_if = "Option::is_none")]
872 pub lease_id: Option<String>,
873 #[serde(skip_serializing_if = "Option::is_none")]
874 pub expires_at_ms: Option<i64>,
875 #[serde(skip_serializing_if = "Option::is_none")]
876 pub error_code: Option<String>,
877}
878
879#[derive(Debug, Clone, Serialize)]
881#[serde(rename_all = "camelCase")]
882pub struct PresencePeer {
883 pub actor_id: String,
884 pub client_id: String,
885 pub doc: serde_json::Value,
886}
887
888#[derive(Debug, Clone, Serialize, Default)]
889#[serde(rename_all = "camelCase")]
890pub struct SyncReport {
891 pub pushed: u32,
892 pub applied: Vec<String>,
893 pub rejected: Vec<String>,
894 pub retryable: Vec<String>,
895 pub conflicts: u32,
896 pub commits_applied: u32,
897 pub segment_rows_applied: u32,
898 pub bootstrapping: Vec<String>,
899 pub resets: Vec<String>,
900 pub revoked: Vec<String>,
901 pub failed: Vec<String>,
902 pub deferred_commits: usize,
903 #[serde(skip_serializing_if = "Option::is_none")]
904 pub schema_floor: Option<SchemaFloor>,
905}
906
907impl SyncReport {
908 pub fn merge(&mut self, report: &Self) {
913 self.pushed += report.pushed;
914 self.applied.extend(report.applied.iter().cloned());
915 self.rejected.extend(report.rejected.iter().cloned());
916 self.retryable.extend(report.retryable.iter().cloned());
917 self.conflicts += report.conflicts;
918 self.commits_applied += report.commits_applied;
919 self.segment_rows_applied += report.segment_rows_applied;
920 self.bootstrapping = report.bootstrapping.clone();
921 self.resets.extend(report.resets.iter().cloned());
922 self.revoked.extend(report.revoked.iter().cloned());
923 self.failed.extend(report.failed.iter().cloned());
924 self.deferred_commits = report.deferred_commits;
925 self.schema_floor = report.schema_floor.clone();
926 }
927}
928
929#[derive(Debug, Clone)]
932pub enum SyncOutcome {
933 Ok(SyncReport),
934 Failed {
935 error_code: String,
936 message: String,
937 details: Option<Value>,
938 recommended_action: Option<String>,
942 },
943 RealtimeUnavailable {
948 state: RealtimeState,
949 reason_code: Option<String>,
950 retry_delay_ms: u64,
951 },
952 BudgetExhausted(SyncReport),
956}
957
958impl SyncOutcome {
959 pub fn to_json(&self) -> Value {
960 match self {
961 SyncOutcome::Ok(report) => {
962 let mut map = Map::new();
963 map.insert("ok".to_owned(), Value::Bool(true));
964 map.insert(
965 "report".to_owned(),
966 serde_json::to_value(report).expect("report serializes"),
967 );
968 Value::Object(map)
969 }
970 SyncOutcome::Failed {
971 error_code,
972 message,
973 details,
974 recommended_action,
975 } => {
976 let mut map = Map::new();
977 map.insert("ok".to_owned(), Value::Bool(false));
978 map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
979 map.insert("message".to_owned(), Value::from(message.clone()));
980 if let Some(details) = details {
981 map.insert("details".to_owned(), details.clone());
982 }
983 if let Some(recommended_action) = recommended_action {
984 map.insert(
985 "recommendedAction".to_owned(),
986 Value::from(recommended_action.clone()),
987 );
988 }
989 Value::Object(map)
990 }
991 SyncOutcome::RealtimeUnavailable {
992 state,
993 reason_code,
994 retry_delay_ms,
995 } => {
996 let mut map = Map::new();
997 map.insert("ok".to_owned(), Value::Bool(false));
998 map.insert(
999 "errorCode".to_owned(),
1000 Value::from(REALTIME_UNAVAILABLE_CODE),
1001 );
1002 map.insert(
1003 "message".to_owned(),
1004 Value::from("realtime is required and the realtime socket is not connected"),
1005 );
1006 map.insert(
1007 "realtimeState".to_owned(),
1008 serde_json::to_value(state).expect("state serializes"),
1009 );
1010 if let Some(reason_code) = reason_code {
1011 map.insert(
1012 "realtimeReasonCode".to_owned(),
1013 Value::from(reason_code.clone()),
1014 );
1015 }
1016 map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
1017 Value::Object(map)
1018 }
1019 SyncOutcome::BudgetExhausted(report) => {
1020 let mut map = Map::new();
1021 map.insert("ok".to_owned(), Value::Bool(true));
1022 map.insert("budgetExhausted".to_owned(), Value::Bool(true));
1023 map.insert(
1024 "report".to_owned(),
1025 serde_json::to_value(report).expect("report serializes"),
1026 );
1027 Value::Object(map)
1028 }
1029 }
1030 }
1031}
1032
1033#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1034#[serde(rename_all = "camelCase")]
1035pub struct ConflictRecord {
1036 pub client_commit_id: String,
1037 pub op_index: i32,
1038 pub table: String,
1039 pub row_id: String,
1040 pub code: String,
1041 pub message: String,
1042 pub server_version: i64,
1043 pub server_row: Map<String, Value>,
1046 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1051 pub conflict_columns: Vec<String>,
1052 #[serde(skip_serializing_if = "Option::is_none")]
1053 pub operation: Option<CommitOperation>,
1054}
1055
1056#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1059#[serde(rename_all = "camelCase", deny_unknown_fields)]
1060pub struct RejectionDetails {
1061 #[serde(skip_serializing_if = "Option::is_none")]
1062 pub field_paths: Option<Vec<String>>,
1063 #[serde(skip_serializing_if = "Option::is_none")]
1064 pub reason: Option<String>,
1065 #[serde(skip_serializing_if = "Option::is_none")]
1066 pub required_action: Option<String>,
1067 #[serde(skip_serializing_if = "Option::is_none")]
1068 pub references: Option<BTreeMap<String, String>>,
1069}
1070
1071impl RejectionDetails {
1072 pub(crate) fn parse(raw: &str) -> Result<Self, String> {
1073 if raw.len() > 4_096 {
1074 return Err("rejection details exceed 4096 encoded bytes".to_owned());
1075 }
1076 let details: Self = serde_json::from_str(raw)
1077 .map_err(|error| format!("invalid rejection details: {error}"))?;
1078 details.validate()?;
1079 Ok(details)
1080 }
1081
1082 fn validate(&self) -> Result<(), String> {
1083 let mut members = 0;
1084 if let Some(paths) = &self.field_paths {
1085 members += 1;
1086 if paths.is_empty() || paths.len() > 32 {
1087 return Err("fieldPaths must contain 1-32 paths".to_owned());
1088 }
1089 let mut seen = std::collections::BTreeSet::new();
1090 for path in paths {
1091 if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
1092 {
1093 return Err("fieldPaths contains an invalid or duplicate path".to_owned());
1094 }
1095 }
1096 }
1097 if let Some(reason) = &self.reason {
1098 members += 1;
1099 if !valid_token(reason, 96) {
1100 return Err("reason must be a lowercase stable token".to_owned());
1101 }
1102 }
1103 if let Some(action) = &self.required_action {
1104 members += 1;
1105 if !valid_token(action, 96) {
1106 return Err("requiredAction must be a lowercase stable token".to_owned());
1107 }
1108 }
1109 if let Some(references) = &self.references {
1110 members += 1;
1111 if references.is_empty() || references.len() > 16 {
1112 return Err("references must contain 1-16 entries".to_owned());
1113 }
1114 for (key, value) in references {
1115 if !valid_token(key, 64)
1116 || value.is_empty()
1117 || value.len() > 256
1118 || value.trim() != value
1119 || value.chars().any(char::is_control)
1120 {
1121 return Err("references contains an invalid key or value".to_owned());
1122 }
1123 }
1124 }
1125 if members == 0 {
1126 return Err("rejection details must not be empty".to_owned());
1127 }
1128 Ok(())
1129 }
1130}
1131
1132fn valid_identifier(segment: &str) -> bool {
1133 let mut chars = segment.chars();
1134 matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
1135 && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1136}
1137
1138fn valid_token(token: &str, max: usize) -> bool {
1139 if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
1140 {
1141 return false;
1142 }
1143 let mut previous_separator = false;
1144 for character in token.chars() {
1145 if character.is_ascii_lowercase() || character.is_ascii_digit() {
1146 previous_separator = false;
1147 } else if matches!(character, '.' | '_' | '-') && !previous_separator {
1148 previous_separator = true;
1149 } else {
1150 return false;
1151 }
1152 }
1153 !previous_separator
1154}
1155
1156#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1157#[serde(rename_all = "camelCase")]
1158pub struct RejectionRecord {
1159 pub client_commit_id: String,
1160 pub op_index: i32,
1161 pub code: String,
1162 pub message: String,
1163 pub retryable: bool,
1164 #[serde(skip_serializing_if = "Option::is_none")]
1165 pub details: Option<RejectionDetails>,
1166 #[serde(skip_serializing_if = "Option::is_none")]
1167 pub operation: Option<CommitOperation>,
1168}
1169
1170#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1172#[serde(rename_all = "camelCase")]
1173pub struct CommitOperation {
1174 pub table: String,
1175 pub row_id: String,
1176 pub op: String,
1177 #[serde(skip_serializing_if = "Option::is_none")]
1178 pub base_version: Option<i64>,
1179 #[serde(skip_serializing_if = "Option::is_none")]
1180 pub values: Option<Map<String, Value>>,
1181 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1183 pub insert: bool,
1184}
1185
1186#[derive(Debug, Clone, Serialize, PartialEq)]
1189#[serde(rename_all = "camelCase")]
1190pub struct PendingCommit {
1191 pub seq: i64,
1193 pub client_commit_id: String,
1194 pub created_at_ms: i64,
1196 pub operations: Vec<CommitOperation>,
1197}
1198
1199#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1200#[serde(rename_all = "snake_case")]
1201pub enum CommitOutcomeStatus {
1202 Applied,
1203 Cached,
1204 Conflict,
1205 Rejected,
1206}
1207
1208#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1209#[serde(rename_all = "snake_case")]
1210pub enum CommitOutcomeResolution {
1211 Active,
1212 ResolvedKeepServer,
1213 Superseded,
1214 Dismissed,
1215}
1216
1217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1218#[serde(tag = "status", rename_all = "snake_case")]
1219pub enum CommitOperationOutcome {
1220 Applied {
1221 #[serde(rename = "opIndex")]
1222 op_index: i32,
1223 },
1224 Conflict {
1225 conflict: ConflictRecord,
1226 },
1227 Error {
1228 rejection: RejectionRecord,
1229 },
1230}
1231
1232#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1233#[serde(rename_all = "camelCase")]
1234pub struct RetainedUniqueConflict {
1235 pub index: String,
1236 pub columns: Vec<String>,
1237 pub row_id: String,
1238 pub server_row: Map<String, Value>,
1239 pub server_version: i64,
1240}
1241
1242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1243#[serde(rename_all = "camelCase")]
1244pub struct RetainedCommitRow {
1245 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1246 pub unique_conflicts: Vec<RetainedUniqueConflict>,
1247 pub table: String,
1248 pub row_id: String,
1249 pub local_row: Option<Map<String, Value>>,
1250 pub server_row: Option<Map<String, Value>>,
1252 pub server_version: Option<i64>,
1253}
1254
1255#[derive(Debug, Clone, Serialize, PartialEq)]
1257#[serde(rename_all = "camelCase")]
1258pub struct CurrentBaseProof {
1259 pub proven: bool,
1260 #[serde(skip_serializing_if = "Option::is_none")]
1261 pub rows: Option<Vec<RetainedCommitRow>>,
1262 #[serde(skip_serializing_if = "Option::is_none")]
1263 pub reason: Option<CurrentBaseProofReason>,
1264}
1265
1266#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1267#[serde(rename_all = "snake_case")]
1268pub enum CurrentBaseProofReason {
1269 Offline,
1270 SyncFailed,
1271 SchemaFloor,
1272 BudgetExhausted,
1273 SnapshotFailed,
1274 MissingCoverage,
1275 Revoked,
1276 OutcomeUnavailable,
1277}
1278
1279impl CurrentBaseProof {
1280 pub fn failure(reason: CurrentBaseProofReason) -> Self {
1281 Self {
1282 proven: false,
1283 rows: None,
1284 reason: Some(reason),
1285 }
1286 }
1287}
1288
1289#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1290#[serde(rename_all = "camelCase")]
1291pub struct CommitOutcome {
1292 pub sequence: i64,
1293 pub client_commit_id: String,
1294 pub status: CommitOutcomeStatus,
1295 pub recorded_at_ms: i64,
1296 pub results: Vec<CommitOperationOutcome>,
1297 #[serde(skip_serializing_if = "Option::is_none")]
1300 pub operations: Option<Vec<CommitOperation>>,
1301 #[serde(skip_serializing_if = "Option::is_none")]
1302 pub retained_rows: Option<Vec<RetainedCommitRow>>,
1303 pub resolution: CommitOutcomeResolution,
1304 #[serde(skip_serializing_if = "Option::is_none")]
1305 pub resolved_at_ms: Option<i64>,
1306 #[serde(skip_serializing_if = "Option::is_none")]
1307 pub replacement_client_commit_id: Option<String>,
1308}
1309
1310#[derive(Debug, Clone, Deserialize, Default)]
1311#[serde(rename_all = "camelCase")]
1312pub struct CommitOutcomeQuery {
1313 pub limit: Option<usize>,
1314 #[serde(default)]
1315 pub active_only: bool,
1316}
1317
1318#[derive(Debug, Clone, Serialize)]
1322#[serde(
1323 tag = "state",
1324 rename_all = "camelCase",
1325 rename_all_fields = "camelCase"
1326)]
1327pub enum UnitCatchup {
1328 Unknown {
1329 id: String,
1330 },
1331 Known {
1332 id: String,
1333 status: UnitStatus,
1334 live: bool,
1335 cursor: i64,
1337 has_resume_token: bool,
1338 bootstrap_complete: bool,
1340 known_pending_pages: bool,
1342 #[serde(skip_serializing_if = "Option::is_none")]
1343 reason_code: Option<String>,
1344 },
1345}
1346
1347#[derive(Debug, Clone, Serialize)]
1355#[serde(tag = "status", rename_all = "snake_case")]
1356pub enum CommitDelivery {
1357 Pending {
1358 #[serde(rename = "clientCommitId")]
1359 client_commit_id: String,
1360 },
1361 Known {
1362 #[serde(rename = "clientCommitId")]
1363 client_commit_id: String,
1364 outcome: CommitOutcome,
1365 },
1366 Unknown {
1367 #[serde(rename = "clientCommitId")]
1368 client_commit_id: String,
1369 },
1370}
1371
1372#[derive(Debug, Clone, Serialize)]
1377#[serde(rename_all = "camelCase")]
1378pub struct SnapshotRead {
1379 pub revision: String,
1380 pub queries: Vec<Vec<QueryRow>>,
1381 pub coverage: CoverageSnapshot,
1382 pub units: Vec<UnitCatchup>,
1383 pub deliveries: Vec<CommitDelivery>,
1384}
1385
1386#[derive(Debug, Clone, Deserialize)]
1387#[serde(rename_all = "camelCase")]
1388pub struct ResolveCommitOutcomeInput {
1389 pub client_commit_id: String,
1390 pub resolution: CommitOutcomeResolution,
1391 pub replacement_client_commit_id: Option<String>,
1392}
1393
1394#[derive(Debug, Clone, Serialize)]
1395#[serde(rename_all = "camelCase")]
1396pub struct RowState {
1397 pub row_id: String,
1398 pub version: i64,
1401 pub values: Map<String, Value>,
1402 #[serde(skip_serializing_if = "Option::is_none")]
1404 pub sealed_key: Option<String>,
1405}
1406
1407#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1411#[serde(rename_all = "camelCase", deny_unknown_fields)]
1412pub struct LocalDataPurgeTarget {
1413 pub table: String,
1414 pub selectors: BTreeMap<String, Vec<String>>,
1415}
1416
1417#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1420#[serde(rename_all = "camelCase", deny_unknown_fields)]
1421pub struct LocalDataPurgeInput {
1422 pub purge_id: String,
1423 pub targets: Vec<LocalDataPurgeTarget>,
1424}
1425
1426#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1428#[serde(rename_all = "camelCase")]
1429pub struct LocalDataPurgeResult {
1430 pub already_applied: bool,
1431 pub purged_rows: usize,
1432 pub dropped_commits: usize,
1433}
1434
1435#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1437#[serde(rename_all = "camelCase", deny_unknown_fields)]
1438pub struct LocalDataRebootstrapInput {
1439 pub rebootstrap_id: String,
1440}
1441
1442#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1444#[serde(rename_all = "camelCase")]
1445pub struct LocalDataRebootstrapResult {
1446 pub already_applied: bool,
1447 pub retained_commits: usize,
1448 pub reset_subscriptions: usize,
1449}
1450
1451#[derive(Debug, Clone, Default)]
1453pub struct ClientLimits {
1454 pub limit_commits: Option<i32>,
1455 pub limit_snapshot_rows: Option<i32>,
1456 pub max_snapshot_pages: Option<i32>,
1457 pub accept: Option<u8>,
1460 pub blob_cache_max_bytes: Option<i64>,
1465 pub outcome_retention_max_entries: Option<usize>,
1468 pub max_push_commits_per_request: Option<usize>,
1470 pub max_push_operations_per_request: Option<usize>,
1475 pub max_push_request_bytes: Option<usize>,
1481 pub previous_version_context: Option<PreviousVersionContextConfig>,
1485 pub authority_reads: Vec<AuthorityReadDeclaration>,
1487}
1488
1489#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
1491#[serde(rename_all = "camelCase", deny_unknown_fields)]
1492pub struct AuthorityReadDeclaration {
1493 pub table: String,
1494 pub columns: Vec<String>,
1495 pub scopes: std::collections::BTreeMap<String, Vec<String>>,
1496}