Skip to main content

syncular_command/
lib.rs

1//! # syncular-command — one JSON command surface over the Rust client core
2//!
3//! The command router the conformance shim proved (JSON in, JSON out, bytes
4//! as `{"$bytes": hex}`) factored into a transport-agnostic module so BOTH
5//! the stdio conformance shim AND the FFI native core dispatch through the
6//! same code. That keeps a single command surface, conformance-locked via
7//! the shim: whatever the shim exercises, the FFI core inherits.
8//!
9//! The router is generic over the `Transport` seam. The shim binds it to a
10//! stdio host (transport inverted to the harness); the FFI crate binds it to
11//! a real native HTTP+WS transport. Everything host-specific — realtime
12//! notification draining, deferred requests, event queues — stays in each
13//! host; only the pure `method → result` dispatch (and its JSON parsing) is
14//! shared here.
15
16use serde_json::{json, Value};
17use ssp2::segment::{decode_rows_segment, encode_rows_segment};
18use ssp2::{
19    decode_message, encode_message, parse_control, render_message, render_rows_segment,
20    ControlMessage,
21};
22use syncular_client::previous_version::{PreviousVersionContextConfig, PreviousVersionReadSpec};
23use syncular_client::values::{bytes_to_hex, hex_to_bytes};
24use syncular_client::{
25    ClientDiagnosticsSnapshot, ClientError, ClientLimits, CommandEffects, CommitOutcomeQuery,
26    LocalDataPurgeInput, LocalDataRebootstrapInput, Mutation, QueryOwner, QueryReadFailure,
27    RealtimePolicy, ResolveCommitOutcomeInput, SyncClient, Transport, TransportError, UnitScopes,
28    WindowBase, WindowCoverage, LOCAL_AUTHORITY_UNCONFIGURED_CODE,
29};
30
31// -- bytes <-> {"$bytes": hex} (the driver-protocol byte envelope) ----------
32
33pub fn bytes_value(bytes: &[u8]) -> Value {
34    Value::Object(serde_json::Map::from_iter([(
35        "$bytes".to_owned(),
36        Value::from(bytes_to_hex(bytes)),
37    )]))
38}
39
40pub fn value_bytes(value: Option<&Value>) -> Result<Vec<u8>, String> {
41    let hex = value
42        .and_then(|v| v.get("$bytes"))
43        .and_then(Value::as_str)
44        .ok_or_else(|| "expected a {\"$bytes\": hex} value".to_owned())?;
45    hex_to_bytes(hex)
46}
47
48/// The structured failure the driver protocol carries in an `error`. `details`
49/// and `retryable` carry the typed mutation fields to the host; non-mutation
50/// failures leave both at their defaults.
51#[derive(Debug, Clone)]
52pub struct CommandError {
53    pub code: String,
54    pub message: String,
55    pub details: Option<Value>,
56    pub retryable: bool,
57}
58
59impl CommandError {
60    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
61        Self {
62            code: code.into(),
63            message: message.into(),
64            details: None,
65            retryable: false,
66        }
67    }
68
69    /// Consume a structured client authoring failure without re-parsing text.
70    pub fn from_client(error: ClientError) -> Self {
71        Self {
72            code: error.code,
73            message: error.message,
74            details: error.details,
75            retryable: error.retryable,
76        }
77    }
78}
79
80impl From<(String, String)> for CommandError {
81    fn from((code, message): (String, String)) -> Self {
82        Self {
83            code,
84            message,
85            details: None,
86            retryable: false,
87        }
88    }
89}
90
91/// The `{"code","message","retryable"[,"details"]}` object every host sends
92/// as the `error` of a failed command.
93pub fn error_envelope(error: CommandError) -> Value {
94    let mut envelope = json!({
95        "code": error.code,
96        "message": error.message,
97        "retryable": error.retryable
98    });
99    if let Some(details) = error.details {
100        envelope["details"] = details;
101    }
102    envelope
103}
104
105/// The application-facing `{"result"}` / `{"error"}` reply of a native host.
106/// The router's `effects` are consumed by the host and never leave it.
107pub fn reply(result: Result<Value, CommandError>) -> Value {
108    match result {
109        Ok(mut value) => {
110            if let Some(object) = value.as_object_mut() {
111                object.remove("effects");
112            }
113            // Moved, never serialized through `json!`: payloads can be megabytes.
114            Value::Object(serde_json::Map::from_iter([("result".to_owned(), value)]))
115        }
116        Err(error) => json!({ "error": error_envelope(error) }),
117    }
118}
119
120/// A well-formed presence control frame (§8.6.2), the one inbound realtime
121/// event a native host surfaces as an event: a fanout, or the server's refusal
122/// of this client's own publish, which carries the server's `error` code.
123pub fn presence_event(text: &str) -> Option<Value> {
124    let Ok(ControlMessage::Presence {
125        scope_key, error, ..
126    }) = parse_control(text)
127    else {
128        return None;
129    };
130    let mut event = json!({ "type": "presence", "scopeKey": scope_key });
131    if let Some(error) = error {
132        event["error"] = Value::from(error);
133    }
134    Some(event)
135}
136
137/// The privacy-safe diagnostics event for `client`, or `None` while a security
138/// preflight is pending, the snapshot fails, or its state (excluding capture
139/// time) equals `last`. Stores the emitted snapshot in `last`.
140pub fn diagnostics_event(
141    client: &SyncClient,
142    last: &mut Option<ClientDiagnosticsSnapshot>,
143) -> Option<Value> {
144    if client.security_preflight() {
145        return None;
146    }
147    let snapshot = client.diagnostics_snapshot().ok()?;
148    if let Some(previous) = last {
149        // Capture time is observation metadata, excluded from evidence equality.
150        previous.captured_at_ms = snapshot.captured_at_ms;
151        if previous == &snapshot {
152            return None;
153        }
154    }
155    let event = json!({ "type": "diagnostics", "snapshot": snapshot });
156    *last = Some(snapshot);
157    Some(event)
158}
159
160/// Parsed side effects of a `create` command that the host must apply to its
161/// own transport/clock (the router stays transport-agnostic). The client is
162/// already installed into the `Option<SyncClient>` slot by `dispatch`.
163#[derive(Debug, Default, Clone)]
164pub struct CreateEffects {
165    /// §5.4 capability the harness/host announced for its endpoints — the
166    /// host sets its transport's `supports_url_fetch` accordingly.
167    pub signed_urls: bool,
168    /// True while a security preflight is pending: a preflighted client was
169    /// installed (or entered preflight, or was shut down mid-preflight) and
170    /// `activateSecurity` has yet to complete. `dispatch` maintains this so a
171    /// replacement `create` without the `securityPreflight` flag is refused
172    /// across `shutdown`, where the client slot is empty, on a host that reuses
173    /// one `CreateEffects` across creates (the Tauri plugin, the conformance
174    /// shim, the bench harness).
175    ///
176    /// A host that allocates a fresh `CreateEffects` per create — the React
177    /// Native native module rebuilds its FFI handle on every `create` — starts
178    /// each create with this flag clear. For those hosts the persisted marker
179    /// in the client core carries the gate: a file-backed replica reopens in
180    /// preflight, and the `create` path refuses a plain re-create against it.
181    /// This in-memory flag covers the same-handle case where no file persists
182    /// the marker.
183    pub security_preflight_pending: bool,
184}
185
186/// §7.5: a read failure keeps its structured code, static message, SQLite
187/// details, and retryability across the command boundary.
188fn read_command_error(failure: QueryReadFailure) -> CommandError {
189    let details = failure.details();
190    let retryable = failure.retryable();
191    CommandError {
192        code: failure.code.unwrap_or("client.failed").to_owned(),
193        message: failure.message,
194        details,
195        retryable,
196    }
197}
198
199/// The code identity follows the client core's own rule
200/// (`ClientError::from`), so a colon-less `sync.unknown_table` keeps its code.
201/// The command boundary keeps the full rendered message.
202fn client_err(message: String) -> CommandError {
203    let code = ClientError::from(message.clone()).code;
204    let retryable = code == "client.storage_busy";
205    CommandError {
206        code,
207        message,
208        details: None,
209        retryable,
210    }
211}
212
213/// An optional command field. Absent or `null` keeps the caller's default; a
214/// present value `read` does not accept is `sync.invalid_request`, never a
215/// silent default.
216fn optional<'a, T>(
217    value: Option<&'a Value>,
218    field: &str,
219    read: impl FnOnce(&'a Value) -> Option<T>,
220) -> Result<Option<T>, String> {
221    match value {
222        None | Some(Value::Null) => Ok(None),
223        Some(value) => read(value)
224            .map(Some)
225            .ok_or_else(|| format!("sync.invalid_request: {field} has the wrong type")),
226    }
227}
228
229/// A transport failure keeps its code and structured details across the
230/// command boundary (`sync.attach_rejected` and its `details.reason`).
231fn transport_command_error(error: TransportError) -> CommandError {
232    CommandError {
233        code: error.code,
234        message: error.message,
235        details: error.details,
236        retryable: false,
237    }
238}
239
240fn need_client(client: &mut Option<SyncClient>) -> Result<&mut SyncClient, CommandError> {
241    client
242        .as_mut()
243        .ok_or_else(|| client_err("no client instance created".to_owned()))
244}
245
246/// RFC 0005 D8: parse the host's `previousVersionContext` config with the
247/// TS keys and defaults: `enabled` (default false), `maxBytes` 8 MiB,
248/// `maxRows` 20000, `maxTables` 32, `maxRowBytes` 1 MiB, `maxAgeMs` 24h.
249/// Invalid values fail the request loudly rather than silently defaulting.
250fn parse_previous_version_context(
251    value: Option<&Value>,
252) -> Result<Option<PreviousVersionContextConfig>, CommandError> {
253    let Some(value) = value else {
254        return Ok(None);
255    };
256    let object = value.as_object().ok_or_else(|| {
257        client_err("sync.invalid_request: previousVersionContext must be an object".to_owned())
258    })?;
259    let enabled = match object.get("enabled") {
260        None => false,
261        Some(Value::Bool(enabled)) => *enabled,
262        Some(_) => {
263            return Err(client_err(
264                "sync.invalid_request: previousVersionContext.enabled must be a boolean".to_owned(),
265            ))
266        }
267    };
268    let mut config = PreviousVersionContextConfig {
269        enabled,
270        ..PreviousVersionContextConfig::default()
271    };
272    for (key, slot) in [
273        ("maxBytes", &mut config.max_bytes),
274        ("maxRows", &mut config.max_rows),
275        ("maxTables", &mut config.max_tables),
276        ("maxRowBytes", &mut config.max_row_bytes),
277        ("maxAgeMs", &mut config.max_age_ms),
278    ] {
279        if let Some(raw) = object.get(key) {
280            *slot = raw.as_i64().ok_or_else(|| {
281                client_err(format!(
282                    "sync.invalid_request: previousVersionContext.{key} must be a positive safe integer"
283                ))
284            })?;
285        }
286    }
287    config.validate().map_err(client_err)?;
288    Ok(Some(config))
289}
290
291/// RFC 0005 D7: `previousVersionSnapshot` params — `{table, rowIds?, limit?}`.
292fn parse_previous_version_snapshot_spec(
293    params: &Value,
294) -> Result<PreviousVersionReadSpec, CommandError> {
295    let table = params.get("table").and_then(Value::as_str).ok_or_else(|| {
296        client_err("sync.invalid_request: previousVersionSnapshot missing table".to_owned())
297    })?;
298    let row_ids = match params.get("rowIds") {
299        None | Some(Value::Null) => Vec::new(),
300        Some(Value::Array(ids)) => ids
301            .iter()
302            .map(|id| match id {
303                Value::String(id) => Ok(id.clone()),
304                Value::Number(number) => Ok(number.to_string()),
305                Value::Bool(boolean) => Ok(boolean.to_string()),
306                _ => Err(client_err(
307                    "sync.invalid_request: previousVersionSnapshot rowIds must be strings"
308                        .to_owned(),
309                )),
310            })
311            .collect::<Result<Vec<_>, _>>()?,
312        Some(_) => {
313            return Err(client_err(
314                "sync.invalid_request: previousVersionSnapshot rowIds must be an array".to_owned(),
315            ))
316        }
317    };
318    let limit = match params.get("limit") {
319        None | Some(Value::Null) => None,
320        Some(value) => Some(value.as_i64().ok_or_else(|| {
321            client_err(
322                "sync.invalid_request: previousVersionSnapshot limit must be a positive number"
323                    .to_owned(),
324            )
325        })?),
326    };
327    Ok(PreviousVersionReadSpec {
328        table: table.to_owned(),
329        row_ids,
330        limit,
331    })
332}
333
334fn parse_limits(value: Option<&Value>) -> Result<ClientLimits, CommandError> {
335    let mut limits = ClientLimits::default();
336    let Some(object) = optional(value, "limits", Value::as_object).map_err(client_err)? else {
337        return Ok(limits);
338    };
339    let i32_field = |key: &str| {
340        optional(object.get(key), key, |v| {
341            v.as_i64().and_then(|n| i32::try_from(n).ok())
342        })
343        .map_err(client_err)
344    };
345    limits.limit_commits = i32_field("limitCommits")?;
346    limits.limit_snapshot_rows = i32_field("limitSnapshotRows")?;
347    limits.max_snapshot_pages = i32_field("maxSnapshotPages")?;
348    limits.accept = optional(object.get("accept"), "limits.accept", |v| {
349        v.as_u64().and_then(|n| u8::try_from(n).ok())
350    })
351    .map_err(client_err)?;
352    limits.blob_cache_max_bytes = optional(
353        object.get("blobCacheMaxBytes"),
354        "limits.blobCacheMaxBytes",
355        Value::as_i64,
356    )
357    .map_err(client_err)?;
358    limits.outcome_retention_max_entries = optional(
359        object.get("outcomeRetentionMaxEntries"),
360        "limits.outcomeRetentionMaxEntries",
361        |v| v.as_u64().and_then(|n| usize::try_from(n).ok()),
362    )
363    .map_err(client_err)?;
364    limits.max_push_commits_per_request = parse_push_limit(object, "maxPushCommitsPerRequest")?;
365    limits.max_push_operations_per_request =
366        parse_push_limit(object, "maxPushOperationsPerRequest")?;
367    limits.max_push_request_bytes = parse_push_limit(object, "maxPushRequestBytes")?;
368    Ok(limits)
369}
370
371/// §7.1: a configured push limit is a positive integer. Null or absent uses
372/// the default for that limit; invalid values fail with a structured error.
373fn parse_push_limit(
374    object: &serde_json::Map<String, Value>,
375    key: &str,
376) -> Result<Option<usize>, CommandError> {
377    match object.get(key) {
378        None | Some(Value::Null) => Ok(None),
379        Some(value) => value
380            .as_u64()
381            .and_then(|n| usize::try_from(n).ok())
382            .filter(|n| *n >= 1 && *n <= u32::MAX as usize)
383            .map(Some)
384            .ok_or_else(|| CommandError {
385                code: "sync.invalid_request".to_owned(),
386                message: "push limit must be an integer in 1..=4294967295".to_owned(),
387                details: Some(serde_json::json!({ "limit": key })),
388                retryable: false,
389            }),
390    }
391}
392
393/// §8.8: parse the `realtimePolicy` create param. Absent ⇒ `optional`.
394fn parse_realtime_policy(value: Option<&Value>) -> Result<RealtimePolicy, CommandError> {
395    match value {
396        None => Ok(RealtimePolicy::Optional),
397        Some(Value::String(text)) => match text.as_str() {
398            "required" => Ok(RealtimePolicy::Required),
399            "optional" => Ok(RealtimePolicy::Optional),
400            "off" => Ok(RealtimePolicy::Off),
401            other => Err(client_err(format!(
402                "sync.invalid_request: realtimePolicy must be 'required', 'optional', or 'off', got {other:?}"
403            ))),
404        },
405        Some(_) => Err(client_err(
406            "sync.invalid_request: realtimePolicy must be a string".to_owned(),
407        )),
408    }
409}
410
411/// §5.11: parse the `encryption` config into the client's portable keyring.
412/// Shape: `{ keys: { "<keyId>": {"$bytes": "<hex>"} },
413/// keyIdColumns: { "<table>": "<column>" } }`.
414/// Keys are 32 bytes.
415fn parse_encryption(value: &Value) -> Result<syncular_client::values::EncryptionConfig, String> {
416    let mut config = syncular_client::values::EncryptionConfig::default();
417    let keys = optional(value.get("keys"), "encryption.keys", Value::as_object)?;
418    for (key_id, key_val) in keys.into_iter().flatten() {
419        let bytes =
420            value_bytes(Some(key_val)).map_err(|e| format!("encryption key {key_id:?}: {e}"))?;
421        if bytes.len() != 32 {
422            return Err(format!(
423                "encryption key {key_id:?} must be 32 bytes, got {}",
424                bytes.len()
425            ));
426        }
427        config.keys.insert(key_id.clone(), bytes);
428    }
429    if let Some(columns) = value.get("keyIdColumns") {
430        let columns = columns
431            .as_object()
432            .ok_or_else(|| "encryption keyIdColumns must be an object".to_owned())?;
433        for (table, column) in columns {
434            let column = column.as_str().ok_or_else(|| {
435                format!("encryption keyIdColumns entry for {table:?} must be a string")
436            })?;
437            if column.is_empty() {
438                return Err(format!(
439                    "encryption keyIdColumns entry for {table:?} must not be empty"
440                ));
441            }
442            config
443                .key_id_columns
444                .insert(table.clone(), column.to_owned());
445        }
446    }
447    Ok(config)
448}
449
450pub fn parse_mutations(value: Option<&Value>) -> Result<Vec<Mutation>, String> {
451    let list = value
452        .and_then(Value::as_array)
453        .ok_or_else(|| "mutations must be a list".to_owned())?;
454    let mut out = Vec::with_capacity(list.len());
455    for entry in list {
456        let op = entry
457            .get("op")
458            .and_then(Value::as_str)
459            .ok_or_else(|| "mutation missing op".to_owned())?;
460        let table = entry
461            .get("table")
462            .and_then(Value::as_str)
463            .ok_or_else(|| "mutation missing table".to_owned())?
464            .to_owned();
465        let base_version = optional(entry.get("baseVersion"), "baseVersion", Value::as_i64)?;
466        match op {
467            "upsert" | "patch" => {
468                let mut values = entry
469                    .get("values")
470                    .and_then(Value::as_object)
471                    .cloned()
472                    .ok_or_else(|| "upsert missing values".to_owned())?;
473                decode_bigint_members(&mut values)?;
474                out.push(if op == "patch" {
475                    Mutation::Patch {
476                        table,
477                        values,
478                        base_version,
479                    }
480                } else {
481                    Mutation::Upsert {
482                        table,
483                        values,
484                        base_version,
485                    }
486                });
487            }
488            "delete" => {
489                let row_id = entry
490                    .get("rowId")
491                    .and_then(Value::as_str)
492                    .ok_or_else(|| "delete missing rowId".to_owned())?
493                    .to_owned();
494                out.push(Mutation::Delete {
495                    table,
496                    row_id,
497                    base_version,
498                });
499            }
500            other => return Err(format!("unknown mutation op {other:?}")),
501        }
502    }
503    Ok(out)
504}
505
506fn decode_bigint_members(values: &mut serde_json::Map<String, Value>) -> Result<(), String> {
507    for value in values.values_mut() {
508        let Some(decimal) = value.get("$bigint").and_then(Value::as_str) else {
509            continue;
510        };
511        let integer = decimal
512            .parse::<i64>()
513            .map_err(|_| format!("bigint value {decimal:?} is outside SQLite's i64 range"))?;
514        *value = Value::from(integer);
515    }
516    Ok(())
517}
518
519/// §4.1: parse a unit scope map `{variable: value}`; absent fails.
520fn unit_scopes(value: Option<&Value>) -> Result<UnitScopes, String> {
521    serde_json::from_value(value.cloned().unwrap_or(Value::Null)).map_err(|_| {
522        "sync.invalid_request: a unit scope map is an object of string values".to_owned()
523    })
524}
525
526/// §4.8: parse a window base descriptor `{ variable, fixedScopes? }` from a
527/// command's `base` param.
528fn window_base_from_params(value: Option<&Value>) -> Result<WindowBase, String> {
529    let object = value
530        .and_then(Value::as_object)
531        .ok_or_else(|| "sync.invalid_request: window base must be an object".to_owned())?;
532    let variable = object
533        .get("variable")
534        .and_then(Value::as_str)
535        .ok_or_else(|| "sync.invalid_request: window base missing variable".to_owned())?
536        .to_owned();
537    Ok(WindowBase {
538        variable,
539        fixed_scopes: match object.get("fixedScopes") {
540            None | Some(Value::Null) => UnitScopes::new(),
541            scopes => unit_scopes(scopes)?,
542        },
543    })
544}
545
546/// §7.5: parse a `coverage` array of `{base, units}` entries. Absent or null is
547/// empty; a non-array, a malformed base, or non-string units are rejected
548/// explicitly instead of silently defaulting. Shared with the Tauri plugin's
549/// read sidecar.
550pub fn parse_window_coverage(value: Option<&Value>) -> Result<Vec<WindowCoverage>, String> {
551    let entries = match value {
552        None | Some(Value::Null) => return Ok(Vec::new()),
553        Some(Value::Array(entries)) => entries,
554        Some(_) => return Err("sync.invalid_request: coverage must be a list".to_owned()),
555    };
556    let mut coverage = Vec::with_capacity(entries.len());
557    for entry in entries {
558        let units = match entry.get("units") {
559            None | Some(Value::Null) => Vec::new(),
560            Some(Value::Array(values)) => values
561                .iter()
562                .map(|value| value.as_str().map(str::to_owned))
563                .collect::<Option<Vec<_>>>()
564                .ok_or_else(|| {
565                    "sync.invalid_request: coverage units must be a list of strings".to_owned()
566                })?,
567            Some(_) => {
568                return Err(
569                    "sync.invalid_request: coverage units must be a list of strings".to_owned(),
570                )
571            }
572        };
573        coverage.push(WindowCoverage {
574            base: window_base_from_params(entry.get("base"))?,
575            units,
576        });
577    }
578    Ok(coverage)
579}
580
581/// §7.5 owner: `{id, tables}`, both required when present. Shared by
582/// `querySnapshot` and `snapshotRead`.
583pub fn parse_query_owner<'a>(
584    owner: Option<&'a Value>,
585    method: &str,
586) -> Result<Option<(&'a str, Vec<&'a str>)>, CommandError> {
587    match owner {
588        None | Some(Value::Null) => Ok(None),
589        Some(value) => {
590            let id = value
591                .get("id")
592                .and_then(Value::as_str)
593                .filter(|id| !id.is_empty());
594            let tables = value
595                .get("tables")
596                .and_then(Value::as_array)
597                .and_then(|list| {
598                    list.iter()
599                        .map(Value::as_str)
600                        .collect::<Option<Vec<&str>>>()
601                });
602            match (id, tables) {
603                (Some(id), Some(tables)) => Ok(Some((id, tables))),
604                _ => Err(client_err(format!(
605                    "sync.invalid_request: {method} owner must be {{id: non-empty string, tables: string[]}}"
606                ))),
607            }
608        }
609    }
610}
611
612/// §7.5: parse a `units`/`commitIds` list. Absent or null is empty; a
613/// non-array or a non-string entry is rejected explicitly.
614fn snapshot_string_list(value: Option<&Value>) -> Result<Vec<String>, CommandError> {
615    match value {
616        None | Some(Value::Null) => Ok(Vec::new()),
617        Some(Value::Array(items)) => items
618            .iter()
619            .map(|item| item.as_str().map(str::to_owned))
620            .collect::<Option<Vec<String>>>()
621            .ok_or_else(|| {
622                client_err(
623                    "sync.invalid_request: snapshotRead list must contain strings".to_owned(),
624                )
625            }),
626        Some(_) => Err(client_err(
627            "sync.invalid_request: snapshotRead list must be a list of strings".to_owned(),
628        )),
629    }
630}
631
632/// The parsed `snapshotRead` params (§7.5), owned so a host can move them to
633/// its read thread.
634pub struct SnapshotReadParams {
635    pub statements: Vec<(String, Vec<Value>)>,
636    pub coverage: Vec<WindowCoverage>,
637    pub units: Vec<String>,
638    pub commit_ids: Vec<String>,
639    pub owner: Option<(String, Vec<String>)>,
640}
641
642/// Parse and validate the params of `snapshotRead`; shared by the router and
643/// the Tauri read sidecar.
644pub fn parse_snapshot_read(params: &Value) -> Result<SnapshotReadParams, CommandError> {
645    let mut statements = Vec::new();
646    match params.get("statements") {
647        None | Some(Value::Null) => {}
648        Some(Value::Array(items)) => {
649            for item in items {
650                let Some(sql) = item.get("sql").and_then(Value::as_str) else {
651                    return Err(client_err(
652                        "sync.invalid_request: snapshotRead statements need a sql string"
653                            .to_owned(),
654                    ));
655                };
656                let bind =
657                    match item.get("params") {
658                        None | Some(Value::Null) => Vec::new(),
659                        Some(Value::Array(values)) => values.clone(),
660                        Some(_) => return Err(client_err(
661                            "sync.invalid_request: snapshotRead statement params must be a list"
662                                .to_owned(),
663                        )),
664                    };
665                statements.push((sql.to_owned(), bind));
666            }
667        }
668        Some(_) => {
669            return Err(client_err(
670                "sync.invalid_request: snapshotRead statements must be a list".to_owned(),
671            ))
672        }
673    }
674    Ok(SnapshotReadParams {
675        statements,
676        units: snapshot_string_list(params.get("units"))?,
677        commit_ids: snapshot_string_list(params.get("commitIds"))?,
678        coverage: parse_window_coverage(params.get("coverage")).map_err(client_err)?,
679        owner: parse_query_owner(params.get("owner"), "snapshotRead")?.map(|(id, tables)| {
680            (
681                id.to_owned(),
682                tables.into_iter().map(str::to_owned).collect(),
683            )
684        }),
685    })
686}
687
688/// §5.10.5: parse the common `(table, rowId, column, name)` target of a crdt
689/// command. `name` selects the shared type inside the doc (default `"text"`,
690/// matching the TS `YjsColumn.text()` default).
691#[cfg(feature = "crdt-yjs")]
692fn crdt_target(params: &Value) -> Result<(String, String, String, String), CommandError> {
693    let table = params
694        .get("table")
695        .and_then(Value::as_str)
696        .ok_or_else(|| client_err("crdt command missing table".to_owned()))?
697        .to_owned();
698    let row_id = params
699        .get("rowId")
700        .and_then(Value::as_str)
701        .ok_or_else(|| client_err("crdt command missing rowId".to_owned()))?
702        .to_owned();
703    let column = params
704        .get("column")
705        .and_then(Value::as_str)
706        .ok_or_else(|| client_err("crdt command missing column".to_owned()))?
707        .to_owned();
708    let name = optional(params.get("name"), "crdt name", Value::as_str)
709        .map_err(client_err)?
710        .unwrap_or("text")
711        .to_owned();
712    Ok((table, row_id, column, name))
713}
714
715/// Dispatch one command against the client instance over `transport`.
716///
717/// The `create` command installs a fresh `SyncClient` into `client` and
718/// returns its parsed `CreateEffects` in the `Ok` result via `effects`; every
719/// other command mutates the existing instance. Errors come back as the
720/// driver-protocol `(code, message)` pair.
721///
722/// Generic over `T: Transport` so the shim (host-inverted transport) and the
723/// FFI core (native HTTP+WS transport) share this exact router.
724pub fn dispatch<T: Transport>(
725    transport: &mut T,
726    client: &mut Option<SyncClient>,
727    effects: &mut CreateEffects,
728    method: &str,
729    params: &Value,
730) -> Result<Value, CommandError> {
731    if method == "create" {
732        // Fail-closed against a compromised webview re-issuing `create` (or
733        // `shutdown` + `create`) WITHOUT the securityPreflight flag to exit
734        // the gate: while a preflight is pending — on the live client, or
735        // carried in `effects` across a `shutdown` — a replacement create must
736        // itself request securityPreflight; the gate opens only through
737        // activateSecurity.
738        let requests_preflight = optional(
739            params.get("securityPreflight"),
740            "securityPreflight",
741            Value::as_bool,
742        )
743        .map_err(client_err)?
744        .unwrap_or(false);
745        let preflight_engaged = client.as_ref().map_or(
746            effects.security_preflight_pending,
747            SyncClient::security_preflight,
748        );
749        if preflight_engaged && !requests_preflight {
750            return Err(CommandError::new(
751                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
752                "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity",
753            ));
754        }
755    } else {
756        let allowed_during_preflight = matches!(
757            method,
758            "authoritySnapshot"
759                | "securityLifecycle"
760                | "beginSecurityPreflight"
761                | "activateSecurity"
762                | "setTransportEnabled"
763                | "disconnectRealtime"
764                | "purgeLocalData"
765                | "previousVersionDiscard"
766                | "localRevision"
767                | "statusSnapshot"
768                | "localAuthorityState"
769                | "drainRealtime"
770                | "shutdown"
771        );
772        if client
773            .as_ref()
774            .is_some_and(|running| running.security_preflight())
775            && !allowed_during_preflight
776        {
777            return Err(CommandError::new(
778                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
779                "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data",
780            ));
781        }
782    }
783    let mut result = match method {
784        "create" => {
785            let client_id = optional(params.get("clientId"), "clientId", Value::as_str)
786                .map_err(client_err)?
787                .map(str::to_owned);
788            let db_path =
789                optional(params.get("dbPath"), "dbPath", Value::as_str).map_err(client_err)?;
790            let schema = params
791                .get("schema")
792                .ok_or_else(|| client_err("create missing schema".to_owned()))?;
793            let limits = parse_limits(params.get("limits"))?;
794            // RFC 0005 D8: the feature config rides the top-level key the TS
795            // client uses; the Rust core carries it on `ClientLimits` so it is
796            // resolved before the opening schema reset runs.
797            let previous_version_context =
798                parse_previous_version_context(params.get("previousVersionContext"))?;
799            let mut limits = limits;
800            limits.previous_version_context = previous_version_context;
801            if let Some(reads) = params.get("authorityReads") {
802                limits.authority_reads = serde_json::from_value(reads.clone()).map_err(|_| {
803                    client_err(
804                        "client.authority_read_forbidden: invalid authority declaration".into(),
805                    )
806                })?;
807            }
808            // §12: a host-configured local authority opens with the client's
809            // schema before the client, as the browser worker opens it.
810            transport
811                .open_local_authority(schema, db_path)
812                .map_err(transport_command_error)?;
813            // §native: a `dbPath` installs a file-backed rusqlite connection so
814            // native hosts (Tauri plugin, FFI file variant) persist across
815            // restarts; absent it, the default in-memory core (the shim's mode).
816            let mut instance = match db_path {
817                Some(path) => SyncClient::open_path_with_identity(client_id, schema, limits, path)
818                    .map_err(client_err)?,
819                None => {
820                    SyncClient::new_with_identity(client_id, schema, limits).map_err(client_err)?
821                }
822            };
823            instance
824                .set_retain_failed_commits(
825                    optional(
826                        params.get("retainFailedCommits"),
827                        "retainFailedCommits",
828                        Value::as_bool,
829                    )
830                    .map_err(client_err)?
831                    .unwrap_or(false),
832                )
833                .map_err(client_err)?;
834            // §8.8: the realtime policy rides the create params; absent ⇒
835            // `optional` (today's socket-or-HTTP behavior).
836            let realtime_policy = parse_realtime_policy(params.get("realtimePolicy"))?;
837            instance
838                .set_realtime_policy(realtime_policy)
839                .map_err(client_err)?;
840            // Harness clock pin (§5.4 expiry runs on the virtual clock).
841            if let Some(now_ms) =
842                optional(params.get("nowMs"), "nowMs", Value::as_i64).map_err(client_err)?
843            {
844                instance.set_now_ms(now_ms);
845            }
846            // §5.4 capability of the host endpoint set (accept bit 3) — the
847            // host applies it to its own transport.
848            effects.signed_urls = optional(params.get("signedUrls"), "signedUrls", Value::as_bool)
849                .map_err(client_err)?
850                .unwrap_or(false);
851            // §5.11: install client-side encryption keys. Shape:
852            // { encryption: { keys: { "<keyId>": {"$bytes": "<hex>"} },
853            //                 keyIdColumns: { "<table>": "<column>" } } }.
854            let security_preflight = optional(
855                params.get("securityPreflight"),
856                "securityPreflight",
857                Value::as_bool,
858            )
859            .map_err(client_err)?
860            .unwrap_or(false);
861            // A file-backed replica reopens in preflight when its persisted
862            // quarantine marker is set (client core restores it). Refuse a plain
863            // re-create so a rebuilt host handle — the React Native native module
864            // tears its FFI handle down on every create — cannot downgrade a
865            // quarantined replica to active. A create that itself requests
866            // securityPreflight, or an activated replica whose marker cleared,
867            // proceeds.
868            if instance.security_preflight() && !security_preflight {
869                return Err(CommandError::new(
870                    syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE,
871                    "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity",
872                ));
873            }
874            if security_preflight && params.get("encryption").is_some() {
875                return Err(client_err(
876                    "sync.invalid_request: securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight"
877                        .to_owned(),
878                ));
879            }
880            if let Some(enc) = params.get("encryption") {
881                let config = parse_encryption(enc).map_err(client_err)?;
882                instance.set_encryption(config);
883            }
884            if security_preflight {
885                instance.begin_security_preflight().map_err(client_err)?;
886            }
887            if let Some(enabled) = params.get("transportEnabled") {
888                let enabled = enabled.as_bool().ok_or_else(|| {
889                    client_err("sync.invalid_request: transportEnabled must be a boolean".into())
890                })?;
891                instance.set_transport_enabled(transport, enabled);
892            }
893            effects.security_preflight_pending = security_preflight;
894            transport.set_client_id(instance.client_id());
895            *client = Some(instance);
896            Ok(json!({}))
897        }
898        "securityLifecycle" => Ok(json!({
899            "state": need_client(client)?.security_lifecycle()
900        })),
901        "beginSecurityPreflight" => {
902            let running = need_client(client)?;
903            running.disconnect_realtime(transport);
904            running.begin_security_preflight().map_err(client_err)?;
905            effects.security_preflight_pending = true;
906            Ok(json!({}))
907        }
908        "authoritySnapshot" => {
909            if !params.as_object().is_some_and(|p| p.is_empty()) {
910                return Err(client_err(
911                    "client.authority_read_forbidden: authoritySnapshot accepts no arguments"
912                        .into(),
913                ));
914            }
915            client
916                .as_ref()
917                .ok_or_else(|| client_err("client.closed: no authority client is open".into()))?
918                .authority_snapshot()
919                .map_err(client_err)
920        }
921        "activateSecurity" => {
922            let encryption = match params.get("encryption") {
923                Some(value) => parse_encryption(value).map_err(client_err)?,
924                None => syncular_client::values::EncryptionConfig::default(),
925            };
926            // The transport reads headers from the host's header source at
927            // each request, so an activation carries none; a host still
928            // passing them is refused and the gate stays closed.
929            if params.get("headers").is_some() {
930                return Err(CommandError::new(
931                    "sync.invalid_request",
932                    "activateSecurity takes no headers; the transport asks the host's header source",
933                ));
934            }
935            need_client(client)?
936                .activate_security(encryption)
937                .map_err(client_err)?;
938            effects.security_preflight_pending = false;
939            Ok(json!({}))
940        }
941        "addEncryptionKeys" => {
942            let running = client
943                .as_mut()
944                .ok_or_else(|| CommandError::new("client.closed", "no client is open"))?;
945            let entries = params
946                .get("keys")
947                .and_then(Value::as_object)
948                .ok_or_else(|| {
949                    CommandError::new(
950                        "sync.invalid_request",
951                        "addEncryptionKeys.keys must be an object of {\"$bytes\": hex} values",
952                    )
953                })?;
954            // A malformed key decodes to no bytes, so the core refuses it in
955            // key-id order with the other bad keys and zeroes every buffer.
956            let keys = entries
957                .iter()
958                .map(|(key_id, value)| {
959                    (key_id.clone(), value_bytes(Some(value)).unwrap_or_default())
960                })
961                .collect();
962            running
963                .add_encryption_keys(keys)
964                .map_err(CommandError::from_client)?;
965            Ok(json!({}))
966        }
967        "setTransportEnabled" => {
968            let enabled = params
969                .get("enabled")
970                .and_then(Value::as_bool)
971                .ok_or_else(|| {
972                    client_err(
973                        "sync.invalid_request: setTransportEnabled.enabled must be a boolean"
974                            .into(),
975                    )
976                })?;
977            need_client(client)?.set_transport_enabled(transport, enabled);
978            Ok(json!({}))
979        }
980        "shutdown" => {
981            if let Some(running) = client.as_mut() {
982                // Capture the gate state BEFORE the shutdown barrier flips the
983                // client into preflight: an unactivated preflight stays
984                // pending across the shutdown, while an activated client may
985                // be recreated plainly afterwards.
986                effects.security_preflight_pending = running.security_preflight();
987                running.disconnect_realtime(transport);
988                // Teardown barrier only: an activated client that shuts down
989                // cleanly must not leave a durable quarantine mark, or its next
990                // plain create would be refused forever.
991                running.seal_security_on_teardown();
992            }
993            *client = None;
994            Ok(json!({}))
995        }
996        "subscribe" => {
997            let scopes = unit_scopes(params.get("scopes")).map_err(client_err)?;
998            let id = need_client(client)?.subscribe(scopes).map_err(client_err)?;
999            Ok(json!({ "id": id }))
1000        }
1001        "subscribeMany" => {
1002            let units = params
1003                .get("units")
1004                .and_then(Value::as_array)
1005                .ok_or_else(|| {
1006                    client_err(
1007                        "sync.invalid_request: subscribeMany units must be a list".to_owned(),
1008                    )
1009                })?
1010                .iter()
1011                .map(|scopes| unit_scopes(Some(scopes)))
1012                .collect::<Result<Vec<_>, _>>()
1013                .map_err(client_err)?;
1014            let ids = need_client(client)?
1015                .subscribe_many(units)
1016                .map_err(client_err)?;
1017            Ok(json!({ "ids": ids }))
1018        }
1019        "unsubscribe" => {
1020            let id = params
1021                .get("id")
1022                .and_then(Value::as_str)
1023                .ok_or_else(|| client_err("unsubscribe missing id".to_owned()))?;
1024            need_client(client)?.unsubscribe(id).map_err(client_err)?;
1025            Ok(json!({}))
1026        }
1027        "setWindow" => {
1028            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
1029            let units: Vec<String> = optional(params.get("units"), "setWindow units", |v| {
1030                v.as_array()?
1031                    .iter()
1032                    .map(|unit| unit.as_str().map(str::to_owned))
1033                    .collect()
1034            })
1035            .map_err(client_err)?
1036            .unwrap_or_default();
1037            let command_effects = need_client(client)?
1038                .set_window(&base, &units)
1039                .map_err(client_err)?;
1040            Ok(json!({ "effects": command_effects }))
1041        }
1042        "windowState" => {
1043            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
1044            let state = need_client(client)?
1045                .window_state(&base)
1046                .map_err(client_err)?;
1047            Ok(json!({ "units": state.units, "pending": state.pending, "revoked": state.revoked }))
1048        }
1049        "timeWindowSugar" => {
1050            let created_at_ms = params
1051                .get("createdAtMs")
1052                .and_then(Value::as_i64)
1053                .ok_or_else(|| client_err("timeWindowSugar missing createdAtMs".to_owned()))?;
1054            let count = params
1055                .get("count")
1056                .and_then(Value::as_u64)
1057                .and_then(|value| usize::try_from(value).ok())
1058                .ok_or_else(|| client_err("timeWindowSugar missing count".to_owned()))?;
1059            let now_ms = params
1060                .get("nowMs")
1061                .and_then(Value::as_i64)
1062                .ok_or_else(|| client_err("timeWindowSugar missing nowMs".to_owned()))?;
1063            if params.get("unit").and_then(Value::as_str) != Some("month") {
1064                return Err(client_err(
1065                    "sync.invalid_request: timeWindowSugar requires the month unit".to_owned(),
1066                ));
1067            }
1068            let unit = syncular_client::TimeBucketUnit::Month;
1069            Ok(json!({
1070                "bucket": syncular_client::creation_time_bucket(created_at_ms, unit)
1071                    .map_err(client_err)?,
1072                "units": syncular_client::last(count, unit, now_ms).map_err(client_err)?,
1073            }))
1074        }
1075        "mutate" => {
1076            let mutations = parse_mutations(params.get("mutations")).map_err(client_err)?;
1077            let id = need_client(client)?
1078                .mutate(mutations)
1079                .map_err(CommandError::from_client)?;
1080            Ok(json!({
1081                "clientCommitId": id,
1082                "effects": CommandEffects::interactive()
1083            }))
1084        }
1085        "replaceCommitOutcome" => {
1086            let id = params
1087                .get("clientCommitId")
1088                .and_then(Value::as_str)
1089                .ok_or_else(|| {
1090                    client_err("sync.invalid_request: clientCommitId must be a string".to_owned())
1091                })?;
1092            let sequence = params
1093                .get("sequence")
1094                .and_then(Value::as_i64)
1095                .ok_or_else(|| {
1096                    client_err("sync.invalid_request: sequence must be an integer".to_owned())
1097                })?;
1098            let replacement = match params.get("replacement") {
1099                None | Some(Value::Null) => None,
1100                value => Some(parse_mutations(value).map_err(client_err)?),
1101            };
1102            let id = need_client(client)?
1103                .replace_commit_outcome(id, sequence, replacement)
1104                .map_err(CommandError::from_client)?;
1105            Ok(json!({
1106                "clientCommitId": id,
1107                "effects": CommandEffects::interactive()
1108            }))
1109        }
1110        "patch" => {
1111            let table = params
1112                .get("table")
1113                .and_then(Value::as_str)
1114                .ok_or_else(|| client_err("patch missing table".to_owned()))?;
1115            let row_id = params
1116                .get("rowId")
1117                .and_then(Value::as_str)
1118                .ok_or_else(|| client_err("patch missing rowId".to_owned()))?;
1119            let mut partial = params
1120                .get("partial")
1121                .and_then(Value::as_object)
1122                .cloned()
1123                .ok_or_else(|| client_err("patch missing partial object".to_owned()))?;
1124            decode_bigint_members(&mut partial).map_err(client_err)?;
1125            let base_version = optional(params.get("baseVersion"), "baseVersion", Value::as_i64)
1126                .map_err(client_err)?;
1127            let id = need_client(client)?
1128                .patch(table, row_id, partial, base_version)
1129                .map_err(CommandError::from_client)?;
1130            Ok(json!({
1131                "clientCommitId": id,
1132                "effects": CommandEffects::interactive()
1133            }))
1134        }
1135        "purgeLocalData" => {
1136            let input: LocalDataPurgeInput =
1137                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
1138                    client_err("sync.invalid_request: purgeLocalData missing input".to_owned())
1139                })?)
1140                .map_err(|error| {
1141                    client_err(format!(
1142                        "sync.invalid_request: invalid purgeLocalData input: {error}"
1143                    ))
1144                })?;
1145            let result = need_client(client)?
1146                .purge_local_data(&input)
1147                .map_err(client_err)?;
1148            serde_json::to_value(result).map_err(|error| client_err(error.to_string()))
1149        }
1150        "rebootstrapLocalData" => {
1151            let input: LocalDataRebootstrapInput =
1152                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
1153                    client_err(
1154                        "sync.invalid_request: rebootstrapLocalData missing input".to_owned(),
1155                    )
1156                })?)
1157                .map_err(|error| {
1158                    client_err(format!(
1159                        "sync.invalid_request: invalid rebootstrapLocalData input: {error}"
1160                    ))
1161                })?;
1162            let result = need_client(client)?
1163                .rebootstrap_local_data(&input)
1164                .map_err(client_err)?;
1165            Ok(json!({
1166                "alreadyApplied": result.already_applied,
1167                "retainedCommits": result.retained_commits,
1168                "resetSubscriptions": result.reset_subscriptions,
1169                "effects": if result.already_applied {
1170                    CommandEffects::none()
1171                } else {
1172                    CommandEffects::interactive()
1173                }
1174            }))
1175        }
1176        "sync" => {
1177            let outcome = need_client(client)?.sync(transport);
1178            Ok(outcome.to_json())
1179        }
1180        "resetClientId" | "reset_client_id" => {
1181            let client_id = need_client(client)?
1182                .reset_client_id(transport)
1183                .map_err(client_err)?;
1184            Ok(json!({ "clientId": client_id }))
1185        }
1186        "syncUntilIdle" => {
1187            let max_rounds = match params.get("maxRounds") {
1188                None | Some(Value::Null) => None,
1189                Some(value) => Some(
1190                    value
1191                        .as_u64()
1192                        .and_then(|n| u32::try_from(n).ok())
1193                        .filter(|n| *n >= 1)
1194                        .ok_or_else(|| {
1195                            client_err(
1196                                "sync.invalid_request: maxRounds must be a positive integer"
1197                                    .to_owned(),
1198                            )
1199                        })?,
1200                ),
1201            };
1202            let timeout_ms = match params.get("timeoutMs") {
1203                None | Some(Value::Null) => None,
1204                Some(value) => Some(value.as_u64().filter(|ms| *ms >= 1).ok_or_else(|| {
1205                    client_err(
1206                        "sync.invalid_request: timeoutMs must be a positive integer".to_owned(),
1207                    )
1208                })?),
1209            };
1210            let client = need_client(client)?;
1211            let outcome = match timeout_ms {
1212                Some(timeout_ms) => {
1213                    client.sync_until_idle_with_deadline(transport, max_rounds, Some(timeout_ms))
1214                }
1215                None => client.sync_until_idle(transport, max_rounds),
1216            };
1217            Ok(outcome.to_json())
1218        }
1219        "proveCurrentBase" => {
1220            let outcome = params
1221                .get("outcome")
1222                .and_then(Value::as_object)
1223                .ok_or_else(|| client_err("proveCurrentBase missing outcome".to_owned()))?;
1224            let id = outcome
1225                .get("clientCommitId")
1226                .and_then(Value::as_str)
1227                .ok_or_else(|| client_err("proveCurrentBase missing clientCommitId".to_owned()))?;
1228            let sequence = outcome
1229                .get("sequence")
1230                .and_then(Value::as_i64)
1231                .ok_or_else(|| client_err("proveCurrentBase missing sequence".to_owned()))?;
1232            let max_rounds = match params.get("maxRounds") {
1233                None | Some(Value::Null) => None,
1234                Some(value) => Some(
1235                    value
1236                        .as_u64()
1237                        .and_then(|n| u32::try_from(n).ok())
1238                        .filter(|n| *n >= 1)
1239                        .ok_or_else(|| {
1240                            client_err(
1241                                "sync.invalid_request: maxRounds must be a positive integer"
1242                                    .to_owned(),
1243                            )
1244                        })?,
1245                ),
1246            };
1247            Ok(json!(
1248                need_client(client)?.prove_current_base(transport, id, sequence, max_rounds)
1249            ))
1250        }
1251        "readRows" => {
1252            let table = params
1253                .get("table")
1254                .and_then(Value::as_str)
1255                .ok_or_else(|| client_err("readRows missing table".to_owned()))?;
1256            let rows = need_client(client)?.read_rows(table).map_err(client_err)?;
1257            Ok(json!({ "rows": rows }))
1258        }
1259        "query" => {
1260            // The React `useSyncQuery` live-query fast path: arbitrary read-only
1261            // SQL over the local visible tables/views. Params ride as the driver
1262            // value forms (bytes as `{"$bytes": hex}`); rows come back the same.
1263            let sql = params
1264                .get("sql")
1265                .and_then(Value::as_str)
1266                .ok_or_else(|| client_err("query missing sql".to_owned()))?;
1267            let bind = match params.get("params") {
1268                Some(Value::Array(list)) => list.as_slice(),
1269                None | Some(Value::Null) => &[],
1270                Some(_) => return Err(client_err("query params must be a list".to_owned())),
1271            };
1272            let rows = need_client(client)?.query(sql, bind).map_err(client_err)?;
1273            Ok(Value::Object(serde_json::Map::from_iter([(
1274                "rows".to_owned(),
1275                Value::Array(rows.into_iter().map(Value::Object).collect()),
1276            )])))
1277        }
1278        "querySnapshot" => {
1279            let sql = params
1280                .get("sql")
1281                .and_then(Value::as_str)
1282                .ok_or_else(|| client_err("querySnapshot missing sql".to_owned()))?;
1283            let bind = match params.get("params") {
1284                Some(Value::Array(list)) => list.as_slice(),
1285                None | Some(Value::Null) => &[],
1286                Some(_) => {
1287                    return Err(client_err("querySnapshot params must be a list".to_owned()))
1288                }
1289            };
1290            let coverage = parse_window_coverage(params.get("coverage")).map_err(client_err)?;
1291            let owner = parse_query_owner(params.get("owner"), "querySnapshot")?;
1292            let mut snapshot = need_client(client)?
1293                .query_snapshot(
1294                    sql,
1295                    bind,
1296                    &coverage,
1297                    owner.as_ref().map(|(id, tables)| QueryOwner { id, tables }),
1298                )
1299                .map_err(client_err)?;
1300            let rows = std::mem::take(&mut snapshot.rows);
1301            let mut result = serde_json::to_value(snapshot).expect("snapshot serializes");
1302            result["rows"] = Value::Array(rows.into_iter().map(Value::Object).collect());
1303            Ok(result)
1304        }
1305        "localRevision" => {
1306            // §7.5: the public revision read is fallible. An empty shared
1307            // snapshot read reports a corrupt marker instead of swallowing it
1308            // to zero. The internal infallible counter stays for bookkeeping.
1309            let read = need_client(client)?
1310                .snapshot_read(&syncular_client::SnapshotReadRequest::default(), None)
1311                .map_err(read_command_error)?;
1312            Ok(json!({ "revision": read.revision }))
1313        }
1314        "snapshotRead" => {
1315            let parsed = parse_snapshot_read(params)?;
1316            let tables: Vec<&str> = parsed.owner.as_ref().map_or_else(Vec::new, |(_, tables)| {
1317                tables.iter().map(String::as_str).collect()
1318            });
1319            let read = need_client(client)?
1320                .snapshot_read(
1321                    &syncular_client::SnapshotReadRequest {
1322                        statements: parsed
1323                            .statements
1324                            .iter()
1325                            .map(|(sql, params)| syncular_client::SnapshotStatement { sql, params })
1326                            .collect(),
1327                        coverage: &parsed.coverage,
1328                        units: parsed.units,
1329                        commit_ids: parsed.commit_ids,
1330                    },
1331                    parsed.owner.as_ref().map(|(id, _)| QueryOwner {
1332                        id,
1333                        tables: &tables,
1334                    }),
1335                )
1336                .map_err(read_command_error)?;
1337            serde_json::to_value(read).map_err(|error| client_err(error.to_string()))
1338        }
1339        "previousVersionSnapshot" | "previous_version_snapshot" => {
1340            let spec = parse_previous_version_snapshot_spec(params)?;
1341            let snapshot = need_client(client)?
1342                .previous_version_snapshot(&spec)
1343                .map_err(client_err)?;
1344            serde_json::to_value(snapshot).map_err(|error| client_err(error.to_string()))
1345        }
1346        "previousVersionAudit" | "previous_version_audit" => Ok(
1347            match need_client(client)?
1348                .previous_version_audit()
1349                .map_err(client_err)?
1350            {
1351                Some(audit) => {
1352                    serde_json::to_value(audit).map_err(|error| client_err(error.to_string()))?
1353                }
1354                None => Value::Null,
1355            },
1356        ),
1357        "previousVersionDiscard" | "previous_version_discard" => {
1358            let outcome = need_client(client)?
1359                .previous_version_discard()
1360                .map_err(client_err)?;
1361            Ok(json!({
1362                "present": outcome.present,
1363                "discarded": outcome.discarded,
1364            }))
1365        }
1366        "statusSnapshot" => Ok(serde_json::to_value(need_client(client)?.status_snapshot())
1367            .expect("status serializes")),
1368        "diagnosticsSnapshot" => {
1369            let snapshot = need_client(client)?
1370                .diagnostics_snapshot()
1371                .map_err(client_err)?;
1372            Ok(serde_json::to_value(snapshot).expect("diagnostics serialize"))
1373        }
1374        // Conformance/debug drains. Production hosts normally drain these
1375        // immediately after every command, but exposing the exact core output
1376        // here lets both client implementations consume one observation
1377        // vector catalog without bridge inference.
1378        "progressSnapshot" => Ok(
1379            serde_json::to_value(need_client(client)?.progress().snapshot())
1380                .expect("progress JSON"),
1381        ),
1382        "drainChangeBatches" => Ok(json!({
1383            "batches": need_client(client)?.drain_change_batches()
1384        })),
1385        "drainSyncIntents" => Ok(json!({
1386            "intents": need_client(client)?.drain_sync_intents()
1387        })),
1388        // -- §5.10.5 native CRDT (the `crdt-yjs` feature) -----------------------
1389        // Thin forwards to the client core's yrs helpers. The command surface
1390        // stays present-but-unavailable in a lean build: without the feature
1391        // these fail loudly (`client.crdt_unavailable`) rather than being an
1392        // unknown method, so a wrapper's typed method gives a clear error.
1393        #[cfg(feature = "crdt-yjs")]
1394        "crdtText" => {
1395            let (table, row_id, column, name) = crdt_target(params)?;
1396            let text = need_client(client)?
1397                .crdt_text(&table, &row_id, &column, &name)
1398                .map_err(client_err)?;
1399            Ok(json!({ "text": text }))
1400        }
1401        #[cfg(feature = "crdt-yjs")]
1402        "crdtInsertText" => {
1403            let (table, row_id, column, name) = crdt_target(params)?;
1404            let index = params
1405                .get("index")
1406                .and_then(Value::as_u64)
1407                .and_then(|n| u32::try_from(n).ok())
1408                .ok_or_else(|| {
1409                    client_err(
1410                        "sync.invalid_request: crdtInsertText index must be a u32".to_owned(),
1411                    )
1412                })?;
1413            let value = params
1414                .get("value")
1415                .and_then(Value::as_str)
1416                .ok_or_else(|| client_err("crdtInsertText missing value".to_owned()))?;
1417            let id = need_client(client)?
1418                .crdt_insert_text(&table, &row_id, &column, &name, index, value)
1419                .map_err(CommandError::from_client)?;
1420            Ok(json!({ "clientCommitId": id }))
1421        }
1422        #[cfg(feature = "crdt-yjs")]
1423        "crdtDeleteText" => {
1424            let (table, row_id, column, name) = crdt_target(params)?;
1425            let index = params
1426                .get("index")
1427                .and_then(Value::as_u64)
1428                .and_then(|n| u32::try_from(n).ok())
1429                .ok_or_else(|| {
1430                    client_err(
1431                        "sync.invalid_request: crdtDeleteText index must be a u32".to_owned(),
1432                    )
1433                })?;
1434            let len = params
1435                .get("len")
1436                .and_then(Value::as_u64)
1437                .and_then(|n| u32::try_from(n).ok())
1438                .ok_or_else(|| {
1439                    client_err("sync.invalid_request: crdtDeleteText len must be a u32".to_owned())
1440                })?;
1441            let id = need_client(client)?
1442                .crdt_delete_text(&table, &row_id, &column, &name, index, len)
1443                .map_err(CommandError::from_client)?;
1444            Ok(json!({ "clientCommitId": id }))
1445        }
1446        #[cfg(feature = "crdt-yjs")]
1447        "crdtApplyUpdate" => {
1448            let (table, row_id, column, _name) = crdt_target(params)?;
1449            let update = value_bytes(params.get("update")).map_err(client_err)?;
1450            let id = need_client(client)?
1451                .crdt_apply_update(&table, &row_id, &column, &update)
1452                .map_err(CommandError::from_client)?;
1453            Ok(json!({ "clientCommitId": id }))
1454        }
1455        #[cfg(not(feature = "crdt-yjs"))]
1456        "crdtText" | "crdtInsertText" | "crdtDeleteText" | "crdtApplyUpdate" => {
1457            Err(CommandError::new(
1458                "client.crdt_unavailable",
1459                "native CRDT support requires the `crdt-yjs` feature (§5.10.5)",
1460            ))
1461        }
1462
1463        "uploadBlob" => {
1464            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1465            let media_type = optional(params.get("mediaType"), "mediaType", Value::as_str)
1466                .map_err(client_err)?
1467                .map(str::to_owned);
1468            let name = optional(params.get("name"), "blob name", Value::as_str)
1469                .map_err(client_err)?
1470                .map(str::to_owned);
1471            let reference = need_client(client)?
1472                .upload_blob(&bytes, media_type, name)
1473                .map_err(client_err)?;
1474            Ok(json!({ "ref": reference }))
1475        }
1476        "fetchBlob" => {
1477            let blob = params
1478                .get("blob")
1479                .and_then(Value::as_str)
1480                .ok_or_else(|| client_err("fetchBlob missing blob".to_owned()))?
1481                .to_owned();
1482            // fetch_blob_bytes returns (code, message) so the server's blob.*
1483            // code reaches the caller (§5.9.5 cross-scope probe). The command
1484            // boundary owns the JSON byte encoding used by native bindings.
1485            let blob = need_client(client)?.fetch_blob_bytes(transport, &blob)?;
1486            let mut value = serde_json::Map::new();
1487            value.insert("blobId".to_owned(), Value::from(blob.blob_id));
1488            value.insert("byteLength".to_owned(), Value::from(blob.byte_length));
1489            value.insert("bytes".to_owned(), bytes_value(&blob.bytes));
1490            if let Some(media_type) = blob.media_type {
1491                value.insert("mediaType".to_owned(), Value::from(media_type));
1492            }
1493            Ok(Value::Object(serde_json::Map::from_iter([(
1494                "blob".to_owned(),
1495                Value::Object(value),
1496            )])))
1497        }
1498        "conflicts" => {
1499            let conflicts = need_client(client)?.conflicts().to_vec();
1500            Ok(json!({ "conflicts": conflicts }))
1501        }
1502        "rejections" => {
1503            let rejections = need_client(client)?.rejections().to_vec();
1504            Ok(json!({ "rejections": rejections }))
1505        }
1506        "commitDelivery" => {
1507            let client_commit_id = params
1508                .get("clientCommitId")
1509                .and_then(Value::as_str)
1510                .ok_or_else(|| {
1511                    client_err(
1512                        "sync.invalid_request: commitDelivery missing clientCommitId".to_owned(),
1513                    )
1514                })?;
1515            let delivery = need_client(client)?
1516                .commit_delivery(client_commit_id)
1517                .map_err(read_command_error)?;
1518            Ok(json!(delivery))
1519        }
1520        "commitOutcomes" => {
1521            let query = serde_json::from_value::<CommitOutcomeQuery>(
1522                params.get("query").cloned().unwrap_or_else(|| json!({})),
1523            )
1524            .map_err(|error| {
1525                client_err(format!(
1526                    "sync.invalid_request: invalid commit outcome query: {error}"
1527                ))
1528            })?;
1529            let outcomes = need_client(client)?
1530                .commit_outcomes(query)
1531                .map_err(client_err)?;
1532            Ok(json!({ "outcomes": outcomes }))
1533        }
1534        "resolveCommitOutcome" => {
1535            let input = serde_json::from_value::<ResolveCommitOutcomeInput>(
1536                params.get("input").cloned().ok_or_else(|| {
1537                    client_err(
1538                        "sync.invalid_request: resolveCommitOutcome missing input".to_owned(),
1539                    )
1540                })?,
1541            )
1542            .map_err(|error| {
1543                client_err(format!(
1544                    "sync.invalid_request: invalid outcome resolution: {error}"
1545                ))
1546            })?;
1547            let outcome = need_client(client)?
1548                .resolve_commit_outcome(input)
1549                .map_err(client_err)?;
1550            Ok(json!({ "outcome": outcome }))
1551        }
1552        "pendingCommitIds" => {
1553            let ids = need_client(client)?.pending_commit_ids();
1554            Ok(json!({ "ids": ids }))
1555        }
1556        "pendingCommits" => Ok(json!({
1557            "commits": need_client(client)?.pending_commits().map_err(client_err)?
1558        })),
1559        "pendingPayloads" => {
1560            let payloads = need_client(client)?
1561                .pending_payloads()
1562                .map_err(client_err)?;
1563            Ok(json!({
1564                "payloads": payloads.iter().map(|p| bytes_value(p)).collect::<Vec<_>>()
1565            }))
1566        }
1567        "units" => Ok(json!({ "units": need_client(client)?.units().map_err(client_err)? })),
1568        "unit" => {
1569            let id = params
1570                .get("id")
1571                .and_then(Value::as_str)
1572                .ok_or_else(|| client_err("unit missing id".to_owned()))?;
1573            Ok(json!({ "unit": need_client(client)?.unit(id).map_err(client_err)? }))
1574        }
1575        "recreateWithSchema" => {
1576            // §7.4.2 "app ships new code": swap to the new schema on the SAME
1577            // in-memory database (the Rust core has no persistent restart, so
1578            // recreation IS the boot). Fires the §7.4.1 marker check.
1579            let schema = params
1580                .get("schema")
1581                .ok_or_else(|| client_err("recreateWithSchema missing schema".to_owned()))?;
1582            need_client(client)?
1583                .recreate_with_schema(schema)
1584                .map_err(client_err)?;
1585            Ok(json!({}))
1586        }
1587        "localAuthorityState" => Ok(json!({ "state": transport.local_authority_state() })),
1588        // A native host drains buffered realtime traffic after every command;
1589        // this command does nothing else. The FFI host answers its
1590        // `realtime-wake` event with it.
1591        "drainRealtime" => Ok(json!({})),
1592        "attachLocalAuthority" | "abandonLocalAuthorityAttach" => {
1593            let running = need_client(client)?;
1594            if transport.local_authority_state().is_none() {
1595                return Err(CommandError::new(
1596                    LOCAL_AUTHORITY_UNCONFIGURED_CODE,
1597                    "the host configured no localAuthorityPath",
1598                ));
1599            }
1600            // §12.3: hold the client's rounds while the authority uploads or
1601            // rolls back, then restore the host's transport gate.
1602            let enabled = running.transport_enabled();
1603            running.set_transport_enabled(transport, false);
1604            let outcome = if method == "attachLocalAuthority" {
1605                transport.attach_local_authority()
1606            } else {
1607                transport.abandon_local_authority_attach()
1608            };
1609            running.set_transport_enabled(transport, enabled);
1610            outcome.map_err(transport_command_error)?;
1611            Ok(json!({ "effects": CommandEffects::interactive() }))
1612        }
1613        "connectRealtime" => {
1614            need_client(client)?
1615                .connect_realtime(transport)
1616                .map_err(client_err)?;
1617            Ok(json!({}))
1618        }
1619        "disconnectRealtime" => {
1620            // A shut-down or not yet created client holds no socket.
1621            if let Some(running) = client.as_mut() {
1622                running.disconnect_realtime(transport);
1623            }
1624            Ok(json!({}))
1625        }
1626        "setPresence" => {
1627            let scope_key = params
1628                .get("scopeKey")
1629                .and_then(Value::as_str)
1630                .ok_or_else(|| client_err("setPresence missing scopeKey".to_owned()))?
1631                .to_owned();
1632            // §8.6.2: `doc` may be a JSON object or null (a leave).
1633            let doc = params.get("doc");
1634            let doc_ref = match doc {
1635                None | Some(Value::Null) => None,
1636                Some(v) => Some(v),
1637            };
1638            need_client(client)?
1639                .set_presence(transport, &scope_key, doc_ref)
1640                .map_err(client_err)?;
1641            Ok(json!({}))
1642        }
1643        "presence" => {
1644            let scope_key = params
1645                .get("scopeKey")
1646                .and_then(Value::as_str)
1647                .ok_or_else(|| client_err("presence missing scopeKey".to_owned()))?;
1648            let peers = need_client(client)?.presence(scope_key);
1649            Ok(json!({ "peers": peers }))
1650        }
1651
1652        // -- CodecDriver surface (Appendix A) — no client instance needed --
1653        "messageRoundtrip" => {
1654            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1655            match decode_message(&bytes) {
1656                Ok(message) => Ok(json!({
1657                    "ok": true,
1658                    "bytes": bytes_value(&encode_message(&message)),
1659                    "renderedJson": render_message(&message).to_string(),
1660                })),
1661                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
1662            }
1663        }
1664        "segmentRoundtrip" => {
1665            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
1666            match decode_rows_segment(&bytes) {
1667                Ok(segment) => Ok(json!({
1668                    "ok": true,
1669                    "bytes": bytes_value(&encode_rows_segment(&segment)),
1670                    "renderedJson": render_rows_segment(&segment).to_string(),
1671                })),
1672                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
1673            }
1674        }
1675        "realtimeKnown" => {
1676            let text = params
1677                .get("text")
1678                .and_then(Value::as_str)
1679                .ok_or_else(|| client_err("realtimeKnown missing text".to_owned()))?;
1680            let known = matches!(
1681                parse_control(text),
1682                Ok(ControlMessage::Hello { .. })
1683                    | Ok(ControlMessage::Wake { .. })
1684                    | Ok(ControlMessage::Heartbeat { .. })
1685                    | Ok(ControlMessage::Scopes { .. })
1686                    | Ok(ControlMessage::Presence { .. })
1687            );
1688            Ok(json!({ "value": known }))
1689        }
1690
1691        other => Err(client_err(format!("unknown method {other:?}"))),
1692    };
1693    if client
1694        .as_ref()
1695        .is_some_and(|running| !running.transport_enabled())
1696    {
1697        if let Ok(value) = &mut result {
1698            if let Some(effects) = value.get_mut("effects").and_then(Value::as_object_mut) {
1699                effects.remove("sync");
1700            }
1701        }
1702    }
1703    result
1704}
1705
1706#[cfg(test)]
1707mod tests {
1708    use serde_json::{json, Value};
1709    use syncular_client::{
1710        Mutation, SegmentRequest, SyncClient, Transport, TransportError,
1711        SECURITY_PREFLIGHT_REQUIRED_CODE,
1712    };
1713
1714    use super::{
1715        client_err, dispatch, parse_encryption, parse_previous_version_context,
1716        parse_window_coverage, CreateEffects, UnitScopes,
1717    };
1718
1719    #[derive(Default)]
1720    struct NoNetwork {
1721        realtime_connects: usize,
1722        realtime_closes: usize,
1723    }
1724
1725    impl Transport for NoNetwork {
1726        fn sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1727            Err(TransportError::new("sync.transport_failed", "offline"))
1728        }
1729
1730        fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1731            Err(TransportError::new("sync.transport_failed", "offline"))
1732        }
1733
1734        fn download_segment(
1735            &mut self,
1736            _request: &SegmentRequest,
1737            _on_progress: &mut dyn FnMut(u64),
1738        ) -> Result<Vec<u8>, TransportError> {
1739            Err(TransportError::new("sync.transport_failed", "offline"))
1740        }
1741
1742        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1743            self.realtime_connects += 1;
1744            Ok(())
1745        }
1746
1747        fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
1748            Ok(())
1749        }
1750
1751        fn realtime_close(&mut self) -> Result<(), TransportError> {
1752            self.realtime_closes += 1;
1753            Ok(())
1754        }
1755    }
1756
1757    fn schema() -> Value {
1758        json!({
1759            "version": 1,
1760            "tables": [{
1761                "name": "todos",
1762                "columns": [
1763                    { "name": "id", "type": "string", "nullable": false },
1764                    { "name": "list_id", "type": "string", "nullable": false }
1765                ],
1766                "primaryKey": "id",
1767                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
1768            }]
1769        })
1770    }
1771
1772    #[test]
1773    fn native_command_realtime_connection_is_idempotent() {
1774        let mut transport = NoNetwork::default();
1775        let mut client: Option<SyncClient> = None;
1776        let mut effects = CreateEffects::default();
1777        dispatch(
1778            &mut transport,
1779            &mut client,
1780            &mut effects,
1781            "create",
1782            &json!({ "schema": schema() }),
1783        )
1784        .expect("create client");
1785
1786        for _ in 0..2 {
1787            dispatch(
1788                &mut transport,
1789                &mut client,
1790                &mut effects,
1791                "connectRealtime",
1792                &json!({}),
1793            )
1794            .expect("idempotent connect command");
1795        }
1796        assert_eq!(transport.realtime_connects, 1);
1797
1798        dispatch(
1799            &mut transport,
1800            &mut client,
1801            &mut effects,
1802            "disconnectRealtime",
1803            &json!({}),
1804        )
1805        .expect("disconnect command");
1806        dispatch(
1807            &mut transport,
1808            &mut client,
1809            &mut effects,
1810            "disconnectRealtime",
1811            &json!({}),
1812        )
1813        .expect("idempotent disconnect command");
1814        assert_eq!(transport.realtime_closes, 1);
1815        dispatch(
1816            &mut transport,
1817            &mut client,
1818            &mut effects,
1819            "connectRealtime",
1820            &json!({}),
1821        )
1822        .expect("deliberate reconnect command");
1823        assert_eq!(transport.realtime_connects, 2);
1824    }
1825
1826    #[test]
1827    fn local_authority_commands_without_one_report_the_unconfigured_code() {
1828        let mut transport = NoNetwork::default();
1829        let mut client: Option<SyncClient> = None;
1830        let mut effects = CreateEffects::default();
1831        let state = dispatch(
1832            &mut transport,
1833            &mut client,
1834            &mut effects,
1835            "localAuthorityState",
1836            &json!({}),
1837        )
1838        .expect("state without a client");
1839        assert_eq!(state, json!({ "state": null }));
1840        dispatch(
1841            &mut transport,
1842            &mut client,
1843            &mut effects,
1844            "create",
1845            &json!({ "schema": schema() }),
1846        )
1847        .expect("create client");
1848        for method in ["attachLocalAuthority", "abandonLocalAuthorityAttach"] {
1849            let error = dispatch(
1850                &mut transport,
1851                &mut client,
1852                &mut effects,
1853                method,
1854                &json!({}),
1855            )
1856            .expect_err("no local authority");
1857            assert_eq!(error.code, "client.local_authority_unconfigured");
1858        }
1859        let running = client.as_mut().expect("client");
1860        assert!(running.transport_enabled());
1861        assert!(
1862            running.drain_sync_intents().is_empty(),
1863            "the gate never toggled"
1864        );
1865    }
1866
1867    /// A host transport with a scripted §12 local authority.
1868    struct ScriptedAuthority {
1869        opened: Vec<(Value, Option<String>)>,
1870        open_error: Option<TransportError>,
1871        attach_error: Option<TransportError>,
1872        abandons: usize,
1873    }
1874
1875    impl Transport for ScriptedAuthority {
1876        fn sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1877            Err(TransportError::new("sync.transport_failed", "offline"))
1878        }
1879        fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1880            Err(TransportError::new("sync.transport_failed", "offline"))
1881        }
1882        fn download_segment(
1883            &mut self,
1884            _request: &SegmentRequest,
1885            _on_progress: &mut dyn FnMut(u64),
1886        ) -> Result<Vec<u8>, TransportError> {
1887            Err(TransportError::new("sync.transport_failed", "offline"))
1888        }
1889        fn realtime_connect(&mut self, _client_id: &str) -> Result<(), TransportError> {
1890            Ok(())
1891        }
1892        fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
1893            Ok(())
1894        }
1895        fn realtime_close(&mut self) -> Result<(), TransportError> {
1896            Ok(())
1897        }
1898        fn open_local_authority(
1899            &mut self,
1900            schema: &Value,
1901            replica_path: Option<&str>,
1902        ) -> Result<(), TransportError> {
1903            self.opened
1904                .push((schema.clone(), replica_path.map(str::to_owned)));
1905            self.open_error.take().map_or(Ok(()), Err)
1906        }
1907        fn local_authority_state(&self) -> Option<&'static str> {
1908            (!self.opened.is_empty()).then_some("local")
1909        }
1910        fn attach_local_authority(&mut self) -> Result<(), TransportError> {
1911            self.attach_error.take().map_or(Ok(()), Err)
1912        }
1913        fn abandon_local_authority_attach(&mut self) -> Result<(), TransportError> {
1914            self.abandons += 1;
1915            Ok(())
1916        }
1917    }
1918
1919    #[test]
1920    fn local_authority_opens_at_create_and_attach_errors_keep_code_and_details() {
1921        let mut transport = ScriptedAuthority {
1922            opened: Vec::new(),
1923            open_error: Some(TransportError::new("sync.internal_error", "open failed")),
1924            attach_error: Some(TransportError {
1925                code: "sync.attach_rejected".to_owned(),
1926                message: "the remote server refused an attach commit".to_owned(),
1927                details: Some(json!({ "reason": "commit_rejected", "opIndex": 0 })),
1928            }),
1929            abandons: 0,
1930        };
1931        let mut client: Option<SyncClient> = None;
1932        let mut effects = CreateEffects::default();
1933        let error = dispatch(
1934            &mut transport,
1935            &mut client,
1936            &mut effects,
1937            "create",
1938            &json!({ "schema": schema() }),
1939        )
1940        .expect_err("an authority that fails to open fails create");
1941        assert_eq!(error.code, "sync.internal_error");
1942        assert!(client.is_none());
1943
1944        dispatch(
1945            &mut transport,
1946            &mut client,
1947            &mut effects,
1948            "create",
1949            &json!({ "schema": schema() }),
1950        )
1951        .expect("create client");
1952        assert_eq!(transport.opened.len(), 2);
1953        assert_eq!(transport.opened[1], (schema(), None));
1954        let state = dispatch(
1955            &mut transport,
1956            &mut client,
1957            &mut effects,
1958            "localAuthorityState",
1959            &json!({}),
1960        )
1961        .expect("state");
1962        assert_eq!(state, json!({ "state": "local" }));
1963
1964        let error = dispatch(
1965            &mut transport,
1966            &mut client,
1967            &mut effects,
1968            "attachLocalAuthority",
1969            &json!({}),
1970        )
1971        .expect_err("scripted rejection");
1972        assert_eq!(error.code, "sync.attach_rejected");
1973        assert_eq!(
1974            error.details,
1975            Some(json!({ "reason": "commit_rejected", "opIndex": 0 }))
1976        );
1977        assert!(client.as_ref().expect("client").transport_enabled());
1978
1979        let abandoned = dispatch(
1980            &mut transport,
1981            &mut client,
1982            &mut effects,
1983            "abandonLocalAuthorityAttach",
1984            &json!({}),
1985        )
1986        .expect("abandon");
1987        assert_eq!(abandoned["effects"]["sync"]["kind"], "interactive");
1988        assert_eq!(transport.abandons, 1);
1989
1990        // An offline host stays offline across attach.
1991        dispatch(
1992            &mut transport,
1993            &mut client,
1994            &mut effects,
1995            "setTransportEnabled",
1996            &json!({ "enabled": false }),
1997        )
1998        .expect("go offline");
1999        let attached = dispatch(
2000            &mut transport,
2001            &mut client,
2002            &mut effects,
2003            "attachLocalAuthority",
2004            &json!({}),
2005        )
2006        .expect("attach");
2007        assert!(attached["effects"].get("sync").is_none());
2008        assert!(!client.as_ref().expect("client").transport_enabled());
2009    }
2010
2011    #[test]
2012    fn schema_downgrade_has_structured_code_at_create_and_recreate_boundaries() {
2013        let path = temp_db_path("schema-downgrade");
2014        let mut newer = schema();
2015        newer["version"] = json!(3);
2016        let mut older = schema();
2017        older["version"] = json!(2);
2018        let mut transport = NoNetwork::default();
2019        let mut client = None;
2020        let mut effects = CreateEffects::default();
2021        dispatch(
2022            &mut transport,
2023            &mut client,
2024            &mut effects,
2025            "create",
2026            &json!({ "schema": newer, "dbPath": path }),
2027        )
2028        .expect("v3 create");
2029        let error = dispatch(
2030            &mut transport,
2031            &mut client,
2032            &mut effects,
2033            "recreateWithSchema",
2034            &json!({ "schema": older }),
2035        )
2036        .expect_err("refuse recreation");
2037        assert_eq!(error.code, "client.schema_downgrade");
2038        assert_eq!(
2039            error.message,
2040            "client.schema_downgrade: persisted local schema is newer than the requested schema"
2041        );
2042        dispatch(
2043            &mut transport,
2044            &mut client,
2045            &mut effects,
2046            "shutdown",
2047            &json!({}),
2048        )
2049        .expect("shutdown");
2050        let error = dispatch(
2051            &mut transport,
2052            &mut client,
2053            &mut effects,
2054            "create",
2055            &json!({ "schema": older, "dbPath": path }),
2056        )
2057        .expect_err("refuse open");
2058        assert_eq!(error.code, "client.schema_downgrade");
2059        assert!(client.is_none());
2060        dispatch(
2061            &mut transport,
2062            &mut client,
2063            &mut effects,
2064            "create",
2065            &json!({ "schema": newer, "dbPath": path }),
2066        )
2067        .expect("compatible reopen");
2068        dispatch(
2069            &mut transport,
2070            &mut client,
2071            &mut effects,
2072            "shutdown",
2073            &json!({}),
2074        )
2075        .expect("shutdown");
2076        let _ = std::fs::remove_file(path);
2077    }
2078
2079    #[test]
2080    fn native_command_realtime_policy_rides_create_and_refuses_http() {
2081        let mut transport = NoNetwork::default();
2082        let mut client: Option<SyncClient> = None;
2083        let mut effects = CreateEffects::default();
2084        dispatch(
2085            &mut transport,
2086            &mut client,
2087            &mut effects,
2088            "create",
2089            &json!({ "schema": schema(), "realtimePolicy": "required" }),
2090        )
2091        .expect("create client with a required realtime policy");
2092        let result = dispatch(
2093            &mut transport,
2094            &mut client,
2095            &mut effects,
2096            "sync",
2097            &json!({}),
2098        )
2099        .expect("sync command");
2100        assert_eq!(result["ok"], json!(false));
2101        assert_eq!(result["errorCode"], json!("sync.realtime_unavailable"));
2102        assert_eq!(result["realtimeState"], json!("disconnected"));
2103        assert_eq!(result["retryDelayMs"], json!(250));
2104        let snapshot = dispatch(
2105            &mut transport,
2106            &mut client,
2107            &mut effects,
2108            "diagnosticsSnapshot",
2109            &json!({}),
2110        )
2111        .expect("diagnostics command");
2112        assert_eq!(snapshot["host"]["realtime"], json!("disconnected"));
2113        assert_eq!(snapshot["host"]["realtimePolicy"], json!("required"));
2114        assert_eq!(snapshot["host"]["realtimeRetryDelayMs"], json!(250));
2115
2116        let mut second: Option<SyncClient> = None;
2117        let error = dispatch(
2118            &mut transport,
2119            &mut second,
2120            &mut effects,
2121            "create",
2122            &json!({ "schema": schema(), "realtimePolicy": "always" }),
2123        )
2124        .expect_err("an unknown policy is refused");
2125        assert_eq!(error.code, "sync.invalid_request");
2126    }
2127
2128    #[test]
2129    fn parses_portable_encryption_keyring_and_key_id_columns() {
2130        let key_hex = "2a".repeat(32);
2131        let config = parse_encryption(&json!({
2132            "keys": { "practice-key-v1": { "$bytes": key_hex } },
2133            "keyIdColumns": { "patients": "encryption_key_id" }
2134        }))
2135        .expect("portable keyring parses");
2136        assert_eq!(config.keys["practice-key-v1"], vec![0x2a; 32]);
2137        assert_eq!(config.key_id_columns["patients"], "encryption_key_id");
2138    }
2139
2140    #[test]
2141    fn rejects_non_string_key_id_columns() {
2142        let error = parse_encryption(&json!({
2143            "keys": {},
2144            "keyIdColumns": { "patients": 7 }
2145        }))
2146        .expect_err("invalid selector must fail");
2147        assert!(error.contains("must be a string"), "{error}");
2148    }
2149
2150    #[test]
2151    fn subscribe_many_registers_every_unit() {
2152        let mut transport = NoNetwork::default();
2153        let mut client: Option<SyncClient> = None;
2154        let mut effects = CreateEffects::default();
2155        let mut run = |command: &str, params: Value| {
2156            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2157        };
2158        run("create", json!({ "schema": schema() })).expect("create client");
2159        let ids = run(
2160            "subscribeMany",
2161            json!({ "units": [{ "list_id": "list-1" }, { "list_id": "list-2" }] }),
2162        )
2163        .expect("register units")["ids"]
2164            .clone();
2165        let single = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))
2166            .expect("re-register a unit");
2167        assert_eq!(single["id"], ids[0], "a unit id derives from its scope map");
2168        let units = run("units", json!({})).expect("units");
2169        assert_eq!(units["units"].as_array().map(Vec::len), Some(2));
2170        for (index, list) in ["list-1", "list-2"].into_iter().enumerate() {
2171            let unit = run("unit", json!({ "id": ids[index] })).expect("unit");
2172            assert_eq!(unit["unit"]["scopes"], json!({ "list_id": list }));
2173            assert_eq!(unit["unit"]["cursor"], -1);
2174        }
2175        assert_eq!(
2176            run("unit", json!({ "id": "absent" })).expect("unit")["unit"],
2177            Value::Null
2178        );
2179        for scopes in [json!({ "list_id": "*" }), json!({ "other": "x" })] {
2180            let error = run("subscribe", json!({ "scopes": scopes }))
2181                .expect_err("a unit names a non-wildcard value per covered variable");
2182            assert_eq!(error.code, "sync.invalid_subscription", "{scopes}");
2183        }
2184    }
2185
2186    #[test]
2187    fn window_coverage_parser_reads_the_generated_descriptor_and_rejects_malformed_units() {
2188        let parsed = parse_window_coverage(Some(&json!([{
2189            "base": { "variable": "project_id", "fixedScopes": { "tenant_id": "one" } },
2190            "units": ["a", "b"]
2191        }])))
2192        .expect("parse coverage");
2193        assert_eq!(parsed[0].base.variable, "project_id");
2194        assert_eq!(
2195            parsed[0].base.fixed_scopes,
2196            UnitScopes::from([("tenant_id".to_owned(), "one".to_owned())])
2197        );
2198        assert_eq!(parsed[0].units, ["a", "b"]);
2199        for coverage in [
2200            json!({}),
2201            json!([{ "base": { "variable": "project_id" }, "units": ["a", 1] }]),
2202            json!([{ "base": { "fixedScopes": {} }, "units": [] }]),
2203        ] {
2204            let error = parse_window_coverage(Some(&coverage)).expect_err("malformed coverage");
2205            assert!(error.starts_with("sync.invalid_request: "), "{error}");
2206        }
2207    }
2208
2209    #[test]
2210    fn subscribe_and_unsubscribe_queue_an_interactive_sync_intent() {
2211        let mut transport = NoNetwork::default();
2212        let mut client: Option<SyncClient> = None;
2213        let mut effects = CreateEffects::default();
2214        let mut run = |command: &str, params: Value| {
2215            dispatch(&mut transport, &mut client, &mut effects, command, &params)
2216                .expect("command succeeds")
2217        };
2218        run("create", json!({ "schema": schema() }));
2219        run("drainSyncIntents", json!({}));
2220        let id = run("subscribe", json!({ "scopes": { "list_id": "list-1" } }))["id"].clone();
2221        let intents = run("drainSyncIntents", json!({}));
2222        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2223        run("unsubscribe", json!({ "id": id }));
2224        let intents = run("drainSyncIntents", json!({}));
2225        assert_eq!(intents["intents"], json!([{ "kind": "interactive" }]));
2226    }
2227
2228    #[test]
2229    fn security_preflight_is_fail_closed_until_exact_activation() {
2230        let mut transport = NoNetwork::default();
2231        let mut client: Option<SyncClient> = None;
2232        let mut effects = CreateEffects::default();
2233        dispatch(
2234            &mut transport,
2235            &mut client,
2236            &mut effects,
2237            "create",
2238            &json!({ "schema": schema(), "securityPreflight": true }),
2239        )
2240        .expect("preflight create");
2241
2242        let lifecycle = dispatch(
2243            &mut transport,
2244            &mut client,
2245            &mut effects,
2246            "securityLifecycle",
2247            &json!({}),
2248        )
2249        .expect("lifecycle");
2250        assert_eq!(lifecycle, json!({ "state": "preflight" }));
2251
2252        let query_error = dispatch(
2253            &mut transport,
2254            &mut client,
2255            &mut effects,
2256            "query",
2257            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2258        )
2259        .expect_err("protected query must fail");
2260        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2261        let diagnostics_error = dispatch(
2262            &mut transport,
2263            &mut client,
2264            &mut effects,
2265            "diagnosticsSnapshot",
2266            &json!({}),
2267        )
2268        .expect_err("diagnostics unit evidence remains protected");
2269        assert_eq!(diagnostics_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2270
2271        dispatch(
2272            &mut transport,
2273            &mut client,
2274            &mut effects,
2275            "purgeLocalData",
2276            &json!({
2277                "input": {
2278                    "purgeId": "directive-1",
2279                    "targets": [{
2280                        "table": "todos",
2281                        "selectors": { "list_id": ["list-1"] }
2282                    }]
2283                }
2284            }),
2285        )
2286        .expect("authorized local purge remains available");
2287
2288        let repair_error = dispatch(
2289            &mut transport,
2290            &mut client,
2291            &mut effects,
2292            "rebootstrapLocalData",
2293            &json!({ "input": { "rebootstrapId": "blocked-repair" } }),
2294        )
2295        .expect_err("projection repair must remain protected during preflight");
2296        assert_eq!(repair_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2297
2298        dispatch(
2299            &mut transport,
2300            &mut client,
2301            &mut effects,
2302            "activateSecurity",
2303            &json!({}),
2304        )
2305        .expect("activation");
2306        let rows = dispatch(
2307            &mut transport,
2308            &mut client,
2309            &mut effects,
2310            "query",
2311            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2312        )
2313        .expect("active query");
2314        assert_eq!(rows, json!({ "rows": [] }));
2315
2316        dispatch(
2317            &mut transport,
2318            &mut client,
2319            &mut effects,
2320            "beginSecurityPreflight",
2321            &json!({}),
2322        )
2323        .expect("re-enter preflight");
2324        let blocked = dispatch(
2325            &mut transport,
2326            &mut client,
2327            &mut effects,
2328            "mutate",
2329            &json!({ "mutations": [] }),
2330        )
2331        .expect_err("mutation must be gated");
2332        assert_eq!(blocked.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2333    }
2334
2335    #[test]
2336    fn replace_commit_outcome_forwards_typed_failures() {
2337        let schema = json!({
2338            "version": 1,
2339            "tables": [{
2340                "name": "todos",
2341                "columns": [{ "name": "id", "type": "string", "nullable": false }],
2342                "primaryKey": "id",
2343                "scopes": []
2344            }]
2345        });
2346        let mut transport = NoNetwork::default();
2347        let mut client: Option<SyncClient> = None;
2348        let mut effects = CreateEffects::default();
2349        dispatch(
2350            &mut transport,
2351            &mut client,
2352            &mut effects,
2353            "create",
2354            &json!({ "schema": schema }),
2355        )
2356        .expect("create");
2357        for (params, code) in [
2358            (json!({ "sequence": 1 }), "sync.invalid_request"),
2359            (json!({ "clientCommitId": "none" }), "sync.invalid_request"),
2360            (
2361                json!({ "clientCommitId": "none", "sequence": 1, "replacement": [] }),
2362                "sync.outcome_not_found",
2363            ),
2364        ] {
2365            let error = dispatch(
2366                &mut transport,
2367                &mut client,
2368                &mut effects,
2369                "replaceCommitOutcome",
2370                &params,
2371            )
2372            .expect_err("refused");
2373            assert_eq!(error.code, code, "{params}");
2374        }
2375    }
2376
2377    #[test]
2378    fn mutate_and_patch_forward_typed_storage_failures() {
2379        let path = temp_db_path("busy-authoring");
2380        let schema = json!({
2381            "version": 1,
2382            "tables": [{
2383                "name": "todos",
2384                "columns": [
2385                    { "name": "id", "type": "string", "nullable": false },
2386                    { "name": "list_id", "type": "string", "nullable": false },
2387                    { "name": "title", "type": "string", "nullable": false }
2388                ],
2389                "primaryKey": "id",
2390                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2391            }]
2392        });
2393        let mut transport = NoNetwork::default();
2394        let mut client: Option<SyncClient> = None;
2395        let mut effects = CreateEffects::default();
2396        dispatch(
2397            &mut transport,
2398            &mut client,
2399            &mut effects,
2400            "create",
2401            &json!({ "schema": schema, "dbPath": path }),
2402        )
2403        .expect("create file-backed client");
2404        let upsert = |id: &str| {
2405            json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2406                "id": id, "list_id": "l1", "title": "first" } }] })
2407        };
2408        dispatch(
2409            &mut transport,
2410            &mut client,
2411            &mut effects,
2412            "mutate",
2413            &upsert("t1"),
2414        )
2415        .expect("seed row");
2416
2417        let locker = rusqlite::Connection::open(&path).expect("second connection");
2418        locker.execute_batch("BEGIN IMMEDIATE").unwrap();
2419        let busy = dispatch(
2420            &mut transport,
2421            &mut client,
2422            &mut effects,
2423            "mutate",
2424            &upsert("t2"),
2425        )
2426        .expect_err("busy mutate");
2427        assert_eq!(busy.code, "client.storage_busy");
2428        assert!(busy.retryable);
2429        assert_eq!(busy.details.as_ref().unwrap()["sqliteCode"], 5);
2430
2431        let busy_patch = dispatch(
2432            &mut transport,
2433            &mut client,
2434            &mut effects,
2435            "patch",
2436            &json!({ "table": "todos", "rowId": "t1", "partial": { "title": "second" } }),
2437        )
2438        .expect_err("busy patch");
2439        assert_eq!(busy_patch.code, "client.storage_busy");
2440        assert!(busy_patch.retryable);
2441        assert_eq!(busy_patch.details.as_ref().unwrap()["sqliteCode"], 5);
2442
2443        locker.execute_batch("ROLLBACK").unwrap();
2444        let retried = dispatch(
2445            &mut transport,
2446            &mut client,
2447            &mut effects,
2448            "mutate",
2449            &upsert("t2"),
2450        )
2451        .expect("retry after busy");
2452        assert!(retried.get("clientCommitId").is_some());
2453        let _ = std::fs::remove_file(&path);
2454    }
2455
2456    #[test]
2457    fn read_command_error_preserves_code_details_and_retryability() {
2458        let corrupt = super::read_command_error(syncular_client::QueryReadFailure {
2459            code: Some("sync.local_corrupt"),
2460            sqlite_code: None,
2461            sqlite_message: None,
2462            rollback_failure: None,
2463            message: "persisted local revision is invalid".to_owned(),
2464        });
2465        assert_eq!(corrupt.code, "sync.local_corrupt");
2466        assert!(!corrupt.retryable);
2467        assert!(corrupt.details.is_none());
2468
2469        let busy = super::read_command_error(syncular_client::QueryReadFailure {
2470            code: Some("client.storage_busy"),
2471            sqlite_code: Some(5),
2472            sqlite_message: Some("database is locked".to_owned()),
2473            rollback_failure: None,
2474            message: "local SQLite storage is busy".to_owned(),
2475        });
2476        assert_eq!(busy.code, "client.storage_busy");
2477        assert!(busy.retryable);
2478        assert_eq!(
2479            busy.details.expect("busy details")["sqliteCode"],
2480            serde_json::json!(5)
2481        );
2482    }
2483
2484    #[test]
2485    fn mutate_and_patch_report_caller_value_failures_as_invalid_request() {
2486        let path = temp_db_path("caller-values");
2487        let schema = json!({
2488            "version": 1,
2489            "tables": [{
2490                "name": "todos",
2491                "columns": [
2492                    { "name": "id", "type": "string", "nullable": false },
2493                    { "name": "list_id", "type": "string", "nullable": false },
2494                    { "name": "title", "type": "string", "nullable": false },
2495                    { "name": "priority", "type": "integer", "nullable": false }
2496                ],
2497                "primaryKey": "id",
2498                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
2499            }]
2500        });
2501        let mut transport = NoNetwork::default();
2502        let mut client: Option<SyncClient> = None;
2503        let mut effects = CreateEffects::default();
2504        dispatch(
2505            &mut transport,
2506            &mut client,
2507            &mut effects,
2508            "create",
2509            &json!({ "schema": schema, "dbPath": path }),
2510        )
2511        .expect("create file-backed client");
2512        let seed = dispatch(
2513            &mut transport,
2514            &mut client,
2515            &mut effects,
2516            "mutate",
2517            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2518                "id": "t1", "list_id": "l1", "title": "first", "priority": 1 } }] }),
2519        )
2520        .expect("seed row");
2521        let seed_id = seed["clientCommitId"].clone();
2522
2523        // §6.1/§7.1: a caller value the authoring seam rejects is an invalid
2524        // request, not the internal-failure default.
2525        let unknown = dispatch(
2526            &mut transport,
2527            &mut client,
2528            &mut effects,
2529            "mutate",
2530            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2531                "id": "t2", "list_id": "l1", "title": "second", "priority": 1,
2532                "missing_column": 1 } }] }),
2533        )
2534        .expect_err("unknown column");
2535        assert_eq!(unknown.code, "sync.invalid_request");
2536        assert_eq!(unknown.message, "the authoring request is invalid");
2537        assert!(!unknown.retryable);
2538        assert!(unknown.details.as_ref().unwrap()["legacyCause"]
2539            .as_str()
2540            .unwrap()
2541            .contains("unknown column"));
2542
2543        let bad_patch = dispatch(
2544            &mut transport,
2545            &mut client,
2546            &mut effects,
2547            "patch",
2548            &json!({ "table": "todos", "rowId": "t1", "partial": { "priority": "high" } }),
2549        )
2550        .expect_err("bad patch value");
2551        assert_eq!(bad_patch.code, "sync.invalid_request");
2552        assert_eq!(bad_patch.message, "the authoring request is invalid");
2553        assert!(bad_patch.details.as_ref().unwrap()["legacyCause"]
2554            .as_str()
2555            .unwrap()
2556            .contains("priority"));
2557
2558        // Neither rejection enqueued a commit or touched the projection.
2559        let pending = dispatch(
2560            &mut transport,
2561            &mut client,
2562            &mut effects,
2563            "pendingCommitIds",
2564            &json!({}),
2565        )
2566        .expect("pending commit ids");
2567        assert_eq!(pending["ids"], json!([seed_id]));
2568        let rows = dispatch(
2569            &mut transport,
2570            &mut client,
2571            &mut effects,
2572            "query",
2573            &json!({ "sql": "SELECT id, priority FROM todos ORDER BY id" }),
2574        )
2575        .expect("visible rows");
2576        assert_eq!(rows["rows"], json!([{ "id": "t1", "priority": 1 }]));
2577
2578        // The next valid call authorizes normally.
2579        let accepted = dispatch(
2580            &mut transport,
2581            &mut client,
2582            &mut effects,
2583            "mutate",
2584            &json!({ "mutations": [{ "op": "upsert", "table": "todos", "values": {
2585                "id": "t2", "list_id": "l1", "title": "second", "priority": 2 } }] }),
2586        )
2587        .expect("retry after rejection");
2588        assert!(accepted.get("clientCommitId").is_some());
2589        let _ = std::fs::remove_file(&path);
2590    }
2591
2592    #[test]
2593    fn client_err_preserves_retryable_for_storage_busy() {
2594        let busy = client_err("client.storage_busy: local SQLite storage is busy".to_owned());
2595        assert_eq!(busy.code, "client.storage_busy");
2596        assert!(busy.retryable);
2597        // The legacy boundary keeps the full rendered message.
2598        assert_eq!(
2599            busy.message,
2600            "client.storage_busy: local SQLite storage is busy"
2601        );
2602        let full = client_err("client.storage_full: local SQLite storage is full".to_owned());
2603        assert_eq!(full.code, "client.storage_full");
2604        assert!(!full.retryable);
2605    }
2606
2607    #[test]
2608    fn client_err_keeps_a_colon_less_code_identity() {
2609        let error = client_err("sync.unknown_table".to_owned());
2610        assert_eq!(error.code, "sync.unknown_table");
2611        let error = client_err("no client instance created".to_owned());
2612        assert_eq!(error.code, "client.failed");
2613    }
2614
2615    #[cfg(feature = "crdt-yjs")]
2616    #[test]
2617    fn crdt_offsets_outside_u32_are_invalid_requests() {
2618        let mut transport = NoNetwork::default();
2619        let mut client: Option<SyncClient> = None;
2620        let mut effects = CreateEffects::default();
2621        dispatch(
2622            &mut transport,
2623            &mut client,
2624            &mut effects,
2625            "create",
2626            &json!({ "schema": schema() }),
2627        )
2628        .expect("create");
2629        let target = json!({ "table": "todos", "rowId": "t1", "column": "body" });
2630        for (method, extra) in [
2631            (
2632                "crdtInsertText",
2633                json!({ "index": 4_294_967_296u64, "value": "x" }),
2634            ),
2635            ("crdtInsertText", json!({ "index": "0", "value": "x" })),
2636            (
2637                "crdtDeleteText",
2638                json!({ "index": 0, "len": 4_294_967_296u64 }),
2639            ),
2640        ] {
2641            let mut params = target.clone();
2642            params
2643                .as_object_mut()
2644                .unwrap()
2645                .extend(extra.as_object().unwrap().clone());
2646            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
2647                .expect_err("out-of-range offset");
2648            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
2649        }
2650    }
2651
2652    #[test]
2653    fn wrong_typed_optional_fields_are_invalid_requests() {
2654        let created = || {
2655            let mut transport = NoNetwork::default();
2656            let mut client: Option<SyncClient> = None;
2657            let mut effects = CreateEffects::default();
2658            dispatch(
2659                &mut transport,
2660                &mut client,
2661                &mut effects,
2662                "create",
2663                &json!({ "schema": schema() }),
2664            )
2665            .expect("create");
2666            (transport, client, effects)
2667        };
2668        for params in [
2669            json!({ "schema": schema(), "limits": "x" }),
2670            json!({ "schema": schema(), "limits": { "accept": 256 } }),
2671            json!({ "schema": schema(), "limits": { "accept": "15" } }),
2672            json!({ "schema": schema(), "limits": { "limitCommits": 4_294_967_296i64 } }),
2673            json!({ "schema": schema(), "limits": { "outcomeRetentionMaxEntries": -1 } }),
2674            json!({ "schema": schema(), "clientId": 7 }),
2675            json!({ "schema": schema(), "nowMs": "1" }),
2676            json!({ "schema": schema(), "signedUrls": "true" }),
2677            json!({ "schema": schema(), "securityPreflight": 1 }),
2678            json!({ "schema": schema(), "encryption": { "keys": "k" } }),
2679        ] {
2680            let mut transport = NoNetwork::default();
2681            let mut client: Option<SyncClient> = None;
2682            let mut effects = CreateEffects::default();
2683            let error = dispatch(&mut transport, &mut client, &mut effects, "create", &params)
2684                .expect_err("wrong-typed create field");
2685            assert_eq!(error.code, "sync.invalid_request", "{params}");
2686        }
2687        let base = json!({ "variable": "list_id" });
2688        for (method, params) in [
2689            ("setWindow", json!({ "base": base, "units": [1] })),
2690            ("setWindow", json!({ "base": base, "units": "l1" })),
2691            (
2692                "setWindow",
2693                json!({ "base": { "variable": "list_id", "fixedScopes": ["x"] }, "units": [] }),
2694            ),
2695            ("windowState", json!({ "base": {} })),
2696            (
2697                "mutate",
2698                json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": "7" }] }),
2699            ),
2700            (
2701                "patch",
2702                json!({ "table": "todos", "rowId": "t1", "partial": { "title": "x" }, "baseVersion": "7" }),
2703            ),
2704            ("subscribe", json!({ "scopes": { "list_id": ["l1"] } })),
2705            (
2706                "subscribeMany",
2707                json!({ "units": [{ "list_id": "l1" }, 7] }),
2708            ),
2709            (
2710                "uploadBlob",
2711                json!({ "bytes": { "$bytes": "00" }, "mediaType": 1 }),
2712            ),
2713        ] {
2714            let (mut transport, mut client, mut effects) = created();
2715            let error = dispatch(&mut transport, &mut client, &mut effects, method, &params)
2716                .expect_err("wrong-typed field");
2717            assert_eq!(error.code, "sync.invalid_request", "{method} {params}");
2718        }
2719        // An absent or null optional field keeps its default.
2720        let (mut transport, mut client, mut effects) = created();
2721        dispatch(
2722            &mut transport,
2723            &mut client,
2724            &mut effects,
2725            "mutate",
2726            &json!({ "mutations": [{ "op": "delete", "table": "todos", "rowId": "t1", "baseVersion": null }] }),
2727        )
2728        .expect("null baseVersion is absent");
2729    }
2730
2731    #[test]
2732    fn sync_until_idle_rejects_an_invalid_max_rounds_budget() {
2733        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
2734            let mut transport = NoNetwork::default();
2735            let mut client: Option<SyncClient> = None;
2736            let mut effects = CreateEffects::default();
2737            dispatch(
2738                &mut transport,
2739                &mut client,
2740                &mut effects,
2741                "create",
2742                &json!({ "schema": schema() }),
2743            )
2744            .expect("create");
2745            let error = dispatch(
2746                &mut transport,
2747                &mut client,
2748                &mut effects,
2749                "syncUntilIdle",
2750                &json!({ "maxRounds": value }),
2751            )
2752            .expect_err("invalid budget");
2753            assert_eq!(error.code, "sync.invalid_request", "{value}");
2754        }
2755    }
2756
2757    #[test]
2758    fn sync_until_idle_rejects_an_invalid_timeout() {
2759        for value in [json!(0), json!(-1), json!(1.5)] {
2760            let mut transport = NoNetwork::default();
2761            let mut client: Option<SyncClient> = None;
2762            let mut effects = CreateEffects::default();
2763            dispatch(
2764                &mut transport,
2765                &mut client,
2766                &mut effects,
2767                "create",
2768                &json!({ "schema": schema() }),
2769            )
2770            .expect("create");
2771            let error = dispatch(
2772                &mut transport,
2773                &mut client,
2774                &mut effects,
2775                "syncUntilIdle",
2776                &json!({ "timeoutMs": value }),
2777            )
2778            .expect_err("invalid timeout");
2779            assert_eq!(error.code, "sync.invalid_request", "{value}");
2780        }
2781    }
2782
2783    #[test]
2784    fn create_rejects_invalid_push_limits() {
2785        for value in [json!(0), json!(-1), json!(1.5), json!(4_294_967_296u64)] {
2786            let mut transport = NoNetwork::default();
2787            let mut client: Option<SyncClient> = None;
2788            let mut effects = CreateEffects::default();
2789            let error = dispatch(
2790                &mut transport,
2791                &mut client,
2792                &mut effects,
2793                "create",
2794                &json!({
2795                    "schema": schema(),
2796                    "limits": { "maxPushRequestBytes": value }
2797                }),
2798            )
2799            .expect_err("invalid push limit");
2800            assert_eq!(error.code, "sync.invalid_request", "{value}");
2801            assert_eq!(
2802                error.details.as_ref().unwrap()["limit"],
2803                json!("maxPushRequestBytes")
2804            );
2805        }
2806    }
2807
2808    #[test]
2809    fn preflight_allows_only_the_authorized_previous_version_discard() {
2810        let mut transport = NoNetwork::default();
2811        let mut client: Option<SyncClient> = None;
2812        let mut effects = CreateEffects::default();
2813        dispatch(
2814            &mut transport,
2815            &mut client,
2816            &mut effects,
2817            "create",
2818            &json!({ "schema": schema(), "securityPreflight": true }),
2819        )
2820        .expect("preflight create");
2821
2822        // Reads and the audit observe protected local data: still gated.
2823        for method in ["previousVersionSnapshot", "previousVersionAudit"] {
2824            let error = dispatch(
2825                &mut transport,
2826                &mut client,
2827                &mut effects,
2828                method,
2829                &json!({}),
2830            )
2831            .expect_err("previous-version reads stay gated during preflight");
2832            assert_eq!(error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2833        }
2834        // RFC 0006 runs the discard consumer inside the quiesced window, so the
2835        // command router must permit it (feature off here: a clean no-op).
2836        let discarded = dispatch(
2837            &mut transport,
2838            &mut client,
2839            &mut effects,
2840            "previousVersionDiscard",
2841            &json!({}),
2842        )
2843        .expect("authorized cleanup is allowed during preflight");
2844        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
2845        // Preflight closed the socket; releasing it again is allowed.
2846        dispatch(
2847            &mut transport,
2848            &mut client,
2849            &mut effects,
2850            "disconnectRealtime",
2851            &json!({}),
2852        )
2853        .expect("disconnect is allowed during preflight");
2854        assert!(client.as_ref().is_some_and(SyncClient::security_preflight));
2855    }
2856
2857    #[test]
2858    fn disconnect_without_a_client_succeeds() {
2859        let mut transport = NoNetwork::default();
2860        let mut client: Option<SyncClient> = None;
2861        let mut effects = CreateEffects::default();
2862        dispatch(
2863            &mut transport,
2864            &mut client,
2865            &mut effects,
2866            "disconnectRealtime",
2867            &json!({}),
2868        )
2869        .expect("a missing client holds no socket");
2870        dispatch(
2871            &mut transport,
2872            &mut client,
2873            &mut effects,
2874            "create",
2875            &json!({ "schema": schema() }),
2876        )
2877        .expect("create");
2878        dispatch(
2879            &mut transport,
2880            &mut client,
2881            &mut effects,
2882            "shutdown",
2883            &json!({}),
2884        )
2885        .expect("shutdown");
2886        dispatch(
2887            &mut transport,
2888            &mut client,
2889            &mut effects,
2890            "disconnectRealtime",
2891            &json!({}),
2892        )
2893        .expect("a shut-down client holds no socket");
2894    }
2895
2896    #[test]
2897    fn preflight_refuses_a_replacement_create_without_the_flag() {
2898        let mut transport = NoNetwork::default();
2899        let mut client: Option<SyncClient> = None;
2900        let mut effects = CreateEffects::default();
2901        dispatch(
2902            &mut transport,
2903            &mut client,
2904            &mut effects,
2905            "create",
2906            &json!({ "schema": schema(), "securityPreflight": true }),
2907        )
2908        .expect("preflight create");
2909
2910        // The escape the gate exists to prevent: a plain re-create must fail.
2911        let escape = dispatch(
2912            &mut transport,
2913            &mut client,
2914            &mut effects,
2915            "create",
2916            &json!({ "schema": schema() }),
2917        )
2918        .expect_err("plain create must be refused during preflight");
2919        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2920        // The refused create left the preflighted client installed and gated.
2921        let query_error = dispatch(
2922            &mut transport,
2923            &mut client,
2924            &mut effects,
2925            "query",
2926            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2927        )
2928        .expect_err("protected query stays gated");
2929        assert_eq!(query_error.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2930
2931        // A preflighted replacement is permitted and stays gated.
2932        dispatch(
2933            &mut transport,
2934            &mut client,
2935            &mut effects,
2936            "create",
2937            &json!({ "schema": schema(), "securityPreflight": true }),
2938        )
2939        .expect("preflighted replacement create");
2940        let still_gated = dispatch(
2941            &mut transport,
2942            &mut client,
2943            &mut effects,
2944            "query",
2945            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2946        )
2947        .expect_err("replacement stays gated");
2948        assert_eq!(still_gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
2949
2950        // A legitimate activation releases the gate; creates behave as today.
2951        dispatch(
2952            &mut transport,
2953            &mut client,
2954            &mut effects,
2955            "activateSecurity",
2956            &json!({}),
2957        )
2958        .expect("activation");
2959        dispatch(
2960            &mut transport,
2961            &mut client,
2962            &mut effects,
2963            "create",
2964            &json!({ "schema": schema() }),
2965        )
2966        .expect("plain create after activation");
2967        let rows = dispatch(
2968            &mut transport,
2969            &mut client,
2970            &mut effects,
2971            "query",
2972            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
2973        )
2974        .expect("active query");
2975        assert_eq!(rows, json!({ "rows": [] }));
2976    }
2977
2978    /// A file-backed replica: the persisted quarantine marker only exists here,
2979    /// which is why the in-memory tests above could not catch this.
2980    fn temp_db_path(tag: &str) -> String {
2981        std::env::temp_dir()
2982            .join(format!(
2983                "syncular-command-{tag}-{}-{:?}.db",
2984                std::process::id(),
2985                std::time::SystemTime::now()
2986                    .duration_since(std::time::UNIX_EPOCH)
2987                    .expect("clock")
2988                    .as_nanos()
2989            ))
2990            .to_string_lossy()
2991            .into_owned()
2992    }
2993
2994    #[test]
2995    fn an_activated_replica_reopens_plainly_after_shutdown() {
2996        // Shutting an ACTIVATED client down is not a quarantine event. The
2997        // teardown barrier used to call `begin_security_preflight`, which now
2998        // persists the gate, so every cleanly closed replica was marked pending
2999        // and its next plain `create` was refused forever — the reopen path
3000        // restores the flag from the marker and the create guard rejects it.
3001        let path = temp_db_path("activated-reopen");
3002        let mut transport = NoNetwork::default();
3003        let mut client: Option<SyncClient> = None;
3004        let mut effects = CreateEffects::default();
3005
3006        dispatch(
3007            &mut transport,
3008            &mut client,
3009            &mut effects,
3010            "create",
3011            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3012        )
3013        .expect("preflight create");
3014        dispatch(
3015            &mut transport,
3016            &mut client,
3017            &mut effects,
3018            "activateSecurity",
3019            &json!({}),
3020        )
3021        .expect("activation clears the gate");
3022        dispatch(
3023            &mut transport,
3024            &mut client,
3025            &mut effects,
3026            "shutdown",
3027            &json!({}),
3028        )
3029        .expect("shutdown after activation");
3030
3031        // The replica is active on disk, so a plain re-create must be admitted.
3032        dispatch(
3033            &mut transport,
3034            &mut client,
3035            &mut effects,
3036            "create",
3037            &json!({ "schema": schema(), "dbPath": path }),
3038        )
3039        .expect("an activated replica must reopen plainly after shutdown");
3040        let state = dispatch(
3041            &mut transport,
3042            &mut client,
3043            &mut effects,
3044            "securityLifecycle",
3045            &json!({}),
3046        )
3047        .expect("lifecycle");
3048        assert_eq!(state, json!({ "state": "active" }));
3049
3050        let _ = std::fs::remove_file(&path);
3051    }
3052
3053    #[test]
3054    fn an_unactivated_replica_stays_quarantined_across_shutdown_on_disk() {
3055        // The other half, and the reason the marker exists: a replica that
3056        // entered preflight and never activated must still refuse a plain
3057        // re-create after shutdown, even on a host that rebuilt its handle and
3058        // carries no in-memory flag.
3059        let path = temp_db_path("quarantined-reopen");
3060        let mut transport = NoNetwork::default();
3061        let mut client: Option<SyncClient> = None;
3062        let mut effects = CreateEffects::default();
3063
3064        dispatch(
3065            &mut transport,
3066            &mut client,
3067            &mut effects,
3068            "create",
3069            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
3070        )
3071        .expect("preflight create");
3072        dispatch(
3073            &mut transport,
3074            &mut client,
3075            &mut effects,
3076            "shutdown",
3077            &json!({}),
3078        )
3079        .expect("shutdown during preflight");
3080
3081        // A fresh host handle: no in-memory pending flag survives here, so only
3082        // the persisted marker can hold the gate.
3083        let mut rebuilt = CreateEffects::default();
3084        let escape = dispatch(
3085            &mut transport,
3086            &mut client,
3087            &mut rebuilt,
3088            "create",
3089            &json!({ "schema": schema(), "dbPath": path }),
3090        )
3091        .expect_err("a quarantined replica must refuse a plain re-create");
3092        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3093
3094        let _ = std::fs::remove_file(&path);
3095    }
3096
3097    #[test]
3098    fn preflight_gate_survives_shutdown_before_replacement_creates() {
3099        let mut transport = NoNetwork::default();
3100        let mut client: Option<SyncClient> = None;
3101        let mut effects = CreateEffects::default();
3102        dispatch(
3103            &mut transport,
3104            &mut client,
3105            &mut effects,
3106            "create",
3107            &json!({ "schema": schema(), "securityPreflight": true }),
3108        )
3109        .expect("preflight create");
3110        dispatch(
3111            &mut transport,
3112            &mut client,
3113            &mut effects,
3114            "shutdown",
3115            &json!({}),
3116        )
3117        .expect("shutdown during preflight");
3118        assert!(client.is_none());
3119
3120        // The pending preflight rides `effects` across the empty client slot.
3121        let escape = dispatch(
3122            &mut transport,
3123            &mut client,
3124            &mut effects,
3125            "create",
3126            &json!({ "schema": schema() }),
3127        )
3128        .expect_err("shutdown + plain create must stay refused");
3129        assert_eq!(escape.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3130
3131        dispatch(
3132            &mut transport,
3133            &mut client,
3134            &mut effects,
3135            "create",
3136            &json!({ "schema": schema(), "securityPreflight": true }),
3137        )
3138        .expect("preflighted re-create");
3139        dispatch(
3140            &mut transport,
3141            &mut client,
3142            &mut effects,
3143            "activateSecurity",
3144            &json!({}),
3145        )
3146        .expect("activation");
3147
3148        // An ACTIVATED client shut down cleanly may be recreated plainly.
3149        dispatch(
3150            &mut transport,
3151            &mut client,
3152            &mut effects,
3153            "shutdown",
3154            &json!({}),
3155        )
3156        .expect("shutdown after activation");
3157        dispatch(
3158            &mut transport,
3159            &mut client,
3160            &mut effects,
3161            "create",
3162            &json!({ "schema": schema() }),
3163        )
3164        .expect("plain create after an activated shutdown");
3165    }
3166
3167    #[test]
3168    fn activate_security_refuses_headers_and_keeps_the_gate_closed() {
3169        let mut transport = NoNetwork::default();
3170        let mut client: Option<SyncClient> = None;
3171        let mut effects = CreateEffects::default();
3172        dispatch(
3173            &mut transport,
3174            &mut client,
3175            &mut effects,
3176            "create",
3177            &json!({ "schema": schema(), "securityPreflight": true }),
3178        )
3179        .expect("preflight create");
3180
3181        // Activation headers fail loudly and keep the gate closed.
3182        let invalid = dispatch(
3183            &mut transport,
3184            &mut client,
3185            &mut effects,
3186            "activateSecurity",
3187            &json!({ "headers": { "authorization": 7 } }),
3188        )
3189        .expect_err("non-string header must fail");
3190        assert_eq!(invalid.code, "sync.invalid_request");
3191        let lifecycle = dispatch(
3192            &mut transport,
3193            &mut client,
3194            &mut effects,
3195            "securityLifecycle",
3196            &json!({}),
3197        )
3198        .expect("lifecycle");
3199        assert_eq!(lifecycle, json!({ "state": "preflight" }));
3200
3201        // Well-formed headers are refused too: the header source replaced
3202        // them. Activation without them opens the gate.
3203        let refused = dispatch(
3204            &mut transport,
3205            &mut client,
3206            &mut effects,
3207            "activateSecurity",
3208            &json!({ "headers": { "authorization": "Bearer fresh" } }),
3209        )
3210        .expect_err("activation headers are refused");
3211        assert_eq!(refused.code, "sync.invalid_request");
3212        dispatch(
3213            &mut transport,
3214            &mut client,
3215            &mut effects,
3216            "activateSecurity",
3217            &json!({}),
3218        )
3219        .expect("activation");
3220        let lifecycle = dispatch(
3221            &mut transport,
3222            &mut client,
3223            &mut effects,
3224            "securityLifecycle",
3225            &json!({}),
3226        )
3227        .expect("lifecycle");
3228        assert_eq!(lifecycle, json!({ "state": "active" }));
3229    }
3230
3231    #[test]
3232    fn add_encryption_keys_extends_an_active_keyring() {
3233        let mut transport = NoNetwork::default();
3234        let mut client: Option<SyncClient> = None;
3235        let mut effects = CreateEffects::default();
3236        let key = |byte: &str| json!({ "$bytes": byte.repeat(32) });
3237        let closed = dispatch(
3238            &mut transport,
3239            &mut client,
3240            &mut effects,
3241            "addEncryptionKeys",
3242            &json!({ "keys": { "k2": key("2b") } }),
3243        )
3244        .expect_err("no client is open");
3245        assert_eq!(closed.code, "client.closed");
3246        assert_eq!(closed.message, "no client is open");
3247
3248        dispatch(
3249            &mut transport,
3250            &mut client,
3251            &mut effects,
3252            "create",
3253            &json!({ "schema": schema(), "encryption": { "keys": { "k1": key("2a") } } }),
3254        )
3255        .expect("create");
3256        let mut add = |client: &mut Option<SyncClient>, params: Value| {
3257            dispatch(
3258                &mut transport,
3259                client,
3260                &mut effects,
3261                "addEncryptionKeys",
3262                &params,
3263            )
3264        };
3265        assert_eq!(
3266            add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("add while active"),
3267            json!({})
3268        );
3269        // The installed key answers a conflicting re-add with its id.
3270        let conflict = add(&mut client, json!({ "keys": { "k2": key("2c") } }))
3271            .expect_err("conflicting bytes");
3272        assert_eq!(conflict.code, "sync.invalid_request");
3273        assert_eq!(
3274            conflict.message,
3275            "encryption key id is already held with different key bytes"
3276        );
3277        assert_eq!(conflict.details, Some(json!({ "keyId": "k2" })));
3278        add(&mut client, json!({ "keys": { "k2": key("2b") } })).expect("identical re-add");
3279
3280        let malformed = add(&mut client, json!({ "keys": { "k3": { "$bytes": "zz" } } }))
3281            .expect_err("malformed hex");
3282        assert_eq!(malformed.code, "sync.invalid_request");
3283        assert_eq!(malformed.details, Some(json!({ "keyId": "k3" })));
3284        // Two bad keys: the first in key-id order is named, whatever the input order.
3285        let first = add(
3286            &mut client,
3287            json!({ "keys": { "k9": { "$bytes": "2a2a" }, "k4": { "$bytes": "zz" } } }),
3288        )
3289        .expect_err("two bad keys");
3290        assert_eq!(first.details, Some(json!({ "keyId": "k4" })));
3291        let short = add(
3292            &mut client,
3293            json!({ "keys": { "k3": { "$bytes": "2a2a" } } }),
3294        )
3295        .expect_err("wrong length");
3296        assert_eq!(short.message, "encryption key must be 32 bytes (AES-256)");
3297        assert_eq!(short.details, Some(json!({ "keyId": "k3" })));
3298        for params in [json!({}), json!({ "keys": [] })] {
3299            assert_eq!(
3300                add(&mut client, params).expect_err("keys object").code,
3301                "sync.invalid_request"
3302            );
3303        }
3304
3305        dispatch(
3306            &mut transport,
3307            &mut client,
3308            &mut effects,
3309            "beginSecurityPreflight",
3310            &json!({}),
3311        )
3312        .expect("preflight");
3313        let gated = dispatch(
3314            &mut transport,
3315            &mut client,
3316            &mut effects,
3317            "addEncryptionKeys",
3318            &json!({ "keys": { "k3": key("2d") } }),
3319        )
3320        .expect_err("preflight refuses the addition");
3321        assert_eq!(gated.code, SECURITY_PREFLIGHT_REQUIRED_CODE);
3322    }
3323
3324    fn schema_v2() -> Value {
3325        json!({
3326            "version": 2,
3327            "tables": [{
3328                "name": "todos",
3329                "columns": [
3330                    { "name": "id", "type": "string", "nullable": false },
3331                    { "name": "list_id", "type": "string", "nullable": false },
3332                    { "name": "note", "type": "string", "nullable": true }
3333                ],
3334                "primaryKey": "id",
3335                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
3336            }]
3337        })
3338    }
3339
3340    fn previous_version_enabled() -> Value {
3341        json!({ "enabled": true })
3342    }
3343
3344    fn container_path(db_path: &str) -> String {
3345        format!("{db_path}.prev-context")
3346    }
3347
3348    #[test]
3349    fn previous_version_config_parser_matches_ts_keys_and_defaults() {
3350        assert_eq!(parse_previous_version_context(None).expect("absent"), None);
3351        let defaults = parse_previous_version_context(Some(&json!({})))
3352            .expect("empty")
3353            .expect("present");
3354        assert!(!defaults.enabled);
3355        assert_eq!(defaults.max_bytes, 8 * 1024 * 1024);
3356        assert_eq!(defaults.max_rows, 20_000);
3357        assert_eq!(defaults.max_tables, 32);
3358        assert_eq!(defaults.max_row_bytes, 1024 * 1024);
3359        assert_eq!(defaults.max_age_ms, 24 * 60 * 60 * 1000);
3360
3361        let configured = parse_previous_version_context(Some(&json!({
3362            "enabled": true,
3363            "maxBytes": 1024,
3364            "maxRows": 3,
3365            "maxTables": 2,
3366            "maxRowBytes": 5,
3367            "maxAgeMs": 7
3368        })))
3369        .expect("configured")
3370        .expect("present");
3371        assert!(configured.enabled);
3372        assert_eq!(configured.max_bytes, 1024);
3373        assert_eq!(configured.max_rows, 3);
3374        assert_eq!(configured.max_tables, 2);
3375        assert_eq!(configured.max_row_bytes, 5);
3376        assert_eq!(configured.max_age_ms, 7);
3377
3378        // Invalid values fail loudly instead of silently defaulting.
3379        for (value, expected) in [
3380            (json!([]), "must be an object"),
3381            (json!({ "enabled": "yes" }), "enabled must be a boolean"),
3382            (
3383                json!({ "maxBytes": 0 }),
3384                "maxBytes must be a positive safe integer",
3385            ),
3386            (
3387                json!({ "maxRows": -1 }),
3388                "maxRows must be a positive safe integer",
3389            ),
3390            (
3391                json!({ "maxTables": 1.5 }),
3392                "maxTables must be a positive safe integer",
3393            ),
3394            (
3395                json!({ "maxRowBytes": "1" }),
3396                "maxRowBytes must be a positive safe integer",
3397            ),
3398            (
3399                json!({ "maxAgeMs": 0 }),
3400                "maxAgeMs must be a positive safe integer",
3401            ),
3402        ] {
3403            let error = parse_previous_version_context(Some(&value)).expect_err("must fail");
3404            assert_eq!(error.code, "sync.invalid_request", "{value}");
3405            assert!(
3406                error.message.contains(expected),
3407                "{value}: {}",
3408                error.message
3409            );
3410        }
3411    }
3412
3413    #[test]
3414    fn invalid_previous_version_config_fails_create_loudly() {
3415        let mut transport = NoNetwork::default();
3416        let mut client: Option<SyncClient> = None;
3417        let mut effects = CreateEffects::default();
3418        let error = dispatch(
3419            &mut transport,
3420            &mut client,
3421            &mut effects,
3422            "create",
3423            &json!({ "schema": schema(), "previousVersionContext": { "enabled": true, "maxRows": 0 } }),
3424        )
3425        .expect_err("invalid config must fail the create");
3426        assert_eq!(error.code, "sync.invalid_request");
3427        assert!(error.message.contains("maxRows"), "{}", error.message);
3428        assert!(client.is_none(), "no client may be installed");
3429    }
3430
3431    #[test]
3432    fn previous_version_snapshot_reports_not_configured_by_default() {
3433        let mut transport = NoNetwork::default();
3434        let mut client: Option<SyncClient> = None;
3435        let mut effects = CreateEffects::default();
3436        dispatch(
3437            &mut transport,
3438            &mut client,
3439            &mut effects,
3440            "create",
3441            &json!({ "schema": schema() }),
3442        )
3443        .expect("create");
3444        let snapshot = dispatch(
3445            &mut transport,
3446            &mut client,
3447            &mut effects,
3448            "previousVersionSnapshot",
3449            &json!({ "table": "todos" }),
3450        )
3451        .expect("snapshot");
3452        assert_eq!(snapshot["state"], json!("previousVersion"));
3453        assert_eq!(snapshot["available"], json!(false));
3454        assert_eq!(snapshot["reason"], json!("not-configured"));
3455        assert_eq!(snapshot["rows"], json!([]));
3456        assert_eq!(snapshot["truncated"], json!(false));
3457        assert_eq!(snapshot["currentVersion"], json!(1));
3458        let discarded = dispatch(
3459            &mut transport,
3460            &mut client,
3461            &mut effects,
3462            "previousVersionDiscard",
3463            &json!({}),
3464        )
3465        .expect("discard");
3466        assert_eq!(discarded, json!({ "present": false, "discarded": false }));
3467        assert_eq!(
3468            dispatch(
3469                &mut transport,
3470                &mut client,
3471                &mut effects,
3472                "previousVersionAudit",
3473                &json!({}),
3474            )
3475            .expect("audit"),
3476            Value::Null
3477        );
3478    }
3479
3480    #[test]
3481    fn previous_version_commands_round_trip_through_the_dispatcher() {
3482        let path = temp_db_path("previous-version");
3483        let mut transport = NoNetwork::default();
3484        let mut client: Option<SyncClient> = None;
3485        let mut effects = CreateEffects::default();
3486
3487        // A v1 replica with one pending local row and the feature on.
3488        dispatch(
3489            &mut transport,
3490            &mut client,
3491            &mut effects,
3492            "create",
3493            &json!({
3494                "schema": schema(),
3495                "dbPath": path,
3496                "previousVersionContext": previous_version_enabled()
3497            }),
3498        )
3499        .expect("create v1");
3500        client
3501            .as_mut()
3502            .expect("client")
3503            .mutate(vec![Mutation::Upsert {
3504                table: "todos".to_owned(),
3505                values: serde_json::Map::from_iter([
3506                    ("id".to_owned(), json!("t1")),
3507                    ("list_id".to_owned(), json!("l1")),
3508                ]),
3509                base_version: None,
3510            }])
3511            .expect("seed a local row");
3512        dispatch(
3513            &mut transport,
3514            &mut client,
3515            &mut effects,
3516            "shutdown",
3517            &json!({}),
3518        )
3519        .expect("shutdown");
3520
3521        // The bump captures into the sibling file.
3522        dispatch(
3523            &mut transport,
3524            &mut client,
3525            &mut effects,
3526            "create",
3527            &json!({
3528                "schema": schema_v2(),
3529                "dbPath": path,
3530                "previousVersionContext": previous_version_enabled()
3531            }),
3532        )
3533        .expect("create v2");
3534        assert!(
3535            std::path::Path::new(&container_path(&path)).exists(),
3536            "the bump must leave a container file"
3537        );
3538        let status = dispatch(
3539            &mut transport,
3540            &mut client,
3541            &mut effects,
3542            "statusSnapshot",
3543            &json!({}),
3544        )
3545        .expect("status");
3546        assert_eq!(
3547            status["previousVersionContext"]["present"],
3548            json!(true),
3549            "{status}"
3550        );
3551        assert!(
3552            status["previousVersionContext"]["createdAtMs"].is_i64(),
3553            "{status}"
3554        );
3555
3556        let snapshot = dispatch(
3557            &mut transport,
3558            &mut client,
3559            &mut effects,
3560            "previousVersionSnapshot",
3561            &json!({ "table": "todos" }),
3562        )
3563        .expect("snapshot");
3564        assert_eq!(snapshot["state"], json!("previousVersion"));
3565        assert_eq!(snapshot["available"], json!(true));
3566        assert_eq!(snapshot["previousVersion"], json!(1));
3567        assert_eq!(snapshot["currentVersion"], json!(2));
3568        assert_eq!(snapshot["truncated"], json!(false));
3569        assert_eq!(snapshot["rows"][0]["id"], json!("t1"));
3570        assert_eq!(snapshot["rows"][0]["list_id"], json!("l1"));
3571
3572        // Unknown previous table and a bad limit are loud request errors.
3573        let unknown = dispatch(
3574            &mut transport,
3575            &mut client,
3576            &mut effects,
3577            "previousVersionSnapshot",
3578            &json!({ "table": "absent" }),
3579        )
3580        .expect_err("unknown previous table");
3581        assert_eq!(unknown.code, "sync.invalid_request");
3582        let bad_limit = dispatch(
3583            &mut transport,
3584            &mut client,
3585            &mut effects,
3586            "previousVersionSnapshot",
3587            &json!({ "table": "todos", "limit": 0 }),
3588        )
3589        .expect_err("bad limit");
3590        assert_eq!(bad_limit.code, "sync.invalid_request");
3591
3592        // D6: the audit names the pending commit's classification, with no
3593        // envelope and nothing dropped.
3594        let audit = dispatch(
3595            &mut transport,
3596            &mut client,
3597            &mut effects,
3598            "previousVersionAudit",
3599            &json!({}),
3600        )
3601        .expect("audit");
3602        assert_eq!(audit["v"], json!(1));
3603        assert_eq!(audit["fromVersion"], json!(1));
3604        assert_eq!(audit["toVersion"], json!(2));
3605        assert_eq!(audit["pending"], json!(1));
3606        assert_eq!(audit["encodable"], json!(1));
3607        assert_eq!(audit["incompatible"], json!([]));
3608        assert!(audit.get("operations").is_none());
3609
3610        // The executable downgrade step, idempotent.
3611        let discarded = dispatch(
3612            &mut transport,
3613            &mut client,
3614            &mut effects,
3615            "previousVersionDiscard",
3616            &json!({}),
3617        )
3618        .expect("discard");
3619        assert_eq!(discarded, json!({ "present": true, "discarded": true }));
3620        assert!(!std::path::Path::new(&container_path(&path)).exists());
3621        let again = dispatch(
3622            &mut transport,
3623            &mut client,
3624            &mut effects,
3625            "previousVersionDiscard",
3626            &json!({}),
3627        )
3628        .expect("idempotent discard");
3629        assert_eq!(again, json!({ "present": false, "discarded": false }));
3630
3631        // Storage read directly: both metadata records are gone.
3632        let inspect = rusqlite::Connection::open(&path).expect("inspect replica");
3633        let remaining: i64 = inspect
3634            .query_row(
3635                "SELECT COUNT(*) FROM _syncular_meta WHERE key IN (?1, ?2)",
3636                rusqlite::params!["previousVersionContext", "previousVersionAudit"],
3637                |row| row.get(0),
3638            )
3639            .expect("count meta");
3640        assert_eq!(remaining, 0);
3641
3642        let _ = std::fs::remove_file(&path);
3643    }
3644
3645    #[test]
3646    fn previous_version_ttl_expires_at_read_through_the_dispatcher() {
3647        let path = temp_db_path("previous-version-ttl");
3648        let mut transport = NoNetwork::default();
3649        let mut client: Option<SyncClient> = None;
3650        let mut effects = CreateEffects::default();
3651        dispatch(
3652            &mut transport,
3653            &mut client,
3654            &mut effects,
3655            "create",
3656            &json!({
3657                "schema": schema(),
3658                "dbPath": path,
3659                "previousVersionContext": previous_version_enabled()
3660            }),
3661        )
3662        .expect("create v1");
3663        dispatch(
3664            &mut transport,
3665            &mut client,
3666            &mut effects,
3667            "shutdown",
3668            &json!({}),
3669        )
3670        .expect("shutdown");
3671
3672        // The injected clock is two seconds past the capture, with a TTL far
3673        // larger than the boot gap but far smaller than the skew, so the boot
3674        // reconcile keeps the container and the read expires it.
3675        let now_ms = std::time::SystemTime::now()
3676            .duration_since(std::time::UNIX_EPOCH)
3677            .expect("clock")
3678            .as_millis() as i64
3679            + 2_000;
3680        dispatch(
3681            &mut transport,
3682            &mut client,
3683            &mut effects,
3684            "create",
3685            &json!({
3686                "schema": schema_v2(),
3687                "dbPath": path,
3688                "nowMs": now_ms,
3689                "previousVersionContext": { "enabled": true, "maxAgeMs": 500 }
3690            }),
3691        )
3692        .expect("create v2");
3693        assert!(std::path::Path::new(&container_path(&path)).exists());
3694        let snapshot = dispatch(
3695            &mut transport,
3696            &mut client,
3697            &mut effects,
3698            "previousVersionSnapshot",
3699            &json!({ "table": "todos" }),
3700        )
3701        .expect("snapshot");
3702        assert_eq!(snapshot["available"], json!(false));
3703        assert_eq!(snapshot["reason"], json!("expired"));
3704        assert_eq!(snapshot["rows"], json!([]));
3705        // The TTL discards, and the FILE is what must be gone.
3706        assert!(!std::path::Path::new(&container_path(&path)).exists());
3707
3708        let _ = std::fs::remove_file(&path);
3709    }
3710
3711    #[test]
3712    fn presence_event_carries_the_fanout_scope_and_the_publish_refusal() {
3713        assert_eq!(
3714            super::presence_event(
3715                r#"{"event":"presence","data":{"scopeKey":"room:42","kind":"leave","actorId":"a","clientId":"c","doc":null,"timestamp":1}}"#
3716            ),
3717            Some(json!({ "type": "presence", "scopeKey": "room:42" }))
3718        );
3719        for code in ["presence.too_large", "presence.forbidden"] {
3720            let frame = format!(
3721                r#"{{"event":"presence","data":{{"scopeKey":"room:42","error":"{code}"}}}}"#
3722            );
3723            assert_eq!(
3724                super::presence_event(&frame),
3725                Some(json!({ "type": "presence", "scopeKey": "room:42", "error": code }))
3726            );
3727        }
3728    }
3729
3730    #[test]
3731    fn presence_event_ignores_malformed_frames_and_unknown_codes() {
3732        for frame in [
3733            r#"{"event":"presence","data":{}}"#,
3734            r#"{"event":"presence","data":{"scopeKey":"room:42","error":"presence.nope"}}"#,
3735            r#"{"event":"presence","data":{"scopeKey":"room:42","error":7}}"#,
3736            r#"{"event":"sync","data":{}}"#,
3737            "not json",
3738        ] {
3739            assert_eq!(super::presence_event(frame), None, "{frame}");
3740        }
3741    }
3742}