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