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