1use 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
14pub 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 Date(i64),
73 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#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct WireError {
153 pub kind: String,
154 #[serde(default)]
155 pub message: String,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub retry_after_secs: Option<f64>,
158}
159
160impl WireError {
161 pub fn new(kind: &str, message: impl Into<String>, retry_after_secs: Option<f64>) -> Self {
162 Self {
163 kind: kind.to_string(),
164 message: message.into(),
165 retry_after_secs,
166 }
167 }
168
169 pub fn into_sync_error(self) -> SyncError {
170 let hint = self.retry_after_secs.filter(|s| s.is_finite() && *s > 0.0);
171 match self.kind.as_str() {
172 "unavailable" | "not_authenticated" | "permission_denied" | "quota_exceeded" => {
173 SyncError::Unavailable(self.message)
174 }
175 "token_expired" => SyncError::TokenExpired,
176 "zone_missing" => SyncError::ZoneMissing,
177 "scope_changed" => SyncError::Cancelled,
178 "conflict" => SyncError::Conflict,
179 "persistence" => SyncError::Persistence(self.message),
180 "retry_after" | "network" | "busy" => SyncError::RetryAfter {
181 secs: hint.unwrap_or(if self.kind == "network" { 15.0 } else { 30.0 }),
182 detail: self.message,
183 },
184 _ => match hint {
185 Some(secs) => SyncError::RetryAfter {
186 secs,
187 detail: self.message,
188 },
189 None => SyncError::Transient(self.message),
190 },
191 }
192 }
193
194 pub fn from_sync_error(e: &SyncError) -> Self {
195 match e {
196 SyncError::Unavailable(m) => Self::new("unavailable", m.clone(), None),
197 SyncError::RetryAfter { secs, detail } => {
198 Self::new("retry_after", detail.clone(), Some(*secs))
199 }
200 SyncError::TokenExpired => Self::new("token_expired", "change token expired", None),
201 SyncError::ZoneMissing => Self::new("zone_missing", "zone missing", None),
202 SyncError::Cancelled => Self::new("scope_changed", "account scope changed", None),
203 SyncError::Conflict => Self::new("conflict", "server record changed", None),
204 SyncError::Persistence(m) => Self::new("persistence", m.clone(), None),
205 other => Self::new("transient", other.to_string(), None),
206 }
207 }
208}
209
210#[derive(Debug, Clone, Deserialize)]
212pub struct Response {
213 pub id: u64,
214 pub ok: bool,
215 #[serde(default)]
216 pub error: Option<WireError>,
217 #[serde(flatten)]
218 pub rest: Map<String, Value>,
219}
220
221#[derive(Debug, Clone, Deserialize)]
223pub struct Request {
224 #[serde(default)]
225 pub v: u32,
226 pub id: u64,
227 pub cmd: String,
228 #[serde(flatten)]
229 pub params: Map<String, Value>,
230}
231
232pub fn ok_line(id: u64, mut body: Map<String, Value>) -> String {
233 body.insert("id".into(), id.into());
234 body.insert("ok".into(), true.into());
235 Value::Object(body).to_string()
236}
237
238pub fn err_line(id: u64, error: &WireError) -> String {
239 let mut m = Map::new();
240 m.insert("id".into(), id.into());
241 m.insert("ok".into(), false.into());
242 m.insert(
243 "error".into(),
244 serde_json::to_value(error).unwrap_or(Value::Null),
245 );
246 Value::Object(m).to_string()
247}