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