kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! The wire format (PROTOCOL.md §4, and §17 for protocol 2): hand-written
//! serde types, checked against the shared golden fixtures
//! (`packages/protocol/testdata/frames`).
//!
//! Protocol 2 (ADR 0021 §5) authenticates the socket with a `hello` that
//! names no space, answers with `welcome`, and then carries any number of
//! subscriptions (`subscribe` / `result` / `changes` / `unsubscribe`).
//! `mutate`, `ack`, `ping`, `pong` and `error` keep their protocol 1 shapes,
//! plus the atomic-batch fields (§6.1).
//!
//! Unknown properties are ignored on input, as the protocol requires.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::error::{Error, Result};
use crate::hlc::Hlc;

pub const PROTOCOL_VERSION: u32 = 1;
/// Protocol 2: one socket, many subscriptions (ADR 0021 §5).
pub const PROTOCOL_V2: u32 = 2;
/// The system table of a space's end users (ADR 0021 §2.5). Only protocol 2
/// subscriptions whose query reads it carry its rows.
pub const USERS_TABLE: &str = "_users";
/// The query of a subscription to the whole space, with protocol 1 semantics.
pub const QUERY_ALL: &str = "*";
/// The message cap, both directions (8 MiB).
pub const MAX_FRAME_BYTES: usize = 8 << 20;
pub const MAX_MUTATIONS_PER_FRAME: usize = 500;

pub type JsonMap = Map<String, Value>;

fn is_false(b: &bool) -> bool {
    !*b
}

/// One column of a table (`TableSchema.columns`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ColumnDef {
    /// `string`, `number`, `boolean`, `datetime`, `json`, `ref` or `file_ref`.
    #[serde(rename = "type")]
    pub ty: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub optional: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_table: Option<String>,
    #[serde(flatten)]
    pub extra: JsonMap,
}

impl ColumnDef {
    pub fn new(ty: &str) -> ColumnDef {
        ColumnDef { ty: ty.to_string(), optional: false, ref_table: None, extra: Map::new() }
    }
    pub fn optional(mut self) -> ColumnDef {
        self.optional = true;
        self
    }
}

pub const COLUMN_TYPES: &[&str] = &["string", "number", "boolean", "datetime", "json", "ref", "file_ref"];

/// A table's schema, as declared in `hello.schema` and sent in snapshots.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TableSchema {
    pub columns: BTreeMap<String, ColumnDef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
    #[serde(flatten)]
    pub extra: JsonMap,
}

/// File metadata in a `file/put` mutation.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileMeta {
    pub path: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub sha256: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<u64>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub mime_type: String,
}

/// A client mutation (PROTOCOL.md §4 mutate).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mutation {
    pub mutation_id: String,
    pub hlc: String,
    /// `record` or `file`.
    pub kind: String,
    /// `upsert`, `delete`, `restore` (records); `put`, `move`, `delete`, `restore` (files).
    pub op: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub table: Option<String>,
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fields: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<FileMeta>,
}

impl Mutation {
    /// The entity this mutation writes: the outbox orders per entity.
    pub fn entity_key(&self) -> String {
        if self.kind == "file" {
            format!("file\u{0}{}", self.id)
        } else {
            format!("record\u{0}{}\u{0}{}", self.table.as_deref().unwrap_or(""), self.id)
        }
    }
}

/// Who made a change.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Actor {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub machine_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_id: Option<String>,
}

/// A file's full state (snapshots, file ops, REST).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileState {
    pub id: String,
    pub path: String,
    #[serde(default)]
    pub sha256: String,
    #[serde(default)]
    pub size_bytes: u64,
    #[serde(default)]
    pub mime_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hlc: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub deleted: bool,
    #[serde(flatten)]
    pub extra: JsonMap,
}

/// A row in a snapshot or a by-ID read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordState {
    pub table: String,
    pub id: String,
    pub fields: JsonMap,
    #[serde(default)]
    pub hlcs: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub deleted: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deleted_hlc: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    #[serde(flatten)]
    pub extra: JsonMap,
}

/// One committed oplog entry (delta and broadcast).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Op {
    pub seq: i64,
    #[serde(default)]
    pub mutation_id: String,
    pub hlc: String,
    pub at: String,
    #[serde(default)]
    pub by: Actor,
    pub kind: String,
    pub op: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub table: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fields: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub file: Option<FileState>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<TableSchema>,
}

/// The `client` property of `hello`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClientInfo {
    pub name: String,
    pub version: String,
    pub platform: String,
}

impl ClientInfo {
    pub fn current() -> ClientInfo {
        ClientInfo { name: "kovlet-rs".into(), version: env!("CARGO_PKG_VERSION").into(), platform: platform().into() }
    }
}

/// The platform name sent in `hello.client`.
pub fn platform() -> &'static str {
    if cfg!(target_os = "ios") {
        "ios"
    } else if cfg!(target_os = "android") {
        "android"
    } else if cfg!(target_os = "macos") {
        "macos"
    } else if cfg!(target_os = "windows") {
        "windows"
    } else if cfg!(target_os = "linux") {
        "linux"
    } else {
        "other"
    }
}

/// `hello`. Protocol 1 names its space and cursor; protocol 2 only
/// authenticates (`space_id` empty, `since_seq` 0, no schema) and may ask a
/// machine session to act as an end user (`as_end_user`, ADR 0021 §2.6).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Hello {
    pub protocol: u32,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub space_id: String,
    #[serde(default)]
    pub since_seq: i64,
    pub token: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_proof: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<BTreeMap<String, TableSchema>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client: Option<ClientInfo>,
    /// Protocol 2: act as this end user (needs the `impersonate` grant flag).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub as_end_user: Option<String>,
}

/// `mutate`. `atomic` with a `batch_id` asks for all or nothing (protocol 2
/// with `welcome.features.atomic`); `params` are values write rules read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mutate {
    pub space_id: String,
    pub mutations: Vec<Mutation>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub atomic: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<JsonMap>,
}

/// What a `files` subscription covers.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FilesScope {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub prefix: String,
}

/// `subscribe` (protocol 2): exactly one of `query` (an object, or `"*"`)
/// and `files`, or neither with a `schema` (a declaration only).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Subscribe {
    pub sub: String,
    pub space_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub files: Option<FilesScope>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub params: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<BTreeMap<String, TableSchema>>,
}

/// `unsubscribe` (protocol 2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Unsubscribe {
    pub sub: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ping {
    pub nonce: String,
}

/// Client-to-server frames.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientFrame {
    Hello(Hello),
    Mutate(Mutate),
    Ping(Ping),
    Subscribe(Subscribe),
    Unsubscribe(Unsubscribe),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Snapshot {
    pub space_id: String,
    pub head_seq: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tables: Option<BTreeMap<String, TableSchema>>,
    #[serde(default)]
    pub records: Vec<RecordState>,
    #[serde(default)]
    pub files: Vec<FileState>,
    #[serde(default)]
    pub complete: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Vec<Value>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delta {
    pub space_id: String,
    pub head_seq: i64,
    #[serde(default)]
    pub complete: bool,
    pub ops: Vec<Op>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Vec<Value>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Broadcast {
    pub space_id: String,
    pub head_seq: i64,
    pub ops: Vec<Op>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorBody {
    pub code: String,
    #[serde(default)]
    pub message: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MutationResult {
    pub mutation_id: String,
    /// `applied`, `duplicate` or `rejected`; `aborted` in an atomic batch
    /// that another mutation's rejection rolled back.
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seq: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorBody>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ack {
    pub space_id: String,
    pub head_seq: i64,
    pub results: Vec<MutationResult>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub warnings: Option<Vec<Value>>,
    /// The answer to an atomic `mutate`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub batch: Option<BatchResult>,
}

/// An atomic batch's fate (`ack.batch`). When `rejected`, the mutation at
/// `failed_index` is `rejected` and every other one `aborted`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchResult {
    pub id: String,
    /// `applied`, `rejected` or `duplicate`.
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failed_index: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorBody>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorFrame {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub space_id: Option<String>,
    /// Protocol 2: the subscription this error ends (the socket stays open).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sub: Option<String>,
    pub code: String,
    #[serde(default)]
    pub message: String,
    #[serde(default)]
    pub retryable: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<JsonMap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Pong {
    pub nonce: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub region: Option<String>,
}

/// Who a protocol 2 session is (`welcome.principal`): `member`, `machine`,
/// `console` or `end_user` (then `end_user_id` is set).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PrincipalInfo {
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_user_id: Option<String>,
}

/// The limits a protocol 2 server applies (`welcome.limits`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Limits {
    #[serde(default)]
    pub max_frame_bytes: u64,
    #[serde(default)]
    pub max_mutations: u64,
    #[serde(default)]
    pub max_subscriptions: u64,
    #[serde(default)]
    pub max_rows_per_subscription: u64,
    #[serde(default)]
    pub ping_interval_ms: u64,
    #[serde(default)]
    pub write_timeout_ms: u64,
}

/// `welcome`: the server accepted a protocol 2 hello. `features` is keyed by
/// feature (`query`, `atomic`, `rooms`); a missing key means "not offered".
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Welcome {
    pub protocol: u32,
    pub principal: PrincipalInfo,
    #[serde(default)]
    pub limits: Limits,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub features: Option<JsonMap>,
}

impl Welcome {
    /// Whether the server takes atomic batches on this session.
    pub fn atomic(&self) -> bool {
        self.features.as_ref().is_some_and(|f| f.get("atomic").is_some_and(|v| !v.is_null()))
    }
}

/// A row that left a subscription.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RemovedRow {
    pub table: String,
    pub id: String,
}

/// `result` (protocol 2): a subscription's initial or resumed state, in
/// pages; the last has `complete`. A full result sends every row in scope;
/// a `resumed` one only rows changed after the cursor, with `ids` (the
/// membership per table) for queries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResultFrame {
    pub sub: String,
    pub space_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tables: Option<BTreeMap<String, TableSchema>>,
    #[serde(default)]
    pub rows: Vec<RecordState>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files: Vec<FileState>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ids: Option<BTreeMap<String, Vec<String>>>,
    #[serde(default, skip_serializing_if = "is_false")]
    pub resumed: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub more: Option<BTreeMap<String, bool>>,
    pub through_seq: i64,
    #[serde(default)]
    pub cursor: String,
    #[serde(default)]
    pub complete: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<Vec<Value>>,
}

/// `changes` (protocol 2): live updates for one subscription. `ops` patch
/// rows it holds (every op in scope for `"*"` and files), `added` rows moved
/// in, `removed` rows moved out.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Changes {
    pub sub: String,
    pub space_id: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ops: Vec<Op>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub added: Vec<RecordState>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub removed: Vec<RemovedRow>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub more: Option<BTreeMap<String, bool>>,
    pub through_seq: i64,
    #[serde(default)]
    pub cursor: String,
}

/// Server-to-client frames. Deserialized by reading `type` and then only
/// the matching frame (see the `Deserialize` impl): serde's internally
/// tagged enums buffer every frame through a second deserializer, which
/// costs mobile binary size (ADR 0017 §1).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerFrame {
    Snapshot(Snapshot),
    Delta(Delta),
    Broadcast(Broadcast),
    Ack(Ack),
    Error(ErrorFrame),
    Pong(Pong),
    Welcome(Welcome),
    Result(ResultFrame),
    Changes(Changes),
}

impl<'de> Deserialize<'de> for ServerFrame {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<ServerFrame, D::Error> {
        use serde::de::Error as _;
        let mut v = Map::<String, Value>::deserialize(d)?;
        let ty = match v.remove("type") {
            Some(Value::String(t)) => t,
            _ => return Err(D::Error::missing_field("type")),
        };
        fn de<T: serde::de::DeserializeOwned, E: serde::de::Error>(v: Map<String, Value>) -> std::result::Result<T, E> {
            serde_json::from_value(Value::Object(v)).map_err(E::custom)
        }
        Ok(match ty.as_str() {
            "snapshot" => ServerFrame::Snapshot(de(v)?),
            "delta" => ServerFrame::Delta(de(v)?),
            "broadcast" => ServerFrame::Broadcast(de(v)?),
            "ack" => ServerFrame::Ack(de(v)?),
            "error" => ServerFrame::Error(de(v)?),
            "pong" => ServerFrame::Pong(de(v)?),
            "welcome" => ServerFrame::Welcome(de(v)?),
            "result" => ServerFrame::Result(de(v)?),
            "changes" => ServerFrame::Changes(de(v)?),
            t => {
                return Err(D::Error::unknown_variant(
                    t,
                    &["snapshot", "delta", "broadcast", "ack", "error", "pong", "welcome", "result", "changes"],
                ))
            }
        })
    }
}

fn invalid(msg: impl Into<String>) -> Error {
    Error::new("invalid_frame", msg)
}

/// An entity id: 1–128 characters of `[A-Za-z0-9_-]`.
pub fn valid_entity_id(s: &str) -> bool {
    !s.is_empty() && s.len() <= 128 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// A record id: 1–256 bytes of UTF-8 with no control characters.
pub fn valid_record_id(s: &str) -> bool {
    !s.is_empty() && s.len() <= 256 && !s.chars().any(|c| (c as u32) < 0x20 || (0x7f..=0x9f).contains(&(c as u32)))
}

/// A table a server row may name: an app table, or a system table
/// (`_users`) that protocol 2 subscriptions reading it carry.
pub fn valid_record_table(s: &str) -> bool {
    valid_identifier(s) || s == USERS_TABLE
}

/// A table or column name: `^[A-Za-z][A-Za-z0-9_]{0,62}$`.
pub fn valid_identifier(s: &str) -> bool {
    let b = s.as_bytes();
    !b.is_empty()
        && b.len() <= 63
        && b[0].is_ascii_alphabetic()
        && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
}

/// A file path: relative, `/`-separated, at most 1024 bytes, no empty, `.` or `..` segments.
pub fn valid_file_path(p: &str) -> bool {
    !p.is_empty()
        && p.len() <= 1024
        && !p.contains('\0')
        && !p.contains('\\')
        && p.split('/').all(|s| !s.is_empty() && s != "." && s != "..")
}

fn valid_sha256(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

impl TableSchema {
    /// The rules a JSON Schema can't express: `order` names every column exactly once.
    pub fn validate(&self, table: &str) -> Result<()> {
        if !valid_identifier(table) {
            return Err(invalid(format!("bad table name {table:?}")));
        }
        for (name, col) in &self.columns {
            if !valid_identifier(name) {
                return Err(invalid(format!("bad column name {table}.{name}")));
            }
            if !COLUMN_TYPES.contains(&col.ty.as_str()) {
                return Err(invalid(format!("unknown column type {:?} for {table}.{name}", col.ty)));
            }
        }
        if let Some(order) = &self.order {
            let mut seen = std::collections::BTreeSet::new();
            for c in order {
                if !self.columns.contains_key(c) || !seen.insert(c) {
                    return Err(invalid(format!("{table}.order must name every column exactly once")));
                }
            }
            if seen.len() != self.columns.len() {
                return Err(invalid(format!("{table}.order must name every column exactly once")));
            }
        }
        Ok(())
    }
}

fn check_hlc(h: &str) -> Result<()> {
    Hlc::parse(h).map(|_| ()).map_err(|_| invalid(format!("bad hlc {h:?}")))
}

impl RecordState {
    /// A row from a protocol 2 frame: a valid table and id, and a stamp per field.
    pub fn validate(&self) -> Result<()> {
        if !valid_record_table(&self.table) || !valid_record_id(&self.id) {
            return Err(invalid(format!("row {}/{} needs a valid table and id", self.table, self.id)));
        }
        for k in self.fields.keys() {
            if !valid_identifier(k) {
                return Err(invalid(format!("bad field name {}.{k}", self.table)));
            }
            match self.hlcs.get(k) {
                Some(h) => check_hlc(h)?,
                None => return Err(invalid(format!("field {}.{k} has no stamp", self.table))),
            }
        }
        if let Some(d) = &self.deleted_hlc {
            check_hlc(d)?;
        }
        Ok(())
    }
}

fn check_tables(tables: Option<&BTreeMap<String, TableSchema>>) -> Result<()> {
    for (name, ts) in tables.into_iter().flatten() {
        ts.validate(name)?;
    }
    Ok(())
}

impl Op {
    pub fn validate(&self) -> Result<()> {
        if self.seq < 1 {
            return Err(invalid("op.seq must be at least 1"));
        }
        check_hlc(&self.hlc)?;
        match (self.kind.as_str(), self.op.as_str()) {
            ("record", "upsert" | "delete" | "restore") => {
                let ok = self.table.as_deref().is_some_and(valid_record_table)
                    && self.id.as_deref().is_some_and(valid_record_id);
                if !ok {
                    return Err(invalid("record ops need a valid table and id"));
                }
            }
            ("file", "put" | "move" | "delete" | "restore") => {
                if self.file.is_none() {
                    return Err(invalid("file op without file"));
                }
            }
            ("schema", "put" | "delete") => {
                if self.table.is_none() {
                    return Err(invalid("schema op without table"));
                }
            }
            (k, o) => return Err(invalid(format!("bad op kind/op {k}/{o}"))),
        }
        Ok(())
    }
}

impl Mutation {
    /// Local validation before a mutation is queued (PROTOCOL.md §4 mutate).
    pub fn validate(&self) -> Result<()> {
        let bad = |code: &str, m: String| Err(Error::new(code, m));
        if !valid_entity_id(&self.mutation_id) {
            return bad("invalid_mutation", format!("bad mutation_id {:?}", self.mutation_id));
        }
        if Hlc::parse(&self.hlc).is_err() {
            return bad("invalid_mutation", format!("bad hlc {:?}", self.hlc));
        }
        match (self.kind.as_str(), self.op.as_str()) {
            ("record", op) => {
                if !valid_record_id(&self.id) {
                    return bad("invalid_id", "record ids are 1–256 bytes of UTF-8 with no control characters".into());
                }
                let Some(t) = &self.table else {
                    return bad("invalid_mutation", "record mutation without table".into());
                };
                if !valid_identifier(t) {
                    return bad("invalid_mutation", format!("bad table name {t:?}"));
                }
                match op {
                    "upsert" => {
                        let Some(f) = &self.fields else {
                            return bad("invalid_mutation", "upsert without fields".into());
                        };
                        if f.is_empty() {
                            return bad("invalid_mutation", "upsert needs at least one field".into());
                        }
                        for k in f.keys() {
                            if !valid_identifier(k) {
                                return bad("invalid_mutation", format!("bad field name {k:?}"));
                            }
                        }
                    }
                    "delete" | "restore" => {
                        if self.fields.is_some() {
                            return bad("invalid_mutation", format!("{op} carries no fields"));
                        }
                    }
                    _ => return bad("invalid_mutation", format!("bad record op {op}")),
                }
            }
            ("file", op) => {
                if !valid_entity_id(&self.id) {
                    return bad("invalid_id", "file ids are 1–128 characters of [A-Za-z0-9_-]".into());
                }
                match op {
                    "put" => {
                        let Some(f) = &self.file else {
                            return bad("invalid_mutation", "file put without file".into());
                        };
                        if !valid_file_path(&f.path) || !valid_sha256(&f.sha256) || f.mime_type.is_empty() {
                            return bad("invalid_mutation", "file put needs a valid path, sha256 and mime_type".into());
                        }
                    }
                    "move" => {
                        let ok = self.file.as_ref().is_some_and(|f| valid_file_path(&f.path));
                        if !ok {
                            return bad("invalid_mutation", "file move needs a valid path".into());
                        }
                    }
                    "delete" | "restore" => {}
                    _ => return bad("invalid_mutation", format!("bad file op {op}")),
                }
            }
            (k, _) => return bad("invalid_mutation", format!("bad mutation kind {k}")),
        }
        Ok(())
    }
}

impl ServerFrame {
    /// Decodes and validates one server frame.
    pub fn decode(text: &str) -> Result<ServerFrame> {
        let v: Value = serde_json::from_str(text).map_err(|e| invalid(format!("not JSON: {e}")))?;
        let f: ServerFrame = serde_json::from_value(v).map_err(|e| invalid(format!("bad frame: {e}")))?;
        f.validate()?;
        Ok(f)
    }

    pub fn validate(&self) -> Result<()> {
        match self {
            ServerFrame::Snapshot(s) => {
                for r in &s.records {
                    for k in r.fields.keys() {
                        if !r.hlcs.contains_key(k) {
                            return Err(invalid(format!("snapshot field {}.{} has no stamp", r.table, k)));
                        }
                    }
                    for h in r.hlcs.values() {
                        check_hlc(h)?;
                    }
                }
                if let Some(t) = &s.tables {
                    for (name, ts) in t {
                        ts.validate(name)?;
                    }
                }
            }
            ServerFrame::Delta(d) => {
                for op in &d.ops {
                    op.validate()?;
                }
            }
            ServerFrame::Broadcast(b) => {
                if b.ops.is_empty() {
                    return Err(invalid("broadcast without ops"));
                }
                for op in &b.ops {
                    op.validate()?;
                }
            }
            ServerFrame::Ack(a) => {
                for r in &a.results {
                    match r.status.as_str() {
                        "applied" | "duplicate" | "aborted" => {}
                        "rejected" if r.error.is_some() => {}
                        "rejected" => return Err(invalid("rejected result without error")),
                        s => return Err(invalid(format!("bad ack status {s}"))),
                    }
                }
                if let Some(b) = &a.batch {
                    if !matches!(b.status.as_str(), "applied" | "rejected" | "duplicate") {
                        return Err(invalid(format!("bad batch status {}", b.status)));
                    }
                }
            }
            ServerFrame::Welcome(w) => {
                if w.protocol < PROTOCOL_V2 {
                    return Err(invalid("welcome.protocol must be >= 2"));
                }
                if w.principal.kind.is_empty() {
                    return Err(invalid("welcome.principal.kind is required"));
                }
            }
            ServerFrame::Result(r) => {
                if !valid_entity_id(&r.sub) || !valid_entity_id(&r.space_id) || r.through_seq < 0 {
                    return Err(invalid("result needs a valid sub, space_id and through_seq"));
                }
                check_tables(r.tables.as_ref())?;
                for row in &r.rows {
                    row.validate()?;
                }
                for (table, ids) in r.ids.iter().flatten() {
                    if !valid_record_table(table) || !ids.iter().all(|id| valid_record_id(id)) {
                        return Err(invalid(format!("result.ids[{table}] is invalid")));
                    }
                }
            }
            ServerFrame::Changes(c) => {
                if !valid_entity_id(&c.sub) || !valid_entity_id(&c.space_id) || c.through_seq < 0 {
                    return Err(invalid("changes needs a valid sub, space_id and through_seq"));
                }
                for op in &c.ops {
                    op.validate()?;
                }
                for row in &c.added {
                    row.validate()?;
                }
                for r in &c.removed {
                    if !valid_record_table(&r.table) || !valid_record_id(&r.id) {
                        return Err(invalid("changes.removed needs a valid table and id"));
                    }
                }
            }
            ServerFrame::Error(e) => {
                if e.code.is_empty() {
                    return Err(invalid("error frame without code"));
                }
            }
            ServerFrame::Pong(p) => {
                if !valid_entity_id(&p.nonce) {
                    return Err(invalid("bad pong nonce"));
                }
                if p.region.as_ref().is_some_and(|r| r.len() > 64) {
                    return Err(invalid("pong region over 64 bytes"));
                }
            }
        }
        Ok(())
    }
}

impl ClientFrame {
    pub fn encode(&self) -> String {
        serde_json::to_string(self).expect("frames serialize")
    }

    /// Decodes and validates a client frame (tests and tooling).
    pub fn decode(text: &str) -> Result<ClientFrame> {
        let f: ClientFrame = serde_json::from_str(text).map_err(|e| invalid(format!("bad frame: {e}")))?;
        match &f {
            ClientFrame::Hello(h) => {
                if h.protocol >= PROTOCOL_V2 {
                    // A v2 hello authenticates only; spaces follow as subscribe frames.
                    if h.token.is_empty() || !h.space_id.is_empty() || h.since_seq != 0 || h.schema.is_some() {
                        return Err(invalid("a protocol 2 hello carries a token and no space_id, since_seq or schema"));
                    }
                } else if h.protocol < 1 || h.since_seq < 0 || h.space_id.is_empty() || h.token.is_empty() {
                    return Err(invalid("bad hello"));
                }
                for (name, t) in h.schema.iter().flatten() {
                    t.validate(name)?;
                }
            }
            ClientFrame::Mutate(m) => {
                if m.mutations.is_empty() || m.mutations.len() > MAX_MUTATIONS_PER_FRAME {
                    return Err(invalid("a mutate frame holds 1 to 500 mutations"));
                }
                for mu in &m.mutations {
                    if !valid_entity_id(&mu.mutation_id) {
                        return Err(invalid("bad mutation_id"));
                    }
                }
                if m.batch_id.as_deref().is_some_and(|b| !valid_entity_id(b)) || (m.atomic && m.batch_id.is_none()) {
                    return Err(invalid("an atomic mutate needs a valid batch_id"));
                }
            }
            ClientFrame::Subscribe(sb) => {
                let declare = sb.query.is_none() && sb.files.is_none();
                if !valid_entity_id(&sb.sub) || !valid_entity_id(&sb.space_id) {
                    return Err(invalid("subscribe needs a valid sub and space_id"));
                }
                if declare && sb.schema.as_ref().is_none_or(|s| s.is_empty()) {
                    return Err(invalid("a subscription needs a query, files or schema"));
                }
                if declare && (sb.params.is_some() || sb.resume.is_some()) {
                    return Err(invalid("a schema declaration takes no params or resume"));
                }
                if sb.query.is_some() && sb.files.is_some() {
                    return Err(invalid("give a query or files, not both"));
                }
                match &sb.query {
                    None | Some(Value::Object(_)) => {}
                    Some(Value::String(q)) if q == QUERY_ALL => {}
                    Some(_) => return Err(invalid(r#"query must be an object or "*""#)),
                }
                check_tables(sb.schema.as_ref())?;
            }
            ClientFrame::Unsubscribe(u) => {
                if !valid_entity_id(&u.sub) {
                    return Err(invalid("unsubscribe needs a valid sub"));
                }
            }
            ClientFrame::Ping(p) => {
                if !valid_entity_id(&p.nonce) {
                    return Err(invalid("bad ping nonce"));
                }
            }
        }
        Ok(f)
    }
}