Skip to main content

syncular_command/
lib.rs

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