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
97#[derive(Debug, Clone)]
101pub struct WindowBase {
102 pub table: String,
103 pub variable: String,
104 pub fixed_scopes: Vec<(String, Vec<String>)>,
106 pub params: Option<String>,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
116#[serde(rename_all = "camelCase")]
117pub struct WindowState {
118 pub units: Vec<String>,
120 pub pending: Vec<String>,
122}
123
124#[cfg(test)]
125mod time_bucket_tests {
126 use super::{creation_time_bucket, last, TimeBucketUnit};
127
128 #[test]
129 fn utc_month_buckets_cross_year_boundaries() {
130 let now = 1_770_508_800_000; assert_eq!(
132 creation_time_bucket(now, TimeBucketUnit::Month).unwrap(),
133 "2026-02"
134 );
135 assert_eq!(
136 last(3, TimeBucketUnit::Month, now).unwrap(),
137 vec!["2025-12", "2026-01", "2026-02"]
138 );
139 }
140
141 #[test]
142 fn utc_month_buckets_reject_unbounded_input() {
143 assert!(last(0, TimeBucketUnit::Month, 0).is_err());
144 assert!(last(1_201, TimeBucketUnit::Month, 0).is_err());
145 assert!(last(2, TimeBucketUnit::Month, 0).is_err());
146 assert!(creation_time_bucket(-1, TimeBucketUnit::Month).is_err());
147 }
148}
149
150#[derive(Debug, Clone, Serialize)]
151#[serde(rename_all = "camelCase")]
152pub struct TableChange {
153 pub table: String,
154 #[serde(skip_serializing_if = "Option::is_none")]
155 pub scope_keys: Option<Vec<String>>,
156}
157
158#[derive(Debug, Clone, Serialize)]
159#[serde(rename_all = "camelCase")]
160pub struct WindowChange {
161 pub base_key: String,
162 pub table: String,
163 pub units: Vec<String>,
164}
165
166#[derive(Debug, Clone, Serialize)]
167#[serde(rename_all = "camelCase")]
168pub struct SyncStatusSnapshot {
169 pub current_schema_version: i32,
170 pub outbox: usize,
171 pub upgrading: bool,
172 #[serde(skip_serializing_if = "Option::is_none")]
173 pub lease_state: Option<LeaseState>,
174 #[serde(skip_serializing_if = "Option::is_none")]
175 pub schema_floor: Option<SchemaFloor>,
176 pub sync_needed: bool,
177 pub previous_version_context: PreviousVersionStatus,
180}
181
182#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq)]
184#[serde(rename_all = "camelCase")]
185pub struct PreviousVersionStatus {
186 pub present: bool,
187 #[serde(skip_serializing_if = "Option::is_none")]
188 pub created_at_ms: Option<i64>,
189}
190
191pub const CLIENT_DIAGNOSTICS_VERSION: u8 = 1;
192pub const MAX_DIAGNOSTIC_EXPECTED_SUBSCRIPTIONS: usize = 256;
193pub const MAX_DIAGNOSTIC_QUERY_FAILURES: usize = 256;
194
195pub const REALTIME_UNAVAILABLE_CODE: &str = "sync.realtime_unavailable";
198pub const REALTIME_LOST_CODE: &str = "client.realtime_lost";
201
202#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
203#[serde(rename_all = "camelCase", deny_unknown_fields)]
204pub struct ExpectedDiagnosticSubscription {
205 pub id: String,
206 pub table: String,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
210#[serde(rename_all = "camelCase", deny_unknown_fields)]
211pub struct ClientDiagnosticsRequest {
212 #[serde(default)]
213 pub expected_subscriptions: Vec<ExpectedDiagnosticSubscription>,
214}
215
216#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
217#[serde(rename_all = "camelCase")]
218pub struct ClientDiagnosticsHost {
219 pub kind: String,
220 pub role: String,
221 pub connectivity: String,
222 pub realtime: RealtimeState,
223 pub realtime_policy: RealtimePolicy,
224 #[serde(skip_serializing_if = "Option::is_none")]
225 pub realtime_reason_code: Option<String>,
226 #[serde(skip_serializing_if = "Option::is_none")]
227 pub realtime_retry_delay_ms: Option<u64>,
228}
229
230#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
231#[serde(rename_all = "camelCase")]
232pub struct DiagnosticSubscription {
233 pub id: String,
234 pub table: String,
235 pub state: String,
236 pub complete: bool,
237 #[serde(skip_serializing_if = "Option::is_none")]
238 pub cursor: Option<i64>,
239 #[serde(skip_serializing_if = "Option::is_none")]
240 pub reason_code: Option<String>,
241}
242
243#[derive(Debug, Clone, Serialize, Default, PartialEq, Eq)]
244#[serde(rename_all = "camelCase")]
245pub struct DiagnosticRoundCounters {
246 pub pushed: u32,
247 pub applied: usize,
248 pub rejected: usize,
249 pub retryable: usize,
250 pub conflicts: u32,
251 pub commits_applied: u32,
252 pub segment_rows_applied: u32,
253 pub bootstrapping: usize,
254 pub resets: usize,
255 pub revoked: usize,
256 pub failed: usize,
257 pub deferred_commits: usize,
258}
259
260#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
261#[serde(rename_all = "camelCase")]
262pub struct DiagnosticLastRound {
263 pub status: String,
264 pub started_at_ms: i64,
265 pub completed_at_ms: i64,
266 pub duration_ms: i64,
267 #[serde(skip_serializing_if = "Option::is_none")]
268 pub counters: Option<DiagnosticRoundCounters>,
269 #[serde(skip_serializing_if = "Option::is_none")]
270 pub error_code: Option<String>,
271}
272
273#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
274#[serde(rename_all = "camelCase")]
275pub struct DiagnosticLastChange {
276 pub revision: String,
277 pub recorded_at_ms: i64,
278 pub tables: Vec<String>,
279 pub windows: Vec<String>,
280 pub domains_truncated: bool,
281 pub status_changed: bool,
282 pub conflicts_changed: bool,
283 pub rejections_changed: bool,
284 pub outcomes_changed: bool,
285}
286
287#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
288#[serde(rename_all = "camelCase")]
289pub struct ClientDiagnosticsStorage {
290 pub status: String,
291 #[serde(skip_serializing_if = "Option::is_none")]
292 pub database_bytes_approx: Option<i64>,
293 #[serde(skip_serializing_if = "Option::is_none")]
294 pub pending_outbox_bytes_approx: Option<i64>,
295 #[serde(skip_serializing_if = "Option::is_none")]
296 pub retained_outcome_bytes_approx: Option<i64>,
297 #[serde(skip_serializing_if = "Option::is_none")]
298 pub retained_outcome_entries: Option<i64>,
299 #[serde(skip_serializing_if = "Option::is_none")]
300 pub blob_cache_bytes_approx: Option<i64>,
301 #[serde(skip_serializing_if = "Option::is_none")]
302 pub pressure_reason_code: Option<String>,
303}
304
305#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
307#[serde(rename_all = "camelCase")]
308pub struct DiagnosticQueryFailure {
309 pub id: String,
310 pub tables: Vec<String>,
312 pub code: String,
314 #[serde(skip_serializing_if = "Option::is_none")]
316 pub sqlite_code: Option<i32>,
317 pub at_ms: i64,
319}
320
321#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
322#[serde(rename_all = "camelCase")]
323pub struct ClientDiagnosticsSnapshot {
324 pub version: u8,
325 pub captured_at_ms: i64,
326 pub host: ClientDiagnosticsHost,
327 pub security_lifecycle: String,
328 pub schema: ClientDiagnosticsSchema,
329 pub replica: ClientDiagnosticsReplica,
330 pub lease: ClientDiagnosticsLease,
331 pub subscriptions: Vec<DiagnosticSubscription>,
332 pub subscriptions_truncated: bool,
333 #[serde(skip_serializing_if = "Option::is_none")]
334 pub last_round: Option<DiagnosticLastRound>,
335 #[serde(skip_serializing_if = "Option::is_none")]
336 pub last_change: Option<DiagnosticLastChange>,
337 pub storage: ClientDiagnosticsStorage,
338 pub query_failures: Vec<DiagnosticQueryFailure>,
339}
340
341#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
342#[serde(rename_all = "camelCase")]
343pub struct ClientDiagnosticsSchema {
344 pub current_version: i32,
345 pub upgrading: bool,
346 #[serde(skip_serializing_if = "Option::is_none")]
347 pub required_version: Option<i32>,
348 #[serde(skip_serializing_if = "Option::is_none")]
349 pub latest_version: Option<i32>,
350}
351
352#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
353#[serde(rename_all = "camelCase")]
354pub struct ClientDiagnosticsReplica {
355 pub local_revision: String,
356 pub sync_needed: bool,
357 pub pending_outbox: usize,
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
362#[serde(rename_all = "lowercase")]
363pub enum RealtimePolicy {
364 Required,
365 #[default]
366 Optional,
367 Off,
368}
369
370impl RealtimePolicy {
371 #[must_use]
372 pub fn as_str(self) -> &'static str {
373 match self {
374 RealtimePolicy::Required => "required",
375 RealtimePolicy::Optional => "optional",
376 RealtimePolicy::Off => "off",
377 }
378 }
379}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
386#[serde(rename_all = "lowercase")]
387pub enum RealtimeState {
388 Connected,
389 Connecting,
390 #[default]
391 Disconnected,
392 Lost,
393 Refused,
394 Disabled,
395}
396
397#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
398#[serde(rename_all = "camelCase")]
399pub struct ClientDiagnosticsLease {
400 pub state: String,
401 #[serde(skip_serializing_if = "Option::is_none")]
402 pub expires_at_ms: Option<i64>,
403 #[serde(skip_serializing_if = "Option::is_none")]
404 pub error_code: Option<String>,
405}
406
407#[derive(Debug, Clone, Serialize)]
409#[serde(rename_all = "camelCase")]
410pub struct ClientChangeBatch {
411 pub revision: String,
412 pub tables: Vec<TableChange>,
413 pub windows: Vec<WindowChange>,
414 #[serde(skip_serializing_if = "Option::is_none")]
415 pub status: Option<SyncStatusSnapshot>,
416 pub conflicts_changed: bool,
417 pub rejections_changed: bool,
418 pub outcomes_changed: bool,
419}
420
421#[derive(Debug, Clone, Serialize)]
422#[serde(tag = "kind", rename_all = "camelCase")]
423pub enum SyncIntent {
424 None,
425 Interactive,
426 Background {
427 #[serde(rename = "delayMs")]
428 delay_ms: u64,
429 },
430}
431
432#[derive(Debug, Clone, Serialize)]
433pub struct CommandEffects {
434 pub sync: SyncIntent,
435}
436
437impl CommandEffects {
438 #[must_use]
439 pub fn none() -> Self {
440 Self {
441 sync: SyncIntent::None,
442 }
443 }
444
445 #[must_use]
446 pub fn interactive() -> Self {
447 Self {
448 sync: SyncIntent::Interactive,
449 }
450 }
451}
452
453#[derive(Debug, Clone)]
454pub struct WindowCoverage {
455 pub base: WindowBase,
456 pub units: Vec<String>,
457}
458
459#[derive(Debug, Clone, Serialize)]
460#[serde(rename_all = "camelCase")]
461pub struct WindowUnitRef {
462 pub base_key: String,
463 pub unit: String,
464}
465
466#[derive(Debug, Clone, Serialize)]
467#[serde(rename_all = "camelCase")]
468pub struct CoverageSnapshot {
469 pub complete: bool,
470 pub pending: Vec<WindowUnitRef>,
471 pub missing: Vec<WindowUnitRef>,
472}
473
474#[derive(Debug, Clone, Copy)]
477pub struct QueryOwner<'a> {
478 pub id: &'a str,
479 pub tables: &'a [&'a str],
480}
481
482#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct QueryReadFailure {
487 pub code: Option<&'static str>,
488 pub sqlite_code: Option<i32>,
489 pub message: String,
490}
491
492impl std::fmt::Display for QueryReadFailure {
493 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494 match self.code {
495 Some(code) => write!(f, "{code}: {}", self.message),
496 None => f.write_str(&self.message),
497 }
498 }
499}
500
501impl From<String> for QueryReadFailure {
502 fn from(message: String) -> Self {
503 Self {
504 code: None,
505 sqlite_code: None,
506 message,
507 }
508 }
509}
510
511impl From<rusqlite::Error> for QueryReadFailure {
512 fn from(error: rusqlite::Error) -> Self {
514 let sqlite_code = match &error {
515 rusqlite::Error::SqliteFailure(failure, _) => Some(failure.extended_code),
516 _ => None,
517 };
518 match sqlite_code.map(|code| code & 0xff) {
519 Some(11 | 26) => Self {
520 code: Some("client.storage_corrupt"),
521 sqlite_code,
522 message: "local SQLite storage is corrupt".to_owned(),
523 },
524 Some(10) => Self {
525 code: Some("client.storage_io"),
526 sqlite_code,
527 message: "local SQLite storage I/O failed".to_owned(),
528 },
529 _ => Self {
530 code: None,
531 sqlite_code,
532 message: error.to_string(),
533 },
534 }
535 }
536}
537
538#[derive(Debug, Clone, Serialize)]
539#[serde(rename_all = "camelCase")]
540pub struct QuerySnapshot {
541 pub revision: String,
542 pub rows: Vec<QueryRow>,
543 pub coverage: CoverageSnapshot,
544}
545
546impl WindowState {
547 #[must_use]
549 pub fn complete(&self, unit: &str) -> bool {
550 self.units.iter().any(|u| u == unit) && !self.pending.iter().any(|u| u == unit)
551 }
552}
553
554#[derive(Debug, Clone)]
556pub enum Mutation {
557 Upsert {
558 table: String,
559 values: Map<String, Value>,
560 base_version: Option<i64>,
561 },
562 Delete {
563 table: String,
564 row_id: String,
565 base_version: Option<i64>,
566 },
567}
568
569#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
570#[serde(rename_all = "camelCase")]
571pub struct SchemaFloor {
572 #[serde(skip_serializing_if = "Option::is_none")]
573 pub required_schema_version: Option<i32>,
574 #[serde(skip_serializing_if = "Option::is_none")]
575 pub latest_schema_version: Option<i32>,
576}
577
578#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
582#[serde(rename_all = "camelCase")]
583pub struct LeaseState {
584 #[serde(skip_serializing_if = "Option::is_none")]
585 pub lease_id: Option<String>,
586 #[serde(skip_serializing_if = "Option::is_none")]
587 pub expires_at_ms: Option<i64>,
588 #[serde(skip_serializing_if = "Option::is_none")]
589 pub error_code: Option<String>,
590}
591
592#[derive(Debug, Clone, Serialize)]
594#[serde(rename_all = "camelCase")]
595pub struct PresencePeer {
596 pub actor_id: String,
597 pub client_id: String,
598 pub doc: serde_json::Value,
599}
600
601#[derive(Debug, Clone, Serialize, Default)]
602#[serde(rename_all = "camelCase")]
603pub struct SyncReport {
604 pub pushed: u32,
605 pub applied: Vec<String>,
606 pub rejected: Vec<String>,
607 pub retryable: Vec<String>,
608 pub conflicts: u32,
609 pub commits_applied: u32,
610 pub segment_rows_applied: u32,
611 pub bootstrapping: Vec<String>,
612 pub resets: Vec<String>,
613 pub revoked: Vec<String>,
614 pub failed: Vec<String>,
615 pub deferred_commits: usize,
616 #[serde(skip_serializing_if = "Option::is_none")]
617 pub schema_floor: Option<SchemaFloor>,
618}
619
620#[derive(Debug, Clone)]
623pub enum SyncOutcome {
624 Ok(SyncReport),
625 Failed {
626 error_code: String,
627 message: String,
628 },
629 RealtimeUnavailable {
634 state: RealtimeState,
635 reason_code: Option<String>,
636 retry_delay_ms: u64,
637 },
638}
639
640impl SyncOutcome {
641 pub fn to_json(&self) -> Value {
642 match self {
643 SyncOutcome::Ok(report) => {
644 let mut map = Map::new();
645 map.insert("ok".to_owned(), Value::Bool(true));
646 map.insert(
647 "report".to_owned(),
648 serde_json::to_value(report).expect("report serializes"),
649 );
650 Value::Object(map)
651 }
652 SyncOutcome::Failed {
653 error_code,
654 message,
655 } => {
656 let mut map = Map::new();
657 map.insert("ok".to_owned(), Value::Bool(false));
658 map.insert("errorCode".to_owned(), Value::from(error_code.clone()));
659 map.insert("message".to_owned(), Value::from(message.clone()));
660 Value::Object(map)
661 }
662 SyncOutcome::RealtimeUnavailable {
663 state,
664 reason_code,
665 retry_delay_ms,
666 } => {
667 let mut map = Map::new();
668 map.insert("ok".to_owned(), Value::Bool(false));
669 map.insert(
670 "errorCode".to_owned(),
671 Value::from(REALTIME_UNAVAILABLE_CODE),
672 );
673 map.insert(
674 "message".to_owned(),
675 Value::from("realtime is required and the realtime socket is not connected"),
676 );
677 map.insert(
678 "realtimeState".to_owned(),
679 serde_json::to_value(state).expect("state serializes"),
680 );
681 if let Some(reason_code) = reason_code {
682 map.insert(
683 "realtimeReasonCode".to_owned(),
684 Value::from(reason_code.clone()),
685 );
686 }
687 map.insert("retryDelayMs".to_owned(), Value::from(*retry_delay_ms));
688 Value::Object(map)
689 }
690 }
691 }
692}
693
694#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
695#[serde(rename_all = "camelCase")]
696pub struct ConflictRecord {
697 pub client_commit_id: String,
698 pub op_index: i32,
699 pub table: String,
700 pub row_id: String,
701 pub code: String,
702 pub message: String,
703 pub server_version: i64,
704 pub server_row: Map<String, Value>,
707 #[serde(default, skip_serializing_if = "Vec::is_empty")]
712 pub conflict_columns: Vec<String>,
713 #[serde(skip_serializing_if = "Option::is_none")]
714 pub operation: Option<CommitOperation>,
715}
716
717#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
720#[serde(rename_all = "camelCase", deny_unknown_fields)]
721pub struct RejectionDetails {
722 #[serde(skip_serializing_if = "Option::is_none")]
723 pub field_paths: Option<Vec<String>>,
724 #[serde(skip_serializing_if = "Option::is_none")]
725 pub reason: Option<String>,
726 #[serde(skip_serializing_if = "Option::is_none")]
727 pub required_action: Option<String>,
728 #[serde(skip_serializing_if = "Option::is_none")]
729 pub references: Option<BTreeMap<String, String>>,
730}
731
732impl RejectionDetails {
733 pub(crate) fn parse(raw: &str) -> Result<Self, String> {
734 if raw.len() > 4_096 {
735 return Err("rejection details exceed 4096 encoded bytes".to_owned());
736 }
737 let details: Self = serde_json::from_str(raw)
738 .map_err(|error| format!("invalid rejection details: {error}"))?;
739 details.validate()?;
740 Ok(details)
741 }
742
743 fn validate(&self) -> Result<(), String> {
744 let mut members = 0;
745 if let Some(paths) = &self.field_paths {
746 members += 1;
747 if paths.is_empty() || paths.len() > 32 {
748 return Err("fieldPaths must contain 1-32 paths".to_owned());
749 }
750 let mut seen = std::collections::BTreeSet::new();
751 for path in paths {
752 if path.len() > 160 || !path.split('.').all(valid_identifier) || !seen.insert(path)
753 {
754 return Err("fieldPaths contains an invalid or duplicate path".to_owned());
755 }
756 }
757 }
758 if let Some(reason) = &self.reason {
759 members += 1;
760 if !valid_token(reason, 96) {
761 return Err("reason must be a lowercase stable token".to_owned());
762 }
763 }
764 if let Some(action) = &self.required_action {
765 members += 1;
766 if !valid_token(action, 96) {
767 return Err("requiredAction must be a lowercase stable token".to_owned());
768 }
769 }
770 if let Some(references) = &self.references {
771 members += 1;
772 if references.is_empty() || references.len() > 16 {
773 return Err("references must contain 1-16 entries".to_owned());
774 }
775 for (key, value) in references {
776 if !valid_token(key, 64)
777 || value.is_empty()
778 || value.len() > 256
779 || value.trim() != value
780 || value.chars().any(char::is_control)
781 {
782 return Err("references contains an invalid key or value".to_owned());
783 }
784 }
785 }
786 if members == 0 {
787 return Err("rejection details must not be empty".to_owned());
788 }
789 Ok(())
790 }
791}
792
793fn valid_identifier(segment: &str) -> bool {
794 let mut chars = segment.chars();
795 matches!(chars.next(), Some(first) if first == '_' || first.is_ascii_alphabetic())
796 && chars.all(|character| character == '_' || character.is_ascii_alphanumeric())
797}
798
799fn valid_token(token: &str, max: usize) -> bool {
800 if token.is_empty() || token.len() > max || !token.starts_with(|c: char| c.is_ascii_lowercase())
801 {
802 return false;
803 }
804 let mut previous_separator = false;
805 for character in token.chars() {
806 if character.is_ascii_lowercase() || character.is_ascii_digit() {
807 previous_separator = false;
808 } else if matches!(character, '.' | '_' | '-') && !previous_separator {
809 previous_separator = true;
810 } else {
811 return false;
812 }
813 }
814 !previous_separator
815}
816
817#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
818#[serde(rename_all = "camelCase")]
819pub struct RejectionRecord {
820 pub client_commit_id: String,
821 pub op_index: i32,
822 pub code: String,
823 pub message: String,
824 pub retryable: bool,
825 #[serde(skip_serializing_if = "Option::is_none")]
826 pub details: Option<RejectionDetails>,
827 #[serde(skip_serializing_if = "Option::is_none")]
828 pub operation: Option<CommitOperation>,
829}
830
831#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
833#[serde(rename_all = "camelCase")]
834pub struct CommitOperation {
835 pub table: String,
836 pub row_id: String,
837 pub op: String,
838 #[serde(skip_serializing_if = "Option::is_none")]
839 pub base_version: Option<i64>,
840 #[serde(skip_serializing_if = "Option::is_none")]
841 pub values: Option<Map<String, Value>>,
842}
843
844#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
845#[serde(rename_all = "snake_case")]
846pub enum CommitOutcomeStatus {
847 Applied,
848 Cached,
849 Conflict,
850 Rejected,
851}
852
853#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
854#[serde(rename_all = "snake_case")]
855pub enum CommitOutcomeResolution {
856 Active,
857 ResolvedKeepServer,
858 Superseded,
859 Dismissed,
860}
861
862#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
863#[serde(tag = "status", rename_all = "snake_case")]
864pub enum CommitOperationOutcome {
865 Applied {
866 #[serde(rename = "opIndex")]
867 op_index: i32,
868 },
869 Conflict {
870 conflict: ConflictRecord,
871 },
872 Error {
873 rejection: RejectionRecord,
874 },
875}
876
877#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
878#[serde(rename_all = "camelCase")]
879pub struct CommitOutcome {
880 pub sequence: i64,
881 pub client_commit_id: String,
882 pub status: CommitOutcomeStatus,
883 pub recorded_at_ms: i64,
884 pub results: Vec<CommitOperationOutcome>,
885 #[serde(skip_serializing_if = "Option::is_none")]
888 pub operations: Option<Vec<CommitOperation>>,
889 pub resolution: CommitOutcomeResolution,
890 #[serde(skip_serializing_if = "Option::is_none")]
891 pub resolved_at_ms: Option<i64>,
892 #[serde(skip_serializing_if = "Option::is_none")]
893 pub replacement_client_commit_id: Option<String>,
894}
895
896#[derive(Debug, Clone, Deserialize, Default)]
897#[serde(rename_all = "camelCase")]
898pub struct CommitOutcomeQuery {
899 pub limit: Option<usize>,
900 #[serde(default)]
901 pub active_only: bool,
902}
903
904#[derive(Debug, Clone, Deserialize)]
905#[serde(rename_all = "camelCase")]
906pub struct ResolveCommitOutcomeInput {
907 pub client_commit_id: String,
908 pub resolution: CommitOutcomeResolution,
909 pub replacement_client_commit_id: Option<String>,
910}
911
912#[derive(Debug, Clone, Serialize)]
913#[serde(rename_all = "camelCase")]
914pub struct RowState {
915 pub row_id: String,
916 pub version: i64,
919 pub values: Map<String, Value>,
920}
921
922#[derive(Debug, Clone, Serialize)]
923#[serde(rename_all = "camelCase")]
924pub struct SubscriptionStateView {
925 pub id: String,
926 pub table: String,
927 pub status: String,
929 pub cursor: i64,
930 pub has_resume_token: bool,
931 #[serde(skip_serializing_if = "Option::is_none")]
932 pub effective_scopes: Option<Value>,
933 #[serde(skip_serializing_if = "Option::is_none")]
934 pub reason_code: Option<String>,
935}
936
937#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
941#[serde(rename_all = "camelCase", deny_unknown_fields)]
942pub struct LocalDataPurgeTarget {
943 pub table: String,
944 pub selectors: BTreeMap<String, Vec<String>>,
945}
946
947#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
950#[serde(rename_all = "camelCase", deny_unknown_fields)]
951pub struct LocalDataPurgeInput {
952 pub purge_id: String,
953 pub targets: Vec<LocalDataPurgeTarget>,
954}
955
956#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
958#[serde(rename_all = "camelCase")]
959pub struct LocalDataPurgeResult {
960 pub already_applied: bool,
961 pub purged_rows: usize,
962 pub dropped_commits: usize,
963}
964
965#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
967#[serde(rename_all = "camelCase", deny_unknown_fields)]
968pub struct LocalDataRebootstrapInput {
969 pub rebootstrap_id: String,
970}
971
972#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
974#[serde(rename_all = "camelCase")]
975pub struct LocalDataRebootstrapResult {
976 pub already_applied: bool,
977 pub retained_commits: usize,
978 pub reset_subscriptions: usize,
979}
980
981#[derive(Debug, Clone, Default)]
983pub struct ClientLimits {
984 pub limit_commits: Option<i32>,
985 pub limit_snapshot_rows: Option<i32>,
986 pub max_snapshot_pages: Option<i32>,
987 pub accept: Option<u8>,
990 pub blob_cache_max_bytes: Option<i64>,
995 pub outcome_retention_max_entries: Option<usize>,
998 pub previous_version_context: Option<PreviousVersionContextConfig>,
1002}