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