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