Skip to main content

che_sync_protocol/
lib.rs

1//! Versioned, backend-independent synchronization messages.
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4use time::OffsetDateTime;
5use uuid::Uuid;
6
7pub mod model_log;
8pub mod object_log;
9
10pub const PROTOCOL_VERSION: u32 = 1;
11
12/// Tagged values preserve types across JSON and between SQLite and PostgreSQL.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14#[serde(tag = "type", content = "value", rename_all = "snake_case")]
15pub enum Value {
16    Integer(#[serde(with = "decimal_i64")] i64),
17    Real(f64),
18    Text(String),
19    Binary(Vec<u8>),
20    Boolean(bool),
21    DateTime(OffsetDateTime),
22    Uuid(Uuid),
23    Null,
24}
25
26pub type Record = BTreeMap<String, Value>;
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29pub struct Entity {
30    pub model: String,
31    pub id: Uuid,
32    pub schema_version: u32,
33    #[serde(with = "decimal_i64")]
34    pub revision: i64,
35    #[serde(default)]
36    pub epoch: Option<Uuid>,
37    #[serde(default, with = "time::serde::rfc3339::option")]
38    pub updated_at: Option<OffsetDateTime>,
39    #[serde(default, with = "time::serde::rfc3339::option")]
40    pub deleted_at: Option<OffsetDateTime>,
41    /// None at a positive revision is a tombstone. Revision zero with None
42    /// means this UUID has never been recorded by the server.
43    pub record: Option<Record>,
44}
45
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub struct Mutation {
48    pub model: String,
49    pub id: Uuid,
50    pub schema_version: u32,
51    #[serde(with = "decimal_i64")]
52    pub base_revision: i64,
53    /// None deletes the entity. Some contains a writable-field patch;
54    /// at revision zero it creates an entity.
55    pub changes: Option<Record>,
56}
57
58/// A group is atomic. Its contents must not change when retried.
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub struct Operation {
61    pub id: Uuid,
62    pub mutations: Vec<Mutation>,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct PushRequest {
67    pub protocol_version: u32,
68    pub scope: String,
69    pub replica_id: Uuid,
70    pub operation: Operation,
71}
72
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
74#[serde(tag = "status", content = "data", rename_all = "snake_case")]
75pub enum PushResult {
76    Accepted(Vec<Entity>),
77    Conflict(Vec<Entity>),
78    Rejected { reason: String },
79}
80
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub struct Cursor {
83    pub scope: String,
84    /// None is the whole-scope feed; Some selects a model and its FK parents.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub model: Option<String>,
87    /// Persistent server-history identity retained for compatibility. Changing
88    /// it is a server replacement, not a supported client recovery operation.
89    pub epoch: Uuid,
90    #[serde(with = "decimal_i64")]
91    pub sequence: i64,
92}
93
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95pub struct ChangeGroup {
96    #[serde(with = "decimal_i64")]
97    pub sequence: i64,
98    pub entities: Vec<Entity>,
99}
100
101/// Emit decimal strings for JavaScript-safe transport. Read legacy integer
102/// tokens as well so durable journals, receipts and outboxes remain readable.
103mod decimal_i64 {
104    use serde::{Deserialize, Deserializer, Serializer, de::Error};
105
106    pub fn serialize<S: Serializer>(value: &i64, serializer: S) -> Result<S::Ok, S::Error> {
107        serializer.serialize_str(&value.to_string())
108    }
109
110    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
111        #[derive(Deserialize)]
112        #[serde(untagged)]
113        enum Decimal {
114            String(String),
115            Integer(i64),
116        }
117        match Decimal::deserialize(deserializer)? {
118            Decimal::String(value) => value.parse().map_err(D::Error::custom),
119            Decimal::Integer(value) => Ok(value),
120        }
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127
128    #[test]
129    fn integers_use_lossless_decimal_strings_and_read_legacy_numbers() {
130        for value in [i64::MIN, i64::MAX, 9_007_199_254_740_993] {
131            let encoded = serde_json::to_value(Value::Integer(value)).unwrap();
132            assert_eq!(encoded["value"], value.to_string());
133            assert_eq!(
134                serde_json::from_value::<Value>(encoded).unwrap(),
135                Value::Integer(value)
136            );
137        }
138        assert_eq!(
139            serde_json::from_str::<Value>(r#"{"type":"integer","value":42}"#).unwrap(),
140            Value::Integer(42)
141        );
142        let cursor = Cursor {
143            scope: "scope".into(),
144            model: None,
145            epoch: Uuid::nil(),
146            sequence: i64::MAX,
147        };
148        let json = serde_json::to_value(&cursor).unwrap();
149        assert_eq!(json["sequence"], i64::MAX.to_string());
150        assert_eq!(serde_json::from_value::<Cursor>(json).unwrap(), cursor);
151    }
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155pub struct PullRequest {
156    pub protocol_version: u32,
157    /// None requests the initial/recovery full load through the same endpoint.
158    pub cursor: Option<Cursor>,
159    /// Number of atomic groups, not individual entities.
160    pub limit: u32,
161}
162
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164#[serde(tag = "status", content = "data", rename_all = "snake_case")]
165pub enum PullResult {
166    Full(Snapshot),
167    Changes {
168        groups: Vec<ChangeGroup>,
169        cursor: Cursor,
170        has_more: bool,
171    },
172    /// Journal cursor expired in the same server history. Load a snapshot;
173    /// retain pending operation identities and their idempotent retry semantics.
174    ResetRequired,
175}
176
177/// A single consistent snapshot. Transports may stream this message, but must
178/// preserve its snapshot boundary; independent live-table pages are not safe.
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
180pub struct Snapshot {
181    pub entities: Vec<Entity>,
182    pub cursor: Cursor,
183}
184
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub struct Conflict {
187    pub model: String,
188    pub id: Uuid,
189    pub base: Option<Record>,
190    pub local: Option<Record>,
191    pub remote: Entity,
192    pub fields: Vec<String>,
193    pub reason: Option<String>,
194    /// Visible reconciliation was blocked by a constraint, not a competing
195    /// field edit or server rejection. It may retry when dependencies are ready.
196    #[serde(default)]
197    pub retryable: bool,
198    /// Canonical anchor for a deferred accepted write. `base` is its sent
199    /// state; newer remote revisions are merged against this acknowledgement.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub acknowledgement: Option<Entity>,
202}