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