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