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