Skip to main content

rightkit_sync/helper/
wire.rs

1//! Line-JSON wire format of the `rightkit-sync-helper/1` protocol. One JSON
2//! object per line, UTF-8, no other framing. See `API.md` section 4.
3
4use std::collections::BTreeMap;
5
6use serde::{Deserialize, Serialize};
7use serde_json::{Map, Value};
8
9use crate::error::SyncError;
10use crate::record::{FieldValue, RawRecord};
11
12pub const PROTOCOL_VERSION: u32 = 1;
13
14/// Standard base64 (RFC 4648, padded). Tokens and byte fields cross the wire
15/// as base64 text. Kept in-crate on purpose: no workspace crate owns base64, and `rightkit-credentials`
16/// and `rightkit-tauri-shell` carry their own small copies; the next owner of a shared helper replaces all three.
17pub fn b64_encode(bytes: &[u8]) -> String {
18    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
20    for c in bytes.chunks(3) {
21        let n = (u32::from(c[0]) << 16)
22            | (u32::from(*c.get(1).unwrap_or(&0)) << 8)
23            | u32::from(*c.get(2).unwrap_or(&0));
24        out.push(T[(n >> 18) as usize & 63] as char);
25        out.push(T[(n >> 12) as usize & 63] as char);
26        out.push(if c.len() > 1 {
27            T[(n >> 6) as usize & 63] as char
28        } else {
29            '='
30        });
31        out.push(if c.len() > 2 {
32            T[n as usize & 63] as char
33        } else {
34            '='
35        });
36    }
37    out
38}
39
40pub fn b64_decode(text: &str) -> Result<Vec<u8>, String> {
41    let mut out = Vec::with_capacity(text.len() / 4 * 3);
42    let (mut acc, mut bits) = (0u32, 0u32);
43    for ch in text.bytes() {
44        let v = match ch {
45            b'A'..=b'Z' => ch - b'A',
46            b'a'..=b'z' => ch - b'a' + 26,
47            b'0'..=b'9' => ch - b'0' + 52,
48            b'+' => 62,
49            b'/' => 63,
50            b'=' => break,
51            b'\n' | b'\r' | b' ' => continue,
52            _ => return Err(format!("invalid base64 byte 0x{ch:02x}")),
53        };
54        acc = (acc << 6) | u32::from(v);
55        bits += 6;
56        if bits >= 8 {
57            bits -= 8;
58            out.push((acc >> bits) as u8);
59            acc &= (1 << bits) - 1;
60        }
61    }
62    Ok(out)
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(tag = "t", content = "v", rename_all = "lowercase")]
67pub enum WireValue {
68    Text(String),
69    I64(i64),
70    F64(f64),
71    /// Unix epoch milliseconds.
72    Date(i64),
73    /// Base64 bytes; a CKAsset on the CloudKit side.
74    Bytes(String),
75    Strings(Vec<String>),
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
79pub struct WireRecord {
80    #[serde(rename = "type")]
81    pub record_type: String,
82    pub name: String,
83    #[serde(default)]
84    pub fields: BTreeMap<String, WireValue>,
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub modified_ms: Option<i64>,
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub created_ms: Option<i64>,
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub change_tag: Option<String>,
91}
92
93impl From<&RawRecord> for WireRecord {
94    fn from(r: &RawRecord) -> Self {
95        let fields = r
96            .fields
97            .iter()
98            .map(|(k, v)| {
99                let w = match v {
100                    FieldValue::Text(s) => WireValue::Text(s.clone()),
101                    FieldValue::I64(n) => WireValue::I64(*n),
102                    FieldValue::F64(n) => WireValue::F64(*n),
103                    FieldValue::Date(n) => WireValue::Date(*n),
104                    FieldValue::Bytes(b) => WireValue::Bytes(b64_encode(b)),
105                    FieldValue::Strings(s) => WireValue::Strings(s.clone()),
106                };
107                (k.clone(), w)
108            })
109            .collect();
110        Self {
111            record_type: r.record_type.clone(),
112            name: r.record_name.clone(),
113            fields,
114            modified_ms: r.modified_ms,
115            created_ms: r.created_ms,
116            change_tag: r.change_tag.clone(),
117        }
118    }
119}
120
121impl WireRecord {
122    pub fn into_raw(self) -> Result<RawRecord, String> {
123        let mut fields = BTreeMap::new();
124        for (k, v) in self.fields {
125            let f = match v {
126                WireValue::Text(s) => FieldValue::Text(s),
127                WireValue::I64(n) => FieldValue::I64(n),
128                WireValue::F64(n) => FieldValue::F64(n),
129                WireValue::Date(n) => FieldValue::Date(n),
130                WireValue::Bytes(b) => {
131                    FieldValue::Bytes(b64_decode(&b).map_err(|e| format!("field {k}: {e}"))?)
132                }
133                WireValue::Strings(s) => FieldValue::Strings(s),
134            };
135            fields.insert(k, f);
136        }
137        Ok(RawRecord {
138            record_type: self.record_type,
139            record_name: self.name,
140            fields,
141            modified_ms: self.modified_ms,
142            created_ms: self.created_ms,
143            change_tag: self.change_tag,
144        })
145    }
146}
147
148/// Error kinds a helper reports. Anything unknown is treated as transient.
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct WireError {
151    pub kind: String,
152    #[serde(default)]
153    pub message: String,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub retry_after_secs: Option<f64>,
156}
157
158impl WireError {
159    pub fn new(kind: &str, message: impl Into<String>, retry_after_secs: Option<f64>) -> Self {
160        Self {
161            kind: kind.to_string(),
162            message: message.into(),
163            retry_after_secs,
164        }
165    }
166
167    pub fn into_sync_error(self) -> SyncError {
168        let hint = self.retry_after_secs.filter(|s| s.is_finite() && *s > 0.0);
169        match self.kind.as_str() {
170            "unavailable" | "not_authenticated" | "permission_denied" | "quota_exceeded" => {
171                SyncError::Unavailable(self.message)
172            }
173            "token_expired" => SyncError::TokenExpired,
174            "zone_missing" => SyncError::ZoneMissing,
175            "scope_changed" => SyncError::Cancelled,
176            "conflict" => SyncError::Conflict,
177            "retry_after" | "network" | "busy" => SyncError::RetryAfter {
178                secs: hint.unwrap_or(if self.kind == "network" { 15.0 } else { 30.0 }),
179                detail: self.message,
180            },
181            _ => match hint {
182                Some(secs) => SyncError::RetryAfter {
183                    secs,
184                    detail: self.message,
185                },
186                None => SyncError::Transient(self.message),
187            },
188        }
189    }
190
191    pub fn from_sync_error(e: &SyncError) -> Self {
192        match e {
193            SyncError::Unavailable(m) => Self::new("unavailable", m.clone(), None),
194            SyncError::RetryAfter { secs, detail } => {
195                Self::new("retry_after", detail.clone(), Some(*secs))
196            }
197            SyncError::TokenExpired => Self::new("token_expired", "change token expired", None),
198            SyncError::ZoneMissing => Self::new("zone_missing", "zone missing", None),
199            SyncError::Cancelled => Self::new("scope_changed", "account scope changed", None),
200            SyncError::Conflict => Self::new("conflict", "server record changed", None),
201            other => Self::new("transient", other.to_string(), None),
202        }
203    }
204}
205
206/// One response line. `rest` holds the command-specific members.
207#[derive(Debug, Clone, Deserialize)]
208pub struct Response {
209    pub id: u64,
210    pub ok: bool,
211    #[serde(default)]
212    pub error: Option<WireError>,
213    #[serde(flatten)]
214    pub rest: Map<String, Value>,
215}
216
217/// One request line as the helper sees it.
218#[derive(Debug, Clone, Deserialize)]
219pub struct Request {
220    #[serde(default)]
221    pub v: u32,
222    pub id: u64,
223    pub cmd: String,
224    #[serde(flatten)]
225    pub params: Map<String, Value>,
226}
227
228pub fn ok_line(id: u64, mut body: Map<String, Value>) -> String {
229    body.insert("id".into(), id.into());
230    body.insert("ok".into(), true.into());
231    Value::Object(body).to_string()
232}
233
234pub fn err_line(id: u64, error: &WireError) -> String {
235    let mut m = Map::new();
236    m.insert("id".into(), id.into());
237    m.insert("ok".into(), false.into());
238    m.insert(
239        "error".into(),
240        serde_json::to_value(error).unwrap_or(Value::Null),
241    );
242    Value::Object(m).to_string()
243}