Skip to main content

syncular_command/
lib.rs

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