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 #[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; 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 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 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 pub previous_version_context: PreviousVersionStatus,
264 pub security_lifecycle: &'static str,
267}
268
269#[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
281pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
284pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
287pub 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#[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 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#[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 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#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
409#[serde(rename_all = "camelCase")]
410pub struct DiagnosticQueryFailure {
411 pub id: String,
412 pub tables: Vec<String>,
414 pub code: String,
416 #[serde(skip_serializing_if = "Option::is_none")]
418 pub sqlite_code: Option<i32>,
419 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 pub active_units: usize,
437 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
490pub enum TransportGate {
491 Closed,
492 Pull,
493 #[default]
494 Open,
495}
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
502#[serde(rename_all = "lowercase")]
503pub enum RealtimeState {
504 Connected,
505 Connecting,
506 #[default]
507 Disconnected,
508 Lost,
509 Refused,
510 Disabled,
511}
512
513#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
514#[serde(rename_all = "camelCase")]
515pub struct ClientDiagnosticsLease {
516 pub state: String,
517 #[serde(skip_serializing_if = "Option::is_none")]
518 pub expires_at_ms: Option<i64>,
519 #[serde(skip_serializing_if = "Option::is_none")]
520 pub error_code: Option<String>,
521}
522
523#[derive(Debug, Clone, Serialize)]
525#[serde(rename_all = "camelCase")]
526pub struct AppliedServerCommit {
527 pub table: String,
528 pub commit_seq: i64,
529 pub source: AppliedServerCommitSource,
530}
531
532#[derive(Debug, Clone, Copy, Serialize)]
533#[serde(rename_all = "camelCase")]
534pub enum AppliedServerCommitSource {
535 Delta,
536 Pull,
537}
538
539#[derive(Debug, Clone, Serialize)]
540#[serde(rename_all = "camelCase")]
541pub struct ClientChangeBatch {
542 pub revision: String,
543 pub tables: Vec<TableChange>,
544 pub windows: Vec<WindowChange>,
545 #[serde(skip_serializing_if = "Option::is_none")]
546 pub status: Option<SyncStatusSnapshot>,
547 pub conflicts_changed: bool,
548 pub rejections_changed: bool,
549 pub outcomes_changed: bool,
550 #[serde(skip_serializing_if = "Vec::is_empty")]
551 pub applied_commits: Vec<AppliedServerCommit>,
552}
553
554#[derive(Debug, Clone, Serialize)]
555#[serde(tag = "kind", rename_all = "camelCase")]
556pub enum SyncIntent {
557 None,
558 Interactive,
559 Background {
560 #[serde(rename = "delayMs")]
561 delay_ms: u64,
562 },
563}
564
565#[derive(Debug, Clone, Serialize)]
566pub struct CommandEffects {
567 pub sync: SyncIntent,
568}
569
570impl CommandEffects {
571 #[must_use]
572 pub fn none() -> Self {
573 Self {
574 sync: SyncIntent::None,
575 }
576 }
577
578 #[must_use]
579 pub fn interactive() -> Self {
580 Self {
581 sync: SyncIntent::Interactive,
582 }
583 }
584}
585
586#[derive(Debug, Clone)]
587pub struct WindowCoverage {
588 pub table: String,
591 pub base: WindowBase,
592 pub units: Vec<String>,
593}
594
595#[derive(Debug, Clone, Serialize)]
596#[serde(rename_all = "camelCase")]
597pub struct WindowUnitRef {
598 pub base_key: String,
599 pub unit: String,
600}
601
602#[derive(Debug, Clone, Serialize)]
603#[serde(rename_all = "camelCase")]
604pub struct CoverageSnapshot {
605 pub complete: bool,
606 pub pending: Vec<WindowUnitRef>,
607 pub missing: Vec<WindowUnitRef>,
608 pub revoked: Vec<WindowUnitRef>,
610}
611
612#[derive(Debug, Clone, Copy)]
615pub struct QueryOwner<'a> {
616 pub id: &'a str,
617 pub tables: &'a [&'a str],
618}
619
620#[derive(Debug, Clone, PartialEq, Eq)]
625pub struct QueryReadFailure {
626 pub code: Option<&'static str>,
627 pub sqlite_code: Option<i32>,
628 pub sqlite_message: Option<String>,
629 pub rollback_failure: Option<Box<QueryReadFailure>>,
630 pub message: String,
631}
632
633impl std::fmt::Display for QueryReadFailure {
634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635 match self.code {
636 Some(code) => write!(f, "{code}: {}", self.message),
637 None => f.write_str(&self.message),
638 }
639 }
640}
641
642impl From<String> for QueryReadFailure {
643 fn from(message: String) -> Self {
644 Self {
645 code: None,
646 sqlite_code: None,
647 sqlite_message: None,
648 rollback_failure: None,
649 message,
650 }
651 }
652}
653
654impl From<rusqlite::Error> for QueryReadFailure {
655 fn from(error: rusqlite::Error) -> Self {
657 let sqlite_code = match &error {
658 rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
659 _ => None,
660 };
661 match sqlite_code.map(|code| code & 0xff) {
662 Some(11 | 26) => Self {
663 code: Some("client.storage_corrupt"),
664 sqlite_code,
665 sqlite_message: Some(error.to_string()),
666 rollback_failure: None,
667 message: "local SQLite storage is corrupt".to_owned(),
668 },
669 Some(13) => Self {
670 code: Some("client.storage_full"),
671 sqlite_code,
672 sqlite_message: Some(error.to_string()),
673 rollback_failure: None,
674 message: "local SQLite storage is full".to_owned(),
675 },
676 Some(10) => Self {
677 code: Some("client.storage_io"),
678 sqlite_code,
679 sqlite_message: Some(error.to_string()),
680 rollback_failure: None,
681 message: "local SQLite storage I/O failed".to_owned(),
682 },
683 Some(5 | 6) => Self {
687 code: Some("client.storage_busy"),
688 sqlite_code,
689 sqlite_message: Some(error.to_string()),
690 rollback_failure: None,
691 message: "local SQLite storage is busy".to_owned(),
692 },
693 _ => Self {
694 code: None,
695 sqlite_code,
696 sqlite_message: Some(error.to_string()),
697 rollback_failure: None,
698 message: error.to_string(),
699 },
700 }
701 }
702}
703
704impl QueryReadFailure {
705 pub fn retryable(&self) -> bool {
708 self.code == Some("client.storage_busy")
709 }
710
711 pub fn details(&self) -> Option<Value> {
712 self.sqlite_code.map(|code| {
713 let mut details =
714 serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
715 if let Some(rollback) = &self.rollback_failure {
716 details["rollbackFailure"] = serde_json::json!({
717 "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
718 });
719 }
720 details
721 })
722 }
723}
724
725#[derive(Debug, Clone, PartialEq, Eq)]
732pub struct ClientError {
733 pub code: String,
734 pub message: String,
735 pub details: Option<Value>,
736 pub retryable: bool,
737}
738
739const DEFAULT_CLIENT_ERROR_CODE: &str = "client.failed";
741
742const GENERIC_AUTHORING_MESSAGE: &str = "the local authoring operation failed";
744
745fn static_authoring_message(code: &str) -> Option<&'static str> {
748 match code {
749 "sync.unknown_table" => Some("the commit targets an unknown table"),
750 "sync.invalid_request" => Some("the authoring request is invalid"),
751 "sync.row_missing" => Some("a sparse patch requires a local row"),
752 "sync.constraint_violation" => Some("local write violates a unique constraint"),
753 DEFAULT_CLIENT_ERROR_CODE => Some(GENERIC_AUTHORING_MESSAGE),
754 _ => None,
755 }
756}
757
758fn is_client_code(candidate: &str) -> bool {
759 candidate.starts_with("client.") || candidate.starts_with("sync.")
760}
761
762impl std::fmt::Display for ClientError {
763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
764 write!(f, "{}: {}", self.code, self.message)
765 }
766}
767
768impl std::error::Error for ClientError {}
769
770impl From<QueryReadFailure> for ClientError {
771 fn from(failure: QueryReadFailure) -> Self {
772 match failure.code {
773 Some(code) => {
775 let details = failure.details();
776 let retryable = failure.retryable();
777 Self {
778 code: code.to_owned(),
779 message: failure.message,
780 details,
781 retryable,
782 }
783 }
784 None => {
785 let mut details = failure.details().unwrap_or_else(|| serde_json::json!({}));
786 if let Some(object) = details.as_object_mut() {
787 object.insert("legacyCause".to_owned(), Value::String(failure.message));
788 }
789 Self {
790 code: DEFAULT_CLIENT_ERROR_CODE.to_owned(),
791 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
792 details: Some(details),
793 retryable: false,
794 }
795 }
796 }
797 }
798}
799
800impl From<String> for ClientError {
801 fn from(message: String) -> Self {
806 if !message.contains(": ") && is_client_code(&message) {
808 return Self {
809 code: message.clone(),
810 message: static_authoring_message(&message)
811 .unwrap_or(GENERIC_AUTHORING_MESSAGE)
812 .to_owned(),
813 details: None,
814 retryable: false,
815 };
816 }
817 let (code, rest) = match message.split_once(": ") {
818 Some((code, rest)) if is_client_code(code) => (code, Some(rest)),
819 _ => (DEFAULT_CLIENT_ERROR_CODE, None),
820 };
821 match static_authoring_message(code) {
822 Some(fixed) => Self {
823 code: code.to_owned(),
824 message: fixed.to_owned(),
825 details: (rest != Some(fixed))
826 .then(|| serde_json::json!({ "legacyCause": message })),
827 retryable: false,
828 },
829 None => Self {
830 code: code.to_owned(),
831 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
832 details: Some(serde_json::json!({ "legacyCause": message })),
833 retryable: false,
834 },
835 }
836 }
837}
838
839#[derive(Debug, Clone, Serialize)]
840#[serde(rename_all = "camelCase")]
841pub struct QuerySnapshot {
842 pub revision: String,
843 pub rows: Vec<QueryRow>,
844 pub coverage: CoverageSnapshot,
845}
846
847impl WindowState {
848 #[must_use]
850 pub fn complete(&self, unit: &str) -> bool {
851 self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
852 }
853}
854
855#[derive(Debug, Clone)]
857pub enum Mutation {
858 Patch {
859 table: String,
860 values: Map<String, Value>,
861 base_version: Option<i64>,
862 },
863 Upsert {
864 table: String,
865 values: Map<String, Value>,
866 base_version: Option<i64>,
867 },
868 Delete {
869 table: String,
870 row_id: String,
871 base_version: Option<i64>,
872 },
873}
874
875#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
876#[serde(rename_all = "camelCase")]
877pub struct SchemaFloor {
878 #[serde(skip_serializing_if = "Option::is_none")]
879 pub required_schema_version: Option<i32>,
880 #[serde(skip_serializing_if = "Option::is_none")]
881 pub latest_schema_version: Option<i32>,
882}
883
884#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
888#[serde(rename_all = "camelCase")]
889pub struct LeaseState {
890 #[serde(skip_serializing_if = "Option::is_none")]
891 pub lease_id: Option<String>,
892 #[serde(skip_serializing_if = "Option::is_none")]
893 pub expires_at_ms: Option<i64>,
894 #[serde(skip_serializing_if = "Option::is_none")]
895 pub error_code: Option<String>,
896}
897
898#[derive(Debug, Clone, Serialize)]
900#[serde(rename_all = "camelCase")]
901pub struct PresencePeer {
902 pub actor_id: String,
903 pub client_id: String,
904 pub doc: serde_json::Value,
905}
906
907#[derive(Debug, Clone, Serialize, Default)]
908#[serde(rename_all = "camelCase")]
909pub struct SyncReport {
910 pub pushed: u32,
911 pub applied: Vec<String>,
912 pub rejected: Vec<String>,
913 pub retryable: Vec<String>,
914 pub conflicts: u32,
915 pub commits_applied: u32,
916 pub segment_rows_applied: u32,
917 pub bootstrapping: Vec<String>,
918 pub resets: Vec<String>,
919 pub revoked: Vec<String>,
920 pub failed: Vec<String>,
921 pub deferred_commits: usize,
922 #[serde(skip_serializing_if = "Option::is_none")]
923 pub schema_floor: Option<SchemaFloor>,
924}
925
926impl SyncReport {
927 pub fn merge(&mut self, report: &Self) {
932 self.pushed += report.pushed;
933 self.applied.extend(report.applied.iter().cloned());
934 self.rejected.extend(report.rejected.iter().cloned());
935 self.retryable.extend(report.retryable.iter().cloned());
936 self.conflicts += report.conflicts;
937 self.commits_applied += report.commits_applied;
938 self.segment_rows_applied += report.segment_rows_applied;
939 self.bootstrapping = report.bootstrapping.clone();
940 self.resets.extend(report.resets.iter().cloned());
941 self.revoked.extend(report.revoked.iter().cloned());
942 self.failed.extend(report.failed.iter().cloned());
943 self.deferred_commits = report.deferred_commits;
944 self.schema_floor = report.schema_floor.clone();
945 }
946}
947
948#[derive(Debug, Clone)]
951pub enum SyncOutcome {
952 Ok(SyncReport),
953 Failed {
954 error_code: String,
955 message: String,
956 details: Option<Value>,
957 recommended_action: Option<String>,
961 },
962 RealtimeUnavailable {
967 state: RealtimeState,
968 reason_code: Option<String>,
969 retry_delay_ms: u64,
970 },
971 BudgetExhausted(SyncReport),
975}
976
977impl SyncOutcome {
978 pub fn to_json(&self) -> Value {
979 match self {
980 SyncOutcome::Ok(report) => {
981 let mut map = Map::new();
982 map.insert("ok".to_owned(), Value::Bool(true));
983 map.insert(
984 "report".to_owned(),
985 serde_json::to_value(report).expect("report serializes"),
986 );
987 Value::Object(map)
988 }
989 SyncOutcome::Failed {
990 error_code,
991 message,
992 details,
993 recommended_action,
994 } => {
995 let mut map = Map::new();
996 map.insert("ok".to_owned(), Value::Bool(false));
997 map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
998 map.insert("message".to_owned(), Value::from(message.clone()));
999 if let Some(details) = details {
1000 map.insert("details".to_owned(), details.clone());
1001 }
1002 if let Some(recommended_action) = recommended_action {
1003 map.insert(
1004 "recommendedAction".to_owned(),
1005 Value::from(recommended_action.clone()),
1006 );
1007 }
1008 Value::Object(map)
1009 }
1010 SyncOutcome::RealtimeUnavailable {
1011 state,
1012 reason_code,
1013 retry_delay_ms,
1014 } => {
1015 let mut map = Map::new();
1016 map.insert("ok".to_owned(), Value::Bool(false));
1017 map.insert(
1018 "errorCode".to_owned(),
1019 Value::from(REALTIME_UNAVAILABLE_CODE),
1020 );
1021 map.insert(
1022 "message".to_owned(),
1023 Value::from("realtime is required and the realtime socket is not connected"),
1024 );
1025 map.insert(
1026 "realtimeState".to_owned(),
1027 serde_json::to_value(state).expect("state serializes"),
1028 );
1029 if let Some(reason_code) = reason_code {
1030 map.insert(
1031 "realtimeReasonCode".to_owned(),
1032 Value::from(reason_code.clone()),
1033 );
1034 }
1035 map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
1036 Value::Object(map)
1037 }
1038 SyncOutcome::BudgetExhausted(report) => {
1039 let mut map = Map::new();
1040 map.insert("ok".to_owned(), Value::Bool(true));
1041 map.insert("budgetExhausted".to_owned(), Value::Bool(true));
1042 map.insert(
1043 "report".to_owned(),
1044 serde_json::to_value(report).expect("report serializes"),
1045 );
1046 Value::Object(map)
1047 }
1048 }
1049 }
1050}
1051
1052#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1053#[serde(rename_all = "camelCase")]
1054pub struct ConflictRecord {
1055 pub client_commit_id: String,
1056 pub op_index: i32,
1057 pub table: String,
1058 pub row_id: String,
1059 pub code: String,
1060 pub message: String,
1061 pub server_version: i64,
1062 pub server_row: Map<String, Value>,
1065 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1070 pub conflict_columns: Vec<String>,
1071 #[serde(skip_serializing_if = "Option::is_none")]
1072 pub operation: Option<CommitOperation>,
1073}
1074
1075#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1078#[serde(rename_all = "camelCase", deny_unknown_fields)]
1079pub struct RejectionDetails {
1080 #[serde(skip_serializing_if = "Option::is_none")]
1081 pub field_paths: Option<Vec<String>>,
1082 #[serde(skip_serializing_if = "Option::is_none")]
1083 pub reason: Option<String>,
1084 #[serde(skip_serializing_if = "Option::is_none")]
1085 pub required_action: Option<String>,
1086 #[serde(skip_serializing_if = "Option::is_none")]
1087 pub references: Option<BTreeMap<String, String>>,
1088}
1089
1090impl RejectionDetails {
1091 pub(crate) fn parse(raw: &str) -> Result<Self, String> {
1092 if raw.len() > 4_096 {
1093 return Err("rejection details exceed 4096 encoded bytes".to_owned());
1094 }
1095 let details: Self = serde_json::from_str(raw)
1096 .map_err(|error| format!("invalid rejection details: {error}"))?;
1097 details.validate()?;
1098 Ok(details)
1099 }
1100
1101 fn validate(&self) -> Result<(), String> {
1102 let mut members = 0;
1103 if let Some(paths) = &self.field_paths {
1104 members += 1;
1105 if paths.is_empty() || paths.len() > 32 {
1106 return Err("fieldPaths must contain 1-32 paths".to_owned());
1107 }
1108 let mut seen = std::collections::BTreeSet::new();
1109 for path in paths {
1110 if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
1111 {
1112 return Err("fieldPaths contains an invalid or duplicate path".to_owned());
1113 }
1114 }
1115 }
1116 if let Some(reason) = &self.reason {
1117 members += 1;
1118 if !valid_token(reason, 96) {
1119 return Err("reason must be a lowercase stable token".to_owned());
1120 }
1121 }
1122 if let Some(action) = &self.required_action {
1123 members += 1;
1124 if !valid_token(action, 96) {
1125 return Err("requiredAction must be a lowercase stable token".to_owned());
1126 }
1127 }
1128 if let Some(references) = &self.references {
1129 members += 1;
1130 if references.is_empty() || references.len() > 16 {
1131 return Err("references must contain 1-16 entries".to_owned());
1132 }
1133 for (key, value) in references {
1134 if !valid_token(key, 64)
1135 || value.is_empty()
1136 || value.len() > 256
1137 || value.trim() != value
1138 || value.chars().any(char::is_control)
1139 {
1140 return Err("references contains an invalid key or value".to_owned());
1141 }
1142 }
1143 }
1144 if members == 0 {
1145 return Err("rejection details must not be empty".to_owned());
1146 }
1147 Ok(())
1148 }
1149}
1150
1151fn valid_identifier(segment: &str) -> bool {
1152 let mut chars = segment.chars();
1153 matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
1154 && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1155}
1156
1157fn valid_token(token: &str, max: usize) -> bool {
1158 if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
1159 {
1160 return false;
1161 }
1162 let mut previous_separator = false;
1163 for character in token.chars() {
1164 if character.is_ascii_lowercase() || character.is_ascii_digit() {
1165 previous_separator = false;
1166 } else if matches!(character, '.' | '_' | '-') && !previous_separator {
1167 previous_separator = true;
1168 } else {
1169 return false;
1170 }
1171 }
1172 !previous_separator
1173}
1174
1175#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1176#[serde(rename_all = "camelCase")]
1177pub struct RejectionRecord {
1178 pub client_commit_id: String,
1179 pub op_index: i32,
1180 pub code: String,
1181 pub message: String,
1182 pub retryable: bool,
1183 #[serde(skip_serializing_if = "Option::is_none")]
1184 pub details: Option<RejectionDetails>,
1185 #[serde(skip_serializing_if = "Option::is_none")]
1186 pub operation: Option<CommitOperation>,
1187}
1188
1189#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1191#[serde(rename_all = "camelCase")]
1192pub struct CommitOperation {
1193 pub table: String,
1194 pub row_id: String,
1195 pub op: String,
1196 #[serde(skip_serializing_if = "Option::is_none")]
1197 pub base_version: Option<i64>,
1198 #[serde(skip_serializing_if = "Option::is_none")]
1199 pub values: Option<Map<String, Value>>,
1200 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1202 pub insert: bool,
1203}
1204
1205#[derive(Debug, Clone, Serialize, PartialEq)]
1208#[serde(rename_all = "camelCase")]
1209pub struct PendingCommit {
1210 pub seq: i64,
1212 pub client_commit_id: String,
1213 pub created_at_ms: i64,
1215 pub operations: Vec<CommitOperation>,
1216}
1217
1218#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1219#[serde(rename_all = "snake_case")]
1220pub enum CommitOutcomeStatus {
1221 Applied,
1222 Cached,
1223 Conflict,
1224 Rejected,
1225 Replaced,
1230}
1231
1232#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1233#[serde(rename_all = "snake_case")]
1234pub enum CommitOutcomeResolution {
1235 Active,
1236 ResolvedKeepServer,
1237 Superseded,
1238 Dismissed,
1239}
1240
1241#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1242#[serde(tag = "status", rename_all = "snake_case")]
1243pub enum CommitOperationOutcome {
1244 Applied {
1245 #[serde(rename = "opIndex")]
1246 op_index: i32,
1247 },
1248 Conflict {
1249 conflict: ConflictRecord,
1250 },
1251 Error {
1252 rejection: RejectionRecord,
1253 },
1254}
1255
1256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1257#[serde(rename_all = "camelCase")]
1258pub struct RetainedUniqueConflict {
1259 pub index: String,
1260 pub columns: Vec<String>,
1261 pub row_id: String,
1262 pub server_row: Map<String, Value>,
1263 pub server_version: i64,
1264}
1265
1266#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1267#[serde(rename_all = "camelCase")]
1268pub struct RetainedCommitRow {
1269 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1270 pub unique_conflicts: Vec<RetainedUniqueConflict>,
1271 pub table: String,
1272 pub row_id: String,
1273 pub local_row: Option<Map<String, Value>>,
1274 pub server_row: Option<Map<String, Value>>,
1276 pub server_version: Option<i64>,
1277}
1278
1279#[derive(Debug, Clone, Serialize, PartialEq)]
1281#[serde(rename_all = "camelCase")]
1282pub struct CurrentBaseProof {
1283 pub proven: bool,
1284 #[serde(skip_serializing_if = "Option::is_none")]
1285 pub rows: Option<Vec<RetainedCommitRow>>,
1286 #[serde(skip_serializing_if = "Option::is_none")]
1287 pub reason: Option<CurrentBaseProofReason>,
1288}
1289
1290#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1291#[serde(rename_all = "snake_case")]
1292pub enum CurrentBaseProofReason {
1293 Offline,
1294 SyncFailed,
1295 SchemaFloor,
1296 BudgetExhausted,
1297 SnapshotFailed,
1298 MissingCoverage,
1299 Revoked,
1300 OutcomeUnavailable,
1301}
1302
1303impl CurrentBaseProof {
1304 pub fn failure(reason: CurrentBaseProofReason) -> Self {
1305 Self {
1306 proven: false,
1307 rows: None,
1308 reason: Some(reason),
1309 }
1310 }
1311}
1312
1313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1314#[serde(rename_all = "camelCase")]
1315pub struct CommitOutcome {
1316 pub sequence: i64,
1317 pub client_commit_id: String,
1318 pub status: CommitOutcomeStatus,
1319 pub recorded_at_ms: i64,
1320 pub results: Vec<CommitOperationOutcome>,
1321 #[serde(skip_serializing_if = "Option::is_none")]
1324 pub operations: Option<Vec<CommitOperation>>,
1325 #[serde(skip_serializing_if = "Option::is_none")]
1326 pub retained_rows: Option<Vec<RetainedCommitRow>>,
1327 pub resolution: CommitOutcomeResolution,
1328 #[serde(skip_serializing_if = "Option::is_none")]
1329 pub resolved_at_ms: Option<i64>,
1330 #[serde(skip_serializing_if = "Option::is_none")]
1331 pub replacement_client_commit_id: Option<String>,
1332}
1333
1334#[derive(Debug, Clone, Deserialize, Default)]
1335#[serde(rename_all = "camelCase")]
1336pub struct CommitOutcomeQuery {
1337 pub limit: Option<usize>,
1338 #[serde(default)]
1339 pub active_only: bool,
1340}
1341
1342#[derive(Debug, Clone, Serialize)]
1346#[serde(
1347 tag = "state",
1348 rename_all = "camelCase",
1349 rename_all_fields = "camelCase"
1350)]
1351pub enum UnitCatchup {
1352 Unknown {
1353 id: String,
1354 },
1355 Known {
1356 id: String,
1357 status: UnitStatus,
1358 live: bool,
1359 cursor: i64,
1361 has_resume_token: bool,
1362 bootstrap_complete: bool,
1364 known_pending_pages: bool,
1366 #[serde(skip_serializing_if = "Option::is_none")]
1367 reason_code: Option<String>,
1368 },
1369}
1370
1371#[derive(Debug, Clone, Serialize)]
1379#[serde(tag = "status", rename_all = "snake_case")]
1380pub enum CommitDelivery {
1381 Pending {
1382 #[serde(rename = "clientCommitId")]
1383 client_commit_id: String,
1384 },
1385 Known {
1386 #[serde(rename = "clientCommitId")]
1387 client_commit_id: String,
1388 outcome: CommitOutcome,
1389 },
1390 Unknown {
1391 #[serde(rename = "clientCommitId")]
1392 client_commit_id: String,
1393 },
1394}
1395
1396#[derive(Debug, Clone, Serialize)]
1401#[serde(rename_all = "camelCase")]
1402pub struct SnapshotRead {
1403 pub revision: String,
1404 pub queries: Vec<Vec<QueryRow>>,
1405 pub coverage: CoverageSnapshot,
1406 pub units: Vec<UnitCatchup>,
1407 pub deliveries: Vec<CommitDelivery>,
1408}
1409
1410#[derive(Debug, Clone, Deserialize)]
1411#[serde(rename_all = "camelCase")]
1412pub struct ResolveCommitOutcomeInput {
1413 pub client_commit_id: String,
1414 pub resolution: CommitOutcomeResolution,
1415 pub replacement_client_commit_id: Option<String>,
1416}
1417
1418#[derive(Debug, Clone, Serialize)]
1419#[serde(rename_all = "camelCase")]
1420pub struct RowState {
1421 pub row_id: String,
1422 pub version: i64,
1425 pub values: Map<String, Value>,
1426 #[serde(skip_serializing_if = "Option::is_none")]
1428 pub sealed_key: Option<String>,
1429}
1430
1431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1435#[serde(untagged, deny_unknown_fields)]
1436pub enum LocalDataPurgeTarget {
1437 Table {
1438 table: String,
1439 selectors: BTreeMap<String, Vec<String>>,
1440 },
1441 Projection {
1442 projection: String,
1443 },
1444}
1445
1446#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1449#[serde(rename_all = "camelCase", deny_unknown_fields)]
1450pub struct LocalDataPurgeInput {
1451 pub purge_id: String,
1452 pub targets: Vec<LocalDataPurgeTarget>,
1453}
1454
1455#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1457#[serde(rename_all = "camelCase")]
1458pub struct LocalDataPurgeResult {
1459 pub already_applied: bool,
1460 pub purged_rows: usize,
1461 pub dropped_commits: usize,
1462}
1463
1464#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1466#[serde(rename_all = "camelCase", deny_unknown_fields)]
1467pub struct LocalDataRebootstrapInput {
1468 pub rebootstrap_id: String,
1469}
1470
1471#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1473#[serde(rename_all = "camelCase")]
1474pub struct LocalDataRebootstrapResult {
1475 pub already_applied: bool,
1476 pub retained_commits: usize,
1477 pub reset_subscriptions: usize,
1478}
1479
1480#[derive(Debug, Clone, Default)]
1482pub struct ClientLimits {
1483 pub limit_commits: Option<i32>,
1484 pub limit_snapshot_rows: Option<i32>,
1485 pub max_snapshot_pages: Option<i32>,
1486 pub accept: Option<u8>,
1489 pub blob_cache_max_bytes: Option<i64>,
1494 pub outcome_retention_max_entries: Option<usize>,
1497 pub max_push_commits_per_request: Option<usize>,
1499 pub max_push_operations_per_request: Option<usize>,
1504 pub max_push_request_bytes: Option<usize>,
1510 pub previous_version_context: Option<PreviousVersionContextConfig>,
1514 pub authority_reads: Vec<AuthorityQuery>,
1516}
1517
1518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1521#[serde(rename_all = "camelCase", deny_unknown_fields)]
1522pub struct AuthorityQuery {
1523 pub name: String,
1524 pub sql: String,
1526 pub bind: Vec<String>,
1528 pub params: Vec<AuthorityParam>,
1529 pub coverage: Vec<AuthorityCoverage>,
1530 pub reads: BTreeMap<String, Vec<String>>,
1532 pub result_columns: Vec<AuthorityResultColumn>,
1533}
1534
1535#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1536#[serde(deny_unknown_fields)]
1537pub struct AuthorityParam {
1538 pub name: String,
1539 #[serde(rename = "type")]
1541 pub ty: String,
1542 pub nullable: bool,
1543}
1544
1545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1547#[serde(rename_all = "camelCase", deny_unknown_fields)]
1548pub struct AuthorityCoverage {
1549 pub table: String,
1550 pub variable: String,
1551 pub units: Vec<String>,
1552 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1553 pub fixed_scopes: BTreeMap<String, String>,
1554}
1555
1556#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1557#[serde(deny_unknown_fields)]
1558pub struct AuthorityResultColumn {
1559 pub name: String,
1560 #[serde(rename = "type")]
1561 pub ty: String,
1562 pub nullable: bool,
1563}
1564
1565#[derive(Debug, Clone, Serialize, PartialEq)]
1568pub struct AuthorityReadResult {
1569 pub revision: String,
1570 pub results: Vec<AuthorityQueryResult>,
1571}
1572
1573#[derive(Debug, Clone, Serialize, PartialEq)]
1574pub struct AuthorityQueryResult {
1575 pub query: String,
1576 pub rows: Vec<QueryRow>,
1577 pub coverage: Vec<AuthorityCoverageState>,
1578 pub complete: bool,
1580}
1581
1582#[derive(Debug, Clone, Serialize, PartialEq)]
1586pub struct AuthorityCoverageState {
1587 pub table: String,
1588 pub base: Value,
1589 pub unit: String,
1590 pub state: &'static str,
1591}