surmux 0.2.0

极简 SurrealDB WebSocket 客户端 — 单连接 JSON-RPC 多路复用, 极简依赖
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! CBOR Tag adapter — typed path 兼容 SurrealDB 自定义 CBOR Tag.
//!
//! ## 用法
//!
//! ```rust,ignore
//! use surmux::serde_compat::{cbor_record_id, cbor_datetime, cbor_uuid};
//!
//! #[derive(Deserialize)]
//! struct User {
//!     #[serde(with = "cbor_record_id")]
//!     id: RecordId,                              // Tag 8
//!     #[serde(with = "cbor_datetime")]
//!     created_at: chrono::DateTime<chrono::Utc>, // Tag 0 / Tag 12
//!     #[serde(with = "cbor_uuid")]
//!     session_id: uuid::Uuid,                    // Tag 9 / Tag 37
//! }
//!
//! let users: Vec<User> = client.query("SELECT * FROM user").all_typed().await?;
//! ```
//!
//! ## CBOR Tag 表 (来自 surrealdb src/rpc/format/cbor/convert.rs)
//!
//! | Tag | 类型       | 内部 wire                     |
//! |-----|-----------|-------------------------------|
//! | 6   | None      | `Null`                         |
//! | 7   | Table     | `Text("name")`                 |
//! | 8   | RecordId  | `Text("t:k")` 或 `Array[t,k]`  |
//! | 9   | UUID      | `Text(uuid-string)`            |
//! | 12  | Datetime  | `Array[i64 secs, u32 nanos]`   |
//! | 37  | UUID      | `Bytes(16)`                    |

use std::fmt;

use ciborium::tag::Captured;
use ciborium::value::Value as CborValue;
use serde::de::Error as DeError;
use serde::ser::Error as SerError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

// ============================================================
// CborValue → serde_json::Value (RecordId 复杂 key 用)
// ============================================================

fn cbor_to_json(v: CborValue) -> serde_json::Value {
    match v {
        CborValue::Null => serde_json::Value::Null,
        CborValue::Bool(b) => serde_json::Value::Bool(b),
        CborValue::Integer(i) => serde_json::Value::Number(
            i64::try_from(i).map(Into::into).unwrap_or_else(|_| {
                u64::try_from(i).map(Into::into).unwrap_or_else(|_| 0.into())
            }),
        ),
        CborValue::Float(f) => serde_json::Number::from_f64(f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        CborValue::Text(s) => serde_json::Value::String(s),
        CborValue::Bytes(b) => serde_json::Value::String(format!(
            "0x{}",
            b.iter().map(|x| format!("{x:02x}")).collect::<String>()
        )),
        CborValue::Array(a) => serde_json::Value::Array(a.into_iter().map(cbor_to_json).collect()),
        CborValue::Map(m) => {
            let mut obj = serde_json::Map::new();
            for (k, v) in m {
                let ks = match k {
                    CborValue::Text(s) => s,
                    CborValue::Integer(i) => i128::from(i).to_string(),
                    _ => continue,
                };
                obj.insert(ks, cbor_to_json(v));
            }
            serde_json::Value::Object(obj)
        }
        CborValue::Tag(_, inner) => cbor_to_json(*inner),
        _ => serde_json::Value::Null,
    }
}

// ============================================================
// RecordId (Tag 8)
// ============================================================

/// `(table, key)`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RecordId(pub String, pub RecordIdKey);

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RecordIdKey {
    String(String),
    Number(i64),
    Object(serde_json::Value),
    Array(serde_json::Value),
}

impl RecordId {
    pub fn new(table: impl Into<String>, key: impl Into<String>) -> Self {
        Self(table.into(), RecordIdKey::String(key.into()))
    }
    pub fn as_str(&self) -> String {
        match &self.1 {
            RecordIdKey::String(k) => format!("{}:{}", self.0, k),
            RecordIdKey::Number(n) => format!("{}:{}", self.0, n),
            _ => format!("{}:<complex>", self.0),
        }
    }
}

impl fmt::Display for RecordId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.as_str())
    }
}

impl Serialize for RecordId {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        // 序列化为 `t:k` 文本形式, 兼容 SurrealDB 的 string-typed RecordId.
        // 复杂 key (Object/Array) 不能反序, 用 as_str 的 `<complex>` 退化形式.
        s.serialize_str(&self.as_str())
    }
}

/// 供 `#[serde(with = "cbor_record_id")]` 用. CBOR typed path 通过 Captured 内 enum hack
/// 自动解 Tag 8 (ciborium::tag::Captured 内部把 `@@TAG@@` 字符串哨兵转成 `(Option<u64>, CborValue)`).
pub mod cbor_record_id {
    use super::*;

    pub fn deserialize<'de, D>(d: D) -> Result<RecordId, D::Error>
    where
        D: Deserializer<'de>,
    {
        let c: Captured<CborValue> = Captured::deserialize(d)?;
        match c.0 {
            Some(8) => parse_record_id(c.1).map_err(DeError::custom),
            Some(t) => Err(DeError::custom(format!("expected Tag 8 RecordId, got Tag {t}"))),
            None => Err(DeError::custom("expected Tag 8 RecordId, got untagged")),
        }
    }

    pub fn serialize<S>(_r: &RecordId, _s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Err(SerError::custom("RecordId serialize not supported; use .query().bind()"))
    }
}

/// 直接从 CborValue 解 (CBOR wire 8(...))
pub(crate) fn parse_record_id(v: CborValue) -> Result<RecordId, String> {
    match v {
        CborValue::Text(s) => {
            let (t, k) = s
                .split_once(':')
                .ok_or_else(|| format!("invalid RecordId text: {s}"))?;
            Ok(RecordId(t.into(), RecordIdKey::String(k.into())))
        }
        CborValue::Array(mut a) if a.len() == 2 => {
            let table = match a.remove(0) {
                CborValue::Text(t) => t,
                other => return Err(format!("RecordId table must be text, got {other:?}")),
            };
            let key = match a.remove(0) {
                CborValue::Integer(i) => match i64::try_from(i) {
                    Ok(n) => RecordIdKey::Number(n),
                    // SurrealDB 支持任意大整数 id, 超出 i64 时退化为字符串形式保留原值,
                    // 避免 `unwrap_or(0)` 导致两条不同记录的 id 静默冲突.
                    Err(_) => RecordIdKey::String(i128::from(i).to_string()),
                },
                CborValue::Text(s) => RecordIdKey::String(s),
                CborValue::Map(m) => RecordIdKey::Object(serde_json::Value::Object({
                    let mut obj = serde_json::Map::new();
                    for (k, v) in m {
                        let ks = match k {
                            CborValue::Text(s) => s,
                            CborValue::Integer(i) => i128::from(i).to_string(),
                            _ => continue,
                        };
                        obj.insert(ks, cbor_to_json(v));
                    }
                    obj
                })),
                CborValue::Array(inner) => RecordIdKey::Array(serde_json::Value::Array(
                    inner.into_iter().map(cbor_to_json).collect(),
                )),
                other => return Err(format!("RecordId key type unsupported: {other:?}")),
            };
            Ok(RecordId(table, key))
        }
        other => Err(format!("RecordId expects Text or Array[2], got {other:?}")),
    }
}

// ============================================================
// Datetime (Tag 0 RFC3339 / Tag 12 Array[secs, nanos])
// ============================================================

pub mod cbor_datetime {
    use super::*;

    pub fn deserialize<'de, D>(d: D) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let c: Captured<CborValue> = Captured::deserialize(d)?;
        match c.0 {
            Some(0) => parse_dt_str(c.1).map_err(DeError::custom),
            Some(12) => parse_dt_struct(&c.1).map_err(DeError::custom),
            Some(t) => Err(D::Error::custom(format!(
                "expected Tag 0/12 Datetime, got Tag {t}"
            ))),
            None => Err(D::Error::custom("expected Datetime Tag, got untagged")),
        }
    }
}

fn parse_dt_str(s: CborValue) -> Result<chrono::DateTime<chrono::Utc>, String> {
    let CborValue::Text(s) = s else {
        return Err(format!("Datetime Tag 0 expects Text, got {s:?}"));
    };
    chrono::DateTime::parse_from_rfc3339(&s)
        .map(|dt| dt.with_timezone(&chrono::Utc))
        .map_err(|e| format!("invalid RFC3339: {e}"))
}

fn parse_dt_struct(v: &CborValue) -> Result<chrono::DateTime<chrono::Utc>, String> {
    let CborValue::Array(a) = v else {
        return Err(format!("Datetime Tag 12 expects Array, got {v:?}"));
    };
    if a.len() != 2 {
        return Err(format!("Datetime Array must have 2 elements, got {}", a.len()));
    }
    let secs = match &a[0] {
        CborValue::Integer(i) => i64::try_from(*i).map_err(|e| format!("secs overflow: {e}"))?,
        other => return Err(format!("Datetime[0] expects Integer, got {other:?}")),
    };
    let nanos = match &a[1] {
        CborValue::Integer(i) => u32::try_from(*i).map_err(|e| format!("nanos overflow: {e}"))?,
        other => return Err(format!("Datetime[1] expects Integer, got {other:?}")),
    };
    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, nanos)
        .ok_or_else(|| format!("invalid Datetime: secs={secs} nanos={nanos}"))
}

// ============================================================
// UUID (Tag 9 string / Tag 37 bytes(16))
// ============================================================

pub mod cbor_uuid {
    use super::*;

    pub fn deserialize<'de, D>(d: D) -> Result<uuid::Uuid, D::Error>
    where
        D: Deserializer<'de>,
    {
        let c: Captured<CborValue> = Captured::deserialize(d)?;
        match c.0 {
            Some(9) => {
                let CborValue::Text(s) = c.1 else {
                    return Err(DeError::custom("UUID Tag 9 expects Text"));
                };
                uuid::Uuid::parse_str(&s).map_err(DeError::custom)
            }
            Some(37) => {
                let CborValue::Bytes(b) = c.1 else {
                    return Err(DeError::custom("UUID Tag 37 expects Bytes"));
                };
                if b.len() != 16 {
                    return Err(DeError::custom(format!("UUID must be 16 bytes, got {}", b.len())));
                }
                let mut a = [0u8; 16];
                a.copy_from_slice(&b);
                Ok(uuid::Uuid::from_bytes(a))
            }
            Some(t) => Err(DeError::custom(format!("expected Tag 9/37 UUID, got Tag {t}"))),
            None => Err(DeError::custom("expected UUID Tag, got untagged")),
        }
    }
}

// ============================================================
// CborNone (Tag 6) — bare Null 也吃
// ============================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct CborNone;

impl Serialize for CborNone {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_unit()
    }
}

impl<'de> Deserialize<'de> for CborNone {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let c: Captured<CborValue> = Captured::deserialize(d)?;
        match c.0 {
            // Tag 6 内部必须是 Null; 其它内容即使带 Tag 6 也拒绝.
            Some(6) if matches!(c.1, CborValue::Null) => Ok(CborNone),
            Some(6) => Err(D::Error::custom("expected Tag 6 wrapping Null, got non-null inner")),
            Some(t) => Err(D::Error::custom(format!("expected Tag 6 None, got Tag {t}"))),
            // bare Null 也接受 (SurrealDB 某些字段不带 Tag 6 直接发 Null).
            None if matches!(c.1, CborValue::Null) => Ok(CborNone),
            None => Err(D::Error::custom("expected Tag 6 None, got untagged non-null")),
        }
    }
}

pub mod cbor_none {
    use super::*;
    pub fn deserialize<'de, D>(d: D) -> Result<CborNone, D::Error>
    where
        D: Deserializer<'de>,
    {
        CborNone::deserialize(d)
    }
    pub fn serialize<S>(n: &CborNone, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        n.serialize(s)
    }
}

// ============================================================
// 单元测试 — 验证 pack/unpack 路径
// ============================================================

#[cfg(test)]
mod tests {
    use super::*;
    use ciborium::value::Integer;

    fn text(s: &str) -> CborValue { CborValue::Text(s.into()) }
    fn int(n: i64) -> CborValue { CborValue::Integer(Integer::from(n)) }
    fn tag(n: u64, inner: CborValue) -> CborValue {
        CborValue::Tag(n, Box::new(inner))
    }

    /// 直接调 Captured + 解码器路径, 模拟 typed path
    fn de_capture<T, F>(v: CborValue, expected: u64, parse: F) -> Result<T, String>
    where
        F: FnOnce(CborValue) -> Result<T, String>,
    {
        // raw CborValue 解 Captured, 必须以 wire 形式
        let mut buf = Vec::new();
        ciborium::into_writer(&v, &mut buf).unwrap();
        let mut scratch = [0u8; 4096];
        let cap: Captured<CborValue> = ciborium::from_reader_with_buffer(&buf[..], &mut scratch)
            .map_err(|e| format!("{e:?}"))?;
        match cap.0 {
            Some(t) if t == expected => parse(cap.1),
            Some(t) => Err(format!("expected Tag {expected}, got Tag {t}")),
            None => Err(format!("expected Tag {expected}, got untagged")),
        }
    }

    #[test]
    fn record_id_via_parse() {
        // 短文本
        let r = de_capture(tag(8, text("user:alice")), 8, parse_record_id).unwrap();
        assert_eq!(r, RecordId::new("user", "alice"));

        // array text
        let r = de_capture(
            tag(8, CborValue::Array(vec![text("user"), text("bob")])),
            8,
            parse_record_id,
        )
        .unwrap();
        assert_eq!(r, RecordId::new("user", "bob"));

        // array number
        let r = de_capture(
            tag(8, CborValue::Array(vec![text("user"), int(42)])),
            8,
            parse_record_id,
        )
        .unwrap();
        assert_eq!(r, RecordId("user".into(), RecordIdKey::Number(42)));

        // 错误表单
        assert!(parse_record_id(text("no_colon")).is_err());
        assert!(parse_record_id(int(123)).is_err());
    }

    #[test]
    fn datetime_via_capture() {
        // Tag 12 struct
        let v = tag(12, CborValue::Array(vec![int(1_752_600_000), int(0)]));
        let dt = de_capture(v, 12, |inner| parse_dt_struct(&inner)).unwrap();
        assert_eq!(dt.timestamp(), 1_752_600_000);

        // Tag 0 rfc3339
        let v = tag(0, text("2026-07-16T10:00:00Z"));
        let dt = de_capture(v, 0, parse_dt_str).unwrap();
        assert_eq!(dt.to_rfc3339(), "2026-07-16T10:00:00+00:00");
    }

    #[test]
    fn uuid_via_capture() {
        let s = "550e8400-e29b-41d4-a716-446655440000";
        let v = tag(9, text(s));
        let u = de_capture(v, 9, |inner| {
            let CborValue::Text(s) = inner else {
                return Err("not text".into());
            };
            uuid::Uuid::parse_str(&s).map_err(|e| e.to_string())
        }).unwrap();
        assert_eq!(u.to_string(), s);

        let bytes = b"\x55\x0e\x84\x00\xe2\x9b\x41\xd4\xa7\x16\x44\x66\x55\x44\x00\x00";
        let v = tag(37, CborValue::Bytes(bytes.to_vec()));
        let u = de_capture(v, 37, |inner| {
            let CborValue::Bytes(b) = inner else {
                return Err("not bytes".into());
            };
            if b.len() != 16 { return Err("not 16".into()); }
            let mut a = [0u8; 16];
            a.copy_from_slice(&b);
            Ok(uuid::Uuid::from_bytes(a))
        }).unwrap();
        assert_eq!(u.to_string(), s);
    }

    #[test]
    fn none_via_capture() {
        // Tag 6 + Null
        let mut buf = Vec::new();
        ciborium::into_writer(&tag(6, CborValue::Null), &mut buf).unwrap();
        let mut scratch = [0u8; 256];
        let n: CborNone = ciborium::from_reader_with_buffer(&buf[..], &mut scratch).unwrap();
        assert_eq!(n, CborNone);

        // bare Null → Captured None + Null → CborNone
        let mut buf = Vec::new();
        ciborium::into_writer(&CborValue::Null, &mut buf).unwrap();
        let mut scratch = [0u8; 256];
        let n: CborNone = ciborium::from_reader_with_buffer(&buf[..], &mut scratch).unwrap();
        assert_eq!(n, CborNone);
    }
}