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)]
131#[serde(rename_all = "camelCase")]
132pub struct UnitRecord {
133 pub id: String,
135 pub scopes: UnitScopes,
136 pub explicit: bool,
139 pub status: UnitStatus,
140 #[serde(skip_serializing_if = "Option::is_none")]
142 pub reason_code: Option<String>,
143 #[serde(skip_serializing_if = "Option::is_none")]
146 pub cursor: Option<i64>,
147 #[serde(skip_serializing_if = "Option::is_none")]
149 pub bootstrap_state: Option<String>,
150 pub seeded: Vec<String>,
152 #[serde(skip_serializing_if = "Option::is_none")]
154 pub echo: Option<Vec<EchoRecord>>,
155}
156
157impl UnitRecord {
158 pub fn bootstrapping(&self) -> bool {
160 self.cursor
161 .is_some_and(|cursor| cursor < 0 || self.bootstrap_state.is_some())
162 }
163}
164
165#[derive(Debug, Clone, Default)]
169pub struct WindowBase {
170 pub variable: String,
171 pub fixed_scopes: UnitScopes,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
182#[serde(rename_all = "camelCase")]
183pub struct WindowState {
184 pub units: Vec<String>,
186 pub pending: Vec<String>,
188}
189
190#[cfg(test)]
191mod time_bucket_tests {
192 use super::{creation_time_bucket, last, TimeBucketUnit};
193
194 #[test]
195 fn utc_month_buckets_cross_year_boundaries() {
196 let now = 1_770_508_800_000; assert_eq!(
198 creation_time_bucket(now, TimeBucketUnit::Month).unwrap(),
199 "2026-02"
200 );
201 assert_eq!(
202 last(3, TimeBucketUnit::Month, now).unwrap(),
203 vec!["2025-12", "2026-01", "2026-02"]
204 );
205 }
206
207 #[test]
208 fn utc_month_buckets_reject_unbounded_input() {
209 assert!(last(0, TimeBucketUnit::Month, 0).is_err());
210 assert!(last(1_201, TimeBucketUnit::Month, 0).is_err());
211 assert!(last(2, TimeBucketUnit::Month, 0).is_err());
212 assert!(creation_time_bucket(-1, TimeBucketUnit::Month).is_err());
213 }
214}
215
216#[derive(Debug, Clone, Serialize)]
217#[serde(rename_all = "camelCase")]
218pub struct TableChange {
219 pub table: String,
220 #[serde(skip_serializing_if = "Option::is_none")]
221 pub scope_keys: Option<Vec<String>>,
222}
223
224#[derive(Debug, Clone, Serialize)]
225#[serde(rename_all = "camelCase")]
226pub struct WindowChange {
227 pub base_key: String,
228 pub units: Vec<String>,
230}
231
232#[derive(Debug, Clone, Serialize)]
233#[serde(rename_all = "camelCase")]
234pub struct SyncStatusSnapshot {
235 pub current_schema_version: i32,
236 pub outbox: usize,
237 pub upgrading: bool,
238 #[serde(skip_serializing_if = "Option::is_none")]
239 pub lease_state: Option<LeaseState>,
240 #[serde(skip_serializing_if = "Option::is_none")]
241 pub schema_floor: Option<SchemaFloor>,
242 pub sync_needed: bool,
243 pub previous_version_context: PreviousVersionStatus,
246 pub security_lifecycle: &'static str,
249}
250
251#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
253#[serde(rename_all = "camelCase")]
254pub struct PreviousVersionStatus {
255 pub present: bool,
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub created_at_ms: Option<i64>,
258}
259
260pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 2;
261pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;
262
263pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
266pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
269pub const LOCAL_AUTHORITY_UNCONFIGURED_CODE: &str = "client.local_authority_unconfigured";
273
274#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
275#[serde(rename_all = "camelCase")]
276pub struct ClientDiagnosticsHost {
277 pub kind: String,
278 pub role: String,
279 pub connectivity: String,
280 pub realtime: RealtimeState,
281 pub realtime_policy: RealtimePolicy,
282 #[serde(skip_serializing_if = "Option::is_none")]
283 pub realtime_reason_code: Option<String>,
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub realtime_retry_delay_ms: Option<u64>,
286}
287
288#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
290#[serde(rename_all = "camelCase")]
291pub struct DiagnosticUnits {
292 pub bootstrapping: usize,
293 pub complete: usize,
294 pub reset: usize,
295 pub revoked: usize,
296 pub failed: usize,
297 pub reason_codes: Vec<String>,
299}
300
301#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
302#[serde(rename_all = "camelCase")]
303pub struct DiagnosticRoundCounters {
304 pub pushed: u32,
305 pub applied: usize,
306 pub rejected: usize,
307 pub retryable: usize,
308 pub conflicts: u32,
309 pub commits_applied: u32,
310 pub segment_rows_applied: u32,
311 pub bootstrapping: usize,
312 pub resets: usize,
313 pub revoked: usize,
314 pub failed: usize,
315 pub deferred_commits: usize,
316}
317
318#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
320#[serde(rename_all = "snake_case")]
321pub enum TransportCauseKind {
322 Network,
323 Connect,
324 Tls,
325 Io,
326 Request,
327 Protocol,
328 Timeout,
329 RoundDeadline,
330 Aborted,
331 Body,
332 Status,
333 Redirect,
334 Unknown,
335}
336
337#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
338#[serde(rename_all = "camelCase")]
339pub struct DiagnosticLastRound {
340 pub status: String,
341 pub started_at_ms: i64,
342 pub completed_at_ms: i64,
343 pub duration_ms: i64,
344 #[serde(skip_serializing_if = "Option::is_none")]
345 pub counters: Option<DiagnosticRoundCounters>,
346 #[serde(skip_serializing_if = "Option::is_none")]
347 pub error_code: Option<String>,
348 #[serde(skip_serializing_if = "Option::is_none")]
349 pub cause_kind: Option<TransportCauseKind>,
350 #[serde(skip_serializing_if = "Option::is_none")]
351 pub http_status: Option<u16>,
352}
353
354#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
355#[serde(rename_all = "camelCase")]
356pub struct DiagnosticLastChange {
357 pub revision: String,
358 pub recorded_at_ms: i64,
359 pub tables: Vec<String>,
360 pub windows: Vec<String>,
361 pub domains_truncated: bool,
362 pub status_changed: bool,
363 pub conflicts_changed: bool,
364 pub rejections_changed: bool,
365 pub outcomes_changed: bool,
366}
367
368#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
369#[serde(rename_all = "camelCase")]
370pub struct ClientDiagnosticsStorage {
371 pub status: String,
372 #[serde(skip_serializing_if = "Option::is_none")]
373 pub database_bytes_approx: Option<i64>,
374 #[serde(skip_serializing_if = "Option::is_none")]
375 pub pending_outbox_bytes_approx: Option<i64>,
376 #[serde(skip_serializing_if = "Option::is_none")]
377 pub retained_outcome_bytes_approx: Option<i64>,
378 #[serde(skip_serializing_if = "Option::is_none")]
379 pub retained_outcome_entries: Option<i64>,
380 #[serde(skip_serializing_if = "Option::is_none")]
381 pub blob_cache_bytes_approx: Option<i64>,
382 #[serde(skip_serializing_if = "Option::is_none")]
383 pub pressure_reason_code: Option<String>,
384}
385
386#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
388#[serde(rename_all = "camelCase")]
389pub struct DiagnosticQueryFailure {
390 pub id: String,
391 pub tables: Vec<String>,
393 pub code: String,
395 #[serde(skip_serializing_if = "Option::is_none")]
397 pub sqlite_code: Option<i32>,
398 pub at_ms: i64,
400}
401
402#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
403#[serde(rename_all = "camelCase")]
404pub struct ClientDiagnosticsSnapshot {
405 pub version: u8,
406 pub captured_at_ms: i64,
407 pub host: ClientDiagnosticsHost,
408 pub security_lifecycle: String,
409 pub schema: ClientDiagnosticsSchema,
410 pub replica: ClientDiagnosticsReplica,
411 pub lease: ClientDiagnosticsLease,
412 pub units: DiagnosticUnits,
413 pub active_units: usize,
416 pub replica_cursor: i64,
418 #[serde(skip_serializing_if = "Option::is_none")]
419 pub last_round: Option<DiagnosticLastRound>,
420 #[serde(skip_serializing_if = "Option::is_none")]
421 pub last_change: Option<DiagnosticLastChange>,
422 pub storage: ClientDiagnosticsStorage,
423 pub query_failures: Vec<DiagnosticQueryFailure>,
424}
425
426#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
427#[serde(rename_all = "camelCase")]
428pub struct ClientDiagnosticsSchema {
429 pub current_version: i32,
430 pub upgrading: bool,
431 #[serde(skip_serializing_if = "Option::is_none")]
432 pub required_version: Option<i32>,
433 #[serde(skip_serializing_if = "Option::is_none")]
434 pub latest_version: Option<i32>,
435}
436
437#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
438#[serde(rename_all = "camelCase")]
439pub struct ClientDiagnosticsReplica {
440 pub local_revision: String,
441 pub sync_needed: bool,
442 pub pending_outbox: usize,
443}
444
445#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
447#[serde(rename_all = "lowercase")]
448pub enum RealtimePolicy {
449 Required,
450 #[default]
451 Optional,
452 Off,
453}
454
455impl RealtimePolicy {
456 #[must_use]
457 pub fn as_str(self) -> &'static str {
458 match self {
459 RealtimePolicy::Required => "required",
460 RealtimePolicy::Optional => "optional",
461 RealtimePolicy::Off => "off",
462 }
463 }
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
471#[serde(rename_all = "lowercase")]
472pub enum RealtimeState {
473 Connected,
474 Connecting,
475 #[default]
476 Disconnected,
477 Lost,
478 Refused,
479 Disabled,
480}
481
482#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
483#[serde(rename_all = "camelCase")]
484pub struct ClientDiagnosticsLease {
485 pub state: String,
486 #[serde(skip_serializing_if = "Option::is_none")]
487 pub expires_at_ms: Option<i64>,
488 #[serde(skip_serializing_if = "Option::is_none")]
489 pub error_code: Option<String>,
490}
491
492#[derive(Debug, Clone, Serialize)]
494#[serde(rename_all = "camelCase")]
495pub struct AppliedServerCommit {
496 pub table: String,
497 pub commit_seq: i64,
498 pub source: AppliedServerCommitSource,
499}
500
501#[derive(Debug, Clone, Copy, Serialize)]
502#[serde(rename_all = "camelCase")]
503pub enum AppliedServerCommitSource {
504 Delta,
505 Pull,
506}
507
508#[derive(Debug, Clone, Serialize)]
509#[serde(rename_all = "camelCase")]
510pub struct ClientChangeBatch {
511 pub revision: String,
512 pub tables: Vec<TableChange>,
513 pub windows: Vec<WindowChange>,
514 #[serde(skip_serializing_if = "Option::is_none")]
515 pub status: Option<SyncStatusSnapshot>,
516 pub conflicts_changed: bool,
517 pub rejections_changed: bool,
518 pub outcomes_changed: bool,
519 #[serde(skip_serializing_if = "Vec::is_empty")]
520 pub applied_commits: Vec<AppliedServerCommit>,
521}
522
523#[derive(Debug, Clone, Serialize)]
524#[serde(tag = "kind", rename_all = "camelCase")]
525pub enum SyncIntent {
526 None,
527 Interactive,
528 Background {
529 #[serde(rename = "delayMs")]
530 delay_ms: u64,
531 },
532}
533
534#[derive(Debug, Clone, Serialize)]
535pub struct CommandEffects {
536 pub sync: SyncIntent,
537}
538
539impl CommandEffects {
540 #[must_use]
541 pub fn none() -> Self {
542 Self {
543 sync: SyncIntent::None,
544 }
545 }
546
547 #[must_use]
548 pub fn interactive() -> Self {
549 Self {
550 sync: SyncIntent::Interactive,
551 }
552 }
553}
554
555#[derive(Debug, Clone)]
556pub struct WindowCoverage {
557 pub base: WindowBase,
558 pub units: Vec<String>,
559}
560
561#[derive(Debug, Clone, Serialize)]
562#[serde(rename_all = "camelCase")]
563pub struct WindowUnitRef {
564 pub base_key: String,
565 pub unit: String,
566}
567
568#[derive(Debug, Clone, Serialize)]
569#[serde(rename_all = "camelCase")]
570pub struct CoverageSnapshot {
571 pub complete: bool,
572 pub pending: Vec<WindowUnitRef>,
573 pub missing: Vec<WindowUnitRef>,
574}
575
576#[derive(Debug, Clone, Copy)]
579pub struct QueryOwner<'a> {
580 pub id: &'a str,
581 pub tables: &'a [&'a str],
582}
583
584#[derive(Debug, Clone, PartialEq, Eq)]
589pub struct QueryReadFailure {
590 pub code: Option<&'static str>,
591 pub sqlite_code: Option<i32>,
592 pub sqlite_message: Option<String>,
593 pub rollback_failure: Option<Box<QueryReadFailure>>,
594 pub message: String,
595}
596
597impl std::fmt::Display for QueryReadFailure {
598 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
599 match self.code {
600 Some(code) => write!(f, "{code}: {}", self.message),
601 None => f.write_str(&self.message),
602 }
603 }
604}
605
606impl From<String> for QueryReadFailure {
607 fn from(message: String) -> Self {
608 Self {
609 code: None,
610 sqlite_code: None,
611 sqlite_message: None,
612 rollback_failure: None,
613 message,
614 }
615 }
616}
617
618impl From<rusqlite::Error> for QueryReadFailure {
619 fn from(error: rusqlite::Error) -> Self {
621 let sqlite_code = match &error {
622 rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
623 _ => None,
624 };
625 match sqlite_code.map(|code| code & 0xff) {
626 Some(11 | 26) => Self {
627 code: Some("client.storage_corrupt"),
628 sqlite_code,
629 sqlite_message: Some(error.to_string()),
630 rollback_failure: None,
631 message: "local SQLite storage is corrupt".to_owned(),
632 },
633 Some(13) => Self {
634 code: Some("client.storage_full"),
635 sqlite_code,
636 sqlite_message: Some(error.to_string()),
637 rollback_failure: None,
638 message: "local SQLite storage is full".to_owned(),
639 },
640 Some(10) => Self {
641 code: Some("client.storage_io"),
642 sqlite_code,
643 sqlite_message: Some(error.to_string()),
644 rollback_failure: None,
645 message: "local SQLite storage I/O failed".to_owned(),
646 },
647 Some(5 | 6) => Self {
651 code: Some("client.storage_busy"),
652 sqlite_code,
653 sqlite_message: Some(error.to_string()),
654 rollback_failure: None,
655 message: "local SQLite storage is busy".to_owned(),
656 },
657 _ => Self {
658 code: None,
659 sqlite_code,
660 sqlite_message: Some(error.to_string()),
661 rollback_failure: None,
662 message: error.to_string(),
663 },
664 }
665 }
666}
667
668impl QueryReadFailure {
669 pub fn retryable(&self) -> bool {
672 self.code == Some("client.storage_busy")
673 }
674
675 pub fn details(&self) -> Option<Value> {
676 self.sqlite_code.map(|code| {
677 let mut details =
678 serde_json::json!({ "sqliteCode": code, "sqliteMessage": self.sqlite_message });
679 if let Some(rollback) = &self.rollback_failure {
680 details["rollbackFailure"] = serde_json::json!({
681 "sqliteCode": rollback.sqlite_code, "message": rollback.sqlite_message
682 });
683 }
684 details
685 })
686 }
687}
688
689#[derive(Debug, Clone, PartialEq, Eq)]
696pub struct ClientError {
697 pub code: String,
698 pub message: String,
699 pub details: Option<Value>,
700 pub retryable: bool,
701}
702
703const DEFAULT_CLIENT_ERROR_CODE: &str = "client.failed";
705
706const GENERIC_AUTHORING_MESSAGE: &str = "the local authoring operation failed";
708
709fn static_authoring_message(code: &str) -> Option<&'static str> {
712 match code {
713 "sync.unknown_table" => Some("the commit targets an unknown table"),
714 "sync.invalid_request" => Some("the authoring request is invalid"),
715 "sync.row_missing" => Some("a sparse patch requires a local row"),
716 "sync.constraint_violation" => Some("local write violates a unique constraint"),
717 DEFAULT_CLIENT_ERROR_CODE => Some(GENERIC_AUTHORING_MESSAGE),
718 _ => None,
719 }
720}
721
722fn is_client_code(candidate: &str) -> bool {
723 candidate.starts_with("client.") || candidate.starts_with("sync.")
724}
725
726impl std::fmt::Display for ClientError {
727 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
728 write!(f, "{}: {}", self.code, self.message)
729 }
730}
731
732impl std::error::Error for ClientError {}
733
734impl From<QueryReadFailure> for ClientError {
735 fn from(failure: QueryReadFailure) -> Self {
736 match failure.code {
737 Some(code) => {
739 let details = failure.details();
740 let retryable = failure.retryable();
741 Self {
742 code: code.to_owned(),
743 message: failure.message,
744 details,
745 retryable,
746 }
747 }
748 None => {
749 let mut details = failure.details().unwrap_or_else(|| serde_json::json!({}));
750 if let Some(object) = details.as_object_mut() {
751 object.insert("legacyCause".to_owned(), Value::String(failure.message));
752 }
753 Self {
754 code: DEFAULT_CLIENT_ERROR_CODE.to_owned(),
755 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
756 details: Some(details),
757 retryable: false,
758 }
759 }
760 }
761 }
762}
763
764impl From<String> for ClientError {
765 fn from(message: String) -> Self {
770 if !message.contains(": ") && is_client_code(&message) {
772 return Self {
773 code: message.clone(),
774 message: static_authoring_message(&message)
775 .unwrap_or(GENERIC_AUTHORING_MESSAGE)
776 .to_owned(),
777 details: None,
778 retryable: false,
779 };
780 }
781 let (code, rest) = match message.split_once(": ") {
782 Some((code, rest)) if is_client_code(code) => (code, Some(rest)),
783 _ => (DEFAULT_CLIENT_ERROR_CODE, None),
784 };
785 match static_authoring_message(code) {
786 Some(fixed) => Self {
787 code: code.to_owned(),
788 message: fixed.to_owned(),
789 details: (rest != Some(fixed))
790 .then(|| serde_json::json!({ "legacyCause": message })),
791 retryable: false,
792 },
793 None => Self {
794 code: code.to_owned(),
795 message: GENERIC_AUTHORING_MESSAGE.to_owned(),
796 details: Some(serde_json::json!({ "legacyCause": message })),
797 retryable: false,
798 },
799 }
800 }
801}
802
803#[derive(Debug, Clone, Serialize)]
804#[serde(rename_all = "camelCase")]
805pub struct QuerySnapshot {
806 pub revision: String,
807 pub rows: Vec<QueryRow>,
808 pub coverage: CoverageSnapshot,
809}
810
811impl WindowState {
812 #[must_use]
814 pub fn complete(&self, unit: &str) -> bool {
815 self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
816 }
817}
818
819#[derive(Debug, Clone)]
821pub enum Mutation {
822 Patch {
823 table: String,
824 values: Map<String, Value>,
825 base_version: Option<i64>,
826 },
827 Upsert {
828 table: String,
829 values: Map<String, Value>,
830 base_version: Option<i64>,
831 },
832 Delete {
833 table: String,
834 row_id: String,
835 base_version: Option<i64>,
836 },
837}
838
839#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
840#[serde(rename_all = "camelCase")]
841pub struct SchemaFloor {
842 #[serde(skip_serializing_if = "Option::is_none")]
843 pub required_schema_version: Option<i32>,
844 #[serde(skip_serializing_if = "Option::is_none")]
845 pub latest_schema_version: Option<i32>,
846}
847
848#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
852#[serde(rename_all = "camelCase")]
853pub struct LeaseState {
854 #[serde(skip_serializing_if = "Option::is_none")]
855 pub lease_id: Option<String>,
856 #[serde(skip_serializing_if = "Option::is_none")]
857 pub expires_at_ms: Option<i64>,
858 #[serde(skip_serializing_if = "Option::is_none")]
859 pub error_code: Option<String>,
860}
861
862#[derive(Debug, Clone, Serialize)]
864#[serde(rename_all = "camelCase")]
865pub struct PresencePeer {
866 pub actor_id: String,
867 pub client_id: String,
868 pub doc: serde_json::Value,
869}
870
871#[derive(Debug, Clone, Serialize, Default)]
872#[serde(rename_all = "camelCase")]
873pub struct SyncReport {
874 pub pushed: u32,
875 pub applied: Vec<String>,
876 pub rejected: Vec<String>,
877 pub retryable: Vec<String>,
878 pub conflicts: u32,
879 pub commits_applied: u32,
880 pub segment_rows_applied: u32,
881 pub bootstrapping: Vec<String>,
882 pub resets: Vec<String>,
883 pub revoked: Vec<String>,
884 pub failed: Vec<String>,
885 pub deferred_commits: usize,
886 #[serde(skip_serializing_if = "Option::is_none")]
887 pub schema_floor: Option<SchemaFloor>,
888}
889
890impl SyncReport {
891 pub fn merge(&mut self, report: &Self) {
896 self.pushed += report.pushed;
897 self.applied.extend(report.applied.iter().cloned());
898 self.rejected.extend(report.rejected.iter().cloned());
899 self.retryable.extend(report.retryable.iter().cloned());
900 self.conflicts += report.conflicts;
901 self.commits_applied += report.commits_applied;
902 self.segment_rows_applied += report.segment_rows_applied;
903 self.bootstrapping = report.bootstrapping.clone();
904 self.resets.extend(report.resets.iter().cloned());
905 self.revoked.extend(report.revoked.iter().cloned());
906 self.failed.extend(report.failed.iter().cloned());
907 self.deferred_commits = report.deferred_commits;
908 self.schema_floor = report.schema_floor.clone();
909 }
910}
911
912#[derive(Debug, Clone)]
915pub enum SyncOutcome {
916 Ok(SyncReport),
917 Failed {
918 error_code: String,
919 message: String,
920 details: Option<Value>,
921 recommended_action: Option<String>,
925 },
926 RealtimeUnavailable {
931 state: RealtimeState,
932 reason_code: Option<String>,
933 retry_delay_ms: u64,
934 },
935 BudgetExhausted(SyncReport),
939}
940
941impl SyncOutcome {
942 pub fn to_json(&self) -> Value {
943 match self {
944 SyncOutcome::Ok(report) => {
945 let mut map = Map::new();
946 map.insert("ok".to_owned(), Value::Bool(true));
947 map.insert(
948 "report".to_owned(),
949 serde_json::to_value(report).expect("report serializes"),
950 );
951 Value::Object(map)
952 }
953 SyncOutcome::Failed {
954 error_code,
955 message,
956 details,
957 recommended_action,
958 } => {
959 let mut map = Map::new();
960 map.insert("ok".to_owned(), Value::Bool(false));
961 map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
962 map.insert("message".to_owned(), Value::from(message.clone()));
963 if let Some(details) = details {
964 map.insert("details".to_owned(), details.clone());
965 }
966 if let Some(recommended_action) = recommended_action {
967 map.insert(
968 "recommendedAction".to_owned(),
969 Value::from(recommended_action.clone()),
970 );
971 }
972 Value::Object(map)
973 }
974 SyncOutcome::RealtimeUnavailable {
975 state,
976 reason_code,
977 retry_delay_ms,
978 } => {
979 let mut map = Map::new();
980 map.insert("ok".to_owned(), Value::Bool(false));
981 map.insert(
982 "errorCode".to_owned(),
983 Value::from(REALTIME_UNAVAILABLE_CODE),
984 );
985 map.insert(
986 "message".to_owned(),
987 Value::from("realtime is required and the realtime socket is not connected"),
988 );
989 map.insert(
990 "realtimeState".to_owned(),
991 serde_json::to_value(state).expect("state serializes"),
992 );
993 if let Some(reason_code) = reason_code {
994 map.insert(
995 "realtimeReasonCode".to_owned(),
996 Value::from(reason_code.clone()),
997 );
998 }
999 map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
1000 Value::Object(map)
1001 }
1002 SyncOutcome::BudgetExhausted(report) => {
1003 let mut map = Map::new();
1004 map.insert("ok".to_owned(), Value::Bool(true));
1005 map.insert("budgetExhausted".to_owned(), Value::Bool(true));
1006 map.insert(
1007 "report".to_owned(),
1008 serde_json::to_value(report).expect("report serializes"),
1009 );
1010 Value::Object(map)
1011 }
1012 }
1013 }
1014}
1015
1016#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1017#[serde(rename_all = "camelCase")]
1018pub struct ConflictRecord {
1019 pub client_commit_id: String,
1020 pub op_index: i32,
1021 pub table: String,
1022 pub row_id: String,
1023 pub code: String,
1024 pub message: String,
1025 pub server_version: i64,
1026 pub server_row: Map<String, Value>,
1029 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1034 pub conflict_columns: Vec<String>,
1035 #[serde(skip_serializing_if = "Option::is_none")]
1036 pub operation: Option<CommitOperation>,
1037}
1038
1039#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1042#[serde(rename_all = "camelCase", deny_unknown_fields)]
1043pub struct RejectionDetails {
1044 #[serde(skip_serializing_if = "Option::is_none")]
1045 pub field_paths: Option<Vec<String>>,
1046 #[serde(skip_serializing_if = "Option::is_none")]
1047 pub reason: Option<String>,
1048 #[serde(skip_serializing_if = "Option::is_none")]
1049 pub required_action: Option<String>,
1050 #[serde(skip_serializing_if = "Option::is_none")]
1051 pub references: Option<BTreeMap<String, String>>,
1052}
1053
1054impl RejectionDetails {
1055 pub(crate) fn parse(raw: &str) -> Result<Self, String> {
1056 if raw.len() > 4_096 {
1057 return Err("rejection details exceed 4096 encoded bytes".to_owned());
1058 }
1059 let details: Self = serde_json::from_str(raw)
1060 .map_err(|error| format!("invalid rejection details: {error}"))?;
1061 details.validate()?;
1062 Ok(details)
1063 }
1064
1065 fn validate(&self) -> Result<(), String> {
1066 let mut members = 0;
1067 if let Some(paths) = &self.field_paths {
1068 members += 1;
1069 if paths.is_empty() || paths.len() > 32 {
1070 return Err("fieldPaths must contain 1-32 paths".to_owned());
1071 }
1072 let mut seen = std::collections::BTreeSet::new();
1073 for path in paths {
1074 if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
1075 {
1076 return Err("fieldPaths contains an invalid or duplicate path".to_owned());
1077 }
1078 }
1079 }
1080 if let Some(reason) = &self.reason {
1081 members += 1;
1082 if !valid_token(reason, 96) {
1083 return Err("reason must be a lowercase stable token".to_owned());
1084 }
1085 }
1086 if let Some(action) = &self.required_action {
1087 members += 1;
1088 if !valid_token(action, 96) {
1089 return Err("requiredAction must be a lowercase stable token".to_owned());
1090 }
1091 }
1092 if let Some(references) = &self.references {
1093 members += 1;
1094 if references.is_empty() || references.len() > 16 {
1095 return Err("references must contain 1-16 entries".to_owned());
1096 }
1097 for (key, value) in references {
1098 if !valid_token(key, 64)
1099 || value.is_empty()
1100 || value.len() > 256
1101 || value.trim() != value
1102 || value.chars().any(char::is_control)
1103 {
1104 return Err("references contains an invalid key or value".to_owned());
1105 }
1106 }
1107 }
1108 if members == 0 {
1109 return Err("rejection details must not be empty".to_owned());
1110 }
1111 Ok(())
1112 }
1113}
1114
1115fn valid_identifier(segment: &str) -> bool {
1116 let mut chars = segment.chars();
1117 matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
1118 && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
1119}
1120
1121fn valid_token(token: &str, max: usize) -> bool {
1122 if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
1123 {
1124 return false;
1125 }
1126 let mut previous_separator = false;
1127 for character in token.chars() {
1128 if character.is_ascii_lowercase() || character.is_ascii_digit() {
1129 previous_separator = false;
1130 } else if matches!(character, '.' | '_' | '-') && !previous_separator {
1131 previous_separator = true;
1132 } else {
1133 return false;
1134 }
1135 }
1136 !previous_separator
1137}
1138
1139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1140#[serde(rename_all = "camelCase")]
1141pub struct RejectionRecord {
1142 pub client_commit_id: String,
1143 pub op_index: i32,
1144 pub code: String,
1145 pub message: String,
1146 pub retryable: bool,
1147 #[serde(skip_serializing_if = "Option::is_none")]
1148 pub details: Option<RejectionDetails>,
1149 #[serde(skip_serializing_if = "Option::is_none")]
1150 pub operation: Option<CommitOperation>,
1151}
1152
1153#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1155#[serde(rename_all = "camelCase")]
1156pub struct CommitOperation {
1157 pub table: String,
1158 pub row_id: String,
1159 pub op: String,
1160 #[serde(skip_serializing_if = "Option::is_none")]
1161 pub base_version: Option<i64>,
1162 #[serde(skip_serializing_if = "Option::is_none")]
1163 pub values: Option<Map<String, Value>>,
1164 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1166 pub insert: bool,
1167}
1168
1169#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1170#[serde(rename_all = "snake_case")]
1171pub enum CommitOutcomeStatus {
1172 Applied,
1173 Cached,
1174 Conflict,
1175 Rejected,
1176}
1177
1178#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1179#[serde(rename_all = "snake_case")]
1180pub enum CommitOutcomeResolution {
1181 Active,
1182 ResolvedKeepServer,
1183 Superseded,
1184 Dismissed,
1185}
1186
1187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1188#[serde(tag = "status", rename_all = "snake_case")]
1189pub enum CommitOperationOutcome {
1190 Applied {
1191 #[serde(rename = "opIndex")]
1192 op_index: i32,
1193 },
1194 Conflict {
1195 conflict: ConflictRecord,
1196 },
1197 Error {
1198 rejection: RejectionRecord,
1199 },
1200}
1201
1202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1203#[serde(rename_all = "camelCase")]
1204pub struct RetainedUniqueConflict {
1205 pub index: String,
1206 pub columns: Vec<String>,
1207 pub row_id: String,
1208 pub server_row: Map<String, Value>,
1209 pub server_version: i64,
1210}
1211
1212#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1213#[serde(rename_all = "camelCase")]
1214pub struct RetainedCommitRow {
1215 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1216 pub unique_conflicts: Vec<RetainedUniqueConflict>,
1217 pub table: String,
1218 pub row_id: String,
1219 pub local_row: Option<Map<String, Value>>,
1220 pub server_row: Option<Map<String, Value>>,
1222 pub server_version: Option<i64>,
1223}
1224
1225#[derive(Debug, Clone, Serialize, PartialEq)]
1227#[serde(rename_all = "camelCase")]
1228pub struct CurrentBaseProof {
1229 pub proven: bool,
1230 #[serde(skip_serializing_if = "Option::is_none")]
1231 pub rows: Option<Vec<RetainedCommitRow>>,
1232 #[serde(skip_serializing_if = "Option::is_none")]
1233 pub reason: Option<CurrentBaseProofReason>,
1234}
1235
1236#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
1237#[serde(rename_all = "snake_case")]
1238pub enum CurrentBaseProofReason {
1239 Offline,
1240 SyncFailed,
1241 SchemaFloor,
1242 BudgetExhausted,
1243 SnapshotFailed,
1244 MissingCoverage,
1245 Revoked,
1246 OutcomeUnavailable,
1247}
1248
1249impl CurrentBaseProof {
1250 pub fn failure(reason: CurrentBaseProofReason) -> Self {
1251 Self {
1252 proven: false,
1253 rows: None,
1254 reason: Some(reason),
1255 }
1256 }
1257}
1258
1259#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1260#[serde(rename_all = "camelCase")]
1261pub struct CommitOutcome {
1262 pub sequence: i64,
1263 pub client_commit_id: String,
1264 pub status: CommitOutcomeStatus,
1265 pub recorded_at_ms: i64,
1266 pub results: Vec<CommitOperationOutcome>,
1267 #[serde(skip_serializing_if = "Option::is_none")]
1270 pub operations: Option<Vec<CommitOperation>>,
1271 #[serde(skip_serializing_if = "Option::is_none")]
1272 pub retained_rows: Option<Vec<RetainedCommitRow>>,
1273 pub resolution: CommitOutcomeResolution,
1274 #[serde(skip_serializing_if = "Option::is_none")]
1275 pub resolved_at_ms: Option<i64>,
1276 #[serde(skip_serializing_if = "Option::is_none")]
1277 pub replacement_client_commit_id: Option<String>,
1278}
1279
1280#[derive(Debug, Clone, Deserialize, Default)]
1281#[serde(rename_all = "camelCase")]
1282pub struct CommitOutcomeQuery {
1283 pub limit: Option<usize>,
1284 #[serde(default)]
1285 pub active_only: bool,
1286}
1287
1288#[derive(Debug, Clone, Serialize)]
1292#[serde(
1293 tag = "state",
1294 rename_all = "camelCase",
1295 rename_all_fields = "camelCase"
1296)]
1297pub enum UnitCatchup {
1298 Unknown {
1299 id: String,
1300 },
1301 Known {
1302 id: String,
1303 status: UnitStatus,
1304 live: bool,
1305 cursor: i64,
1307 has_resume_token: bool,
1308 bootstrap_complete: bool,
1310 known_pending_pages: bool,
1312 #[serde(skip_serializing_if = "Option::is_none")]
1313 reason_code: Option<String>,
1314 },
1315}
1316
1317#[derive(Debug, Clone, Serialize)]
1326#[serde(tag = "status", rename_all = "snake_case")]
1327pub enum CommitDelivery {
1328 Pending {
1329 #[serde(rename = "clientCommitId")]
1330 client_commit_id: String,
1331 },
1332 Known {
1333 #[serde(rename = "clientCommitId")]
1334 client_commit_id: String,
1335 outcome: CommitOutcome,
1336 },
1337 Unknown {
1338 #[serde(rename = "clientCommitId")]
1339 client_commit_id: String,
1340 },
1341}
1342
1343#[derive(Debug, Clone, Serialize)]
1348#[serde(rename_all = "camelCase")]
1349pub struct SnapshotRead {
1350 pub revision: String,
1351 pub queries: Vec<Vec<QueryRow>>,
1352 pub coverage: CoverageSnapshot,
1353 pub units: Vec<UnitCatchup>,
1354 pub deliveries: Vec<CommitDelivery>,
1355}
1356
1357#[derive(Debug, Clone, Deserialize)]
1358#[serde(rename_all = "camelCase")]
1359pub struct ResolveCommitOutcomeInput {
1360 pub client_commit_id: String,
1361 pub resolution: CommitOutcomeResolution,
1362 pub replacement_client_commit_id: Option<String>,
1363}
1364
1365#[derive(Debug, Clone, Serialize)]
1366#[serde(rename_all = "camelCase")]
1367pub struct RowState {
1368 pub row_id: String,
1369 pub version: i64,
1372 pub values: Map<String, Value>,
1373}
1374
1375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1379#[serde(rename_all = "camelCase", deny_unknown_fields)]
1380pub struct LocalDataPurgeTarget {
1381 pub table: String,
1382 pub selectors: BTreeMap<String, Vec<String>>,
1383}
1384
1385#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1388#[serde(rename_all = "camelCase", deny_unknown_fields)]
1389pub struct LocalDataPurgeInput {
1390 pub purge_id: String,
1391 pub targets: Vec<LocalDataPurgeTarget>,
1392}
1393
1394#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1396#[serde(rename_all = "camelCase")]
1397pub struct LocalDataPurgeResult {
1398 pub already_applied: bool,
1399 pub purged_rows: usize,
1400 pub dropped_commits: usize,
1401}
1402
1403#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1405#[serde(rename_all = "camelCase", deny_unknown_fields)]
1406pub struct LocalDataRebootstrapInput {
1407 pub rebootstrap_id: String,
1408}
1409
1410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1412#[serde(rename_all = "camelCase")]
1413pub struct LocalDataRebootstrapResult {
1414 pub already_applied: bool,
1415 pub retained_commits: usize,
1416 pub reset_subscriptions: usize,
1417}
1418
1419#[derive(Debug, Clone, Default)]
1421pub struct ClientLimits {
1422 pub limit_commits: Option<i32>,
1423 pub limit_snapshot_rows: Option<i32>,
1424 pub max_snapshot_pages: Option<i32>,
1425 pub accept: Option<u8>,
1428 pub blob_cache_max_bytes: Option<i64>,
1433 pub outcome_retention_max_entries: Option<usize>,
1436 pub max_push_commits_per_request: Option<usize>,
1438 pub max_push_operations_per_request: Option<usize>,
1443 pub max_push_request_bytes: Option<usize>,
1449 pub previous_version_context: Option<PreviousVersionContextConfig>,
1453 pub authority_reads: Vec<AuthorityReadDeclaration>,
1455}
1456
1457#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
1459#[serde(rename_all = "camelCase", deny_unknown_fields)]
1460pub struct AuthorityReadDeclaration {
1461 pub table: String,
1462 pub columns: Vec<String>,
1463 pub scopes: std::collections::BTreeMap<String, Vec<String>>,
1464}