Skip to main content

tauri_plugin_syncular/
core.rs

1//! The transport-agnostic, Tauri-free CORE of the plugin.
2//!
3//! Everything here is plain Rust with no dependency on the `tauri` crate, so
4//! it is unit-testable without a window or a mock runtime. The Tauri shell
5//! (see `lib.rs`) is a thin layer that owns one [`SyncularCore`] on a
6//! dedicated thread, forwards mutable commands and raw queries to it, and pumps
7//! drained events onto the `syncular://event` Tauri channel. The shell's
8//! file-backed atomic snapshot sidecar is intentionally outside this mutable
9//! core and uses a separate read-only SQLite connection.
10//!
11//! This mirrors the `syncular-ffi` `Handle`: one owned [`SyncClient`], one
12//! owned [`HostTransport`] (native HTTP+WS via the `native-transport` feature),
13//! and an exact core-output event queue. The plugin is the THIRD consumer of the shared
14//! `syncular-command` router (after the conformance shim and the FFI core), so
15//! the command surface stays conformance-locked.
16//!
17//! ## Thread-safety, honestly
18//!
19//! [`SyncClient`] is synchronous and NOT `Sync` — it owns a rusqlite
20//! connection. Exactly one thread owns the mutable core, and all mutable access
21//! arrives through a command mailbox (an mpsc channel). Tauri commands never
22//! touch that client directly. The background host loop (§8.4) runs on the same
23//! owner, so the mutable connection is never accessed concurrently. The shell
24//! may independently read the file database through SQLite's snapshot model;
25//! it does not access this `SyncClient`.
26
27use std::collections::VecDeque;
28
29use serde_json::{json, Value};
30use syncular_client::{ClientDiagnosticsRequest, SyncClient, SyncIntent};
31use syncular_command::{dispatch, CreateEffects};
32
33use crate::transport::{self, HostTransport};
34
35/// One client-observable event (§8 realtime signals + §6 conflicts + §1.6
36/// schema floor + §7.3 lease). JSON-able; delivered onto the Tauri channel.
37/// The same event vocabulary the FFI `poll_event` surfaces.
38#[derive(Debug, Clone)]
39pub struct Event {
40    pub json: Value,
41}
42
43/// The Tauri-free core: one client, its owned transport, explicit scheduling
44/// state, and the pending exact-event queue. Lives on ONE owning thread.
45pub struct SyncularCore {
46    client: Option<SyncClient>,
47    transport: HostTransport,
48    effects: CreateEffects,
49    queue: VecDeque<Event>,
50    last_diagnostics_fingerprint: Option<Value>,
51    /// Diagnostics snapshots are computed only after a consumer registers —
52    /// the analogue of the web client's `ClientDiagnosticsEmitter.observed`.
53    /// Set by the explicit `enableDiagnostics` command and by the first
54    /// `diagnosticsSnapshot` pull (the devtools attach signal).
55    diagnostics_observed: bool,
56    interactive_sync: bool,
57    background_sync_ms: Option<u64>,
58}
59
60impl SyncularCore {
61    /// Build a core from the plugin config JSON (`baseUrl`, `headers`, …). A
62    /// `baseUrl` under the `native-transport` feature owns a real HTTP+WS
63    /// transport; without it the core is client-local only (tests, offline).
64    pub fn new(config: &Value) -> Result<Self, String> {
65        Self::new_with_notify(config, None)
66    }
67
68    pub fn new_with_notify(
69        config: &Value,
70        notify: Option<std::sync::Arc<dyn Fn() + Send + Sync>>,
71    ) -> Result<Self, String> {
72        let transport = HostTransport::from_config_with_notify(config, notify)?;
73        Ok(SyncularCore {
74            client: None,
75            transport,
76            effects: CreateEffects::default(),
77            queue: VecDeque::new(),
78            last_diagnostics_fingerprint: None,
79            diagnostics_observed: false,
80            interactive_sync: false,
81            background_sync_ms: None,
82        })
83    }
84
85    /// Run one JSON command (`{"method","params"}`) through the shared router,
86    /// then drain inbound realtime traffic and exact core events. Returns the
87    /// driver-protocol `{"result"|"error"}` reply.
88    pub fn command(&mut self, command: &Value) -> Value {
89        let method = command.get("method").and_then(Value::as_str).unwrap_or("");
90        let params = command.get("params").cloned().unwrap_or(Value::Null);
91        if method == "enableDiagnostics" {
92            // Host-local registration signal (the Tauri event channel carries
93            // no listener count). Emission starts on this drain: the reset
94            // fingerprint guarantees the observer receives a first snapshot.
95            self.diagnostics_observed = true;
96            self.last_diagnostics_fingerprint = None;
97            self.drain_realtime();
98            self.drain_core_outputs();
99            self.emit_diagnostics_if_changed();
100            return json!({ "result": {} });
101        }
102        if method == "diagnosticsSnapshot" {
103            // A direct pull proves a diagnostics consumer exists; keep the
104            // pushed snapshots flowing for it from here on.
105            self.diagnostics_observed = true;
106        }
107        let result = dispatch(
108            &mut self.transport,
109            &mut self.client,
110            &mut self.effects,
111            method,
112            &params,
113        );
114        if method == "create" {
115            self.last_diagnostics_fingerprint = None;
116            self.transport.set_signed_urls(self.effects.signed_urls);
117        }
118        if method == "beginSecurityPreflight"
119            || method == "shutdown"
120            || (method == "create"
121                && params
122                    .get("securityPreflight")
123                    .and_then(Value::as_bool)
124                    .unwrap_or(false))
125        {
126            self.interactive_sync = false;
127            self.background_sync_ms = None;
128        }
129        if let Ok(value) = &result {
130            if value.pointer("/effects/sync/kind").and_then(Value::as_str) == Some("interactive") {
131                self.interactive_sync = true;
132            }
133        }
134        self.drain_realtime();
135        self.drain_core_outputs();
136        self.emit_diagnostics_if_changed();
137        match result {
138            Ok(mut value) => {
139                // The router's effects are consumed by this native host above;
140                // they are not part of the public command acknowledgement.
141                if let Some(object) = value.as_object_mut() {
142                    object.remove("effects");
143                }
144                json!({ "result": value })
145            }
146            Err((code, message)) => json!({ "error": { "code": code, "message": message } }),
147        }
148    }
149
150    /// The `syncular_query` fast path: arbitrary read-only SQL over the local
151    /// database. Routed through the same `query` command so there is one
152    /// implementation (the router owns it); this wrapper spares the JS bridge
153    /// from wrapping the method/params envelope for the hot live-query path.
154    pub fn query(&mut self, sql: &str, params: Value) -> Value {
155        let bind = match params {
156            Value::Null => Value::Array(Vec::new()),
157            other => other,
158        };
159        self.command(&json!({ "method": "query", "params": { "sql": sql, "params": bind } }))
160    }
161
162    /// Consume the next coalesced host schedule. Interactive work preempts a
163    /// pending retry; background work keeps the earliest real deadline.
164    pub fn take_sync_intent(&mut self) -> SyncIntent {
165        if std::mem::take(&mut self.interactive_sync) {
166            self.background_sync_ms = None;
167            SyncIntent::Interactive
168        } else if let Some(delay_ms) = self.background_sync_ms.take() {
169            SyncIntent::Background { delay_ms }
170        } else {
171            SyncIntent::None
172        }
173    }
174
175    /// Run one `syncUntilIdle` round for the background host loop, deriving
176    /// events afterwards. A no-op (empty reply) before `create`.
177    pub fn sync_until_idle(&mut self) -> Value {
178        if self.client.is_none() {
179            return json!({ "result": null });
180        }
181        self.command(&json!({ "method": "syncUntilIdle", "params": {} }))
182    }
183
184    /// Owner-mailbox wake from the native realtime reader.
185    pub fn poll_transport(&mut self) {
186        self.drain_realtime();
187        self.drain_core_outputs();
188        self.emit_diagnostics_if_changed();
189    }
190
191    /// Drain every event queued since the last call (the host thread pushes
192    /// them onto the Tauri channel). Mirrors the FFI `poll_event`, batched.
193    pub fn drain_events(&mut self) -> Vec<Event> {
194        self.queue.drain(..).collect()
195    }
196
197    /// Replace the transport's request headers (RFC 0002 §2.3 — rotating
198    /// auth without tearing the plugin down). See
199    /// `HostTransport::set_headers` for the HTTP/WS pickup semantics.
200    pub fn set_headers(&mut self, headers: Vec<(String, String)>) {
201        self.transport.set_headers(headers);
202    }
203
204    /// Release the socket/reader thread. Idempotent.
205    pub fn shutdown(&mut self) {
206        if let Some(mut client) = self.client.take() {
207            client.disconnect_realtime(&mut self.transport);
208            client.begin_security_preflight();
209        }
210        self.interactive_sync = false;
211        self.background_sync_ms = None;
212        // The TS driver clears its diagnostics listeners on dispose; require
213        // a fresh registration after any restart.
214        self.diagnostics_observed = false;
215        self.transport.shutdown();
216    }
217
218    fn push(&mut self, json: Value) {
219        self.queue.push_back(Event { json });
220    }
221
222    /// Feed buffered inbound WS frames to the client (which may ack back through
223    /// the same transport). A no-op without a native socket.
224    fn drain_realtime(&mut self) {
225        if self.client.is_none() {
226            return;
227        }
228        let frames = self.transport.take_inbound();
229        for frame in frames {
230            match frame {
231                transport::Inbound::Text(text) => {
232                    if is_presence_control(&text) {
233                        self.push(json!({ "type": "presence" }));
234                    }
235                    if let Some(client) = self.client.as_mut() {
236                        client.on_realtime_text(&text);
237                    }
238                }
239                transport::Inbound::Binary(bytes) => {
240                    if let Some(client) = self.client.as_mut() {
241                        client.on_realtime_binary(&mut self.transport, &bytes);
242                    }
243                }
244            }
245        }
246    }
247
248    /// Drain exact observer batches and sync intents produced by the Rust core.
249    fn drain_core_outputs(&mut self) {
250        let Some(client) = self.client.as_mut() else {
251            return;
252        };
253        let batches = client.drain_change_batches();
254        let intents = client.drain_sync_intents();
255        for batch in batches {
256            self.push(json!({ "type": "change", "batch": batch }));
257        }
258        for intent in intents {
259            match intent {
260                SyncIntent::Interactive => self.interactive_sync = true,
261                SyncIntent::Background { delay_ms } => {
262                    self.background_sync_ms = Some(
263                        self.background_sync_ms
264                            .map_or(delay_ms, |current| current.min(delay_ms)),
265                    );
266                }
267                SyncIntent::None => {}
268            }
269        }
270    }
271
272    /// Emit one privacy-safe snapshot only when a diagnostics consumer has
273    /// registered (`diagnostics_observed`) AND durable/client status changed.
274    /// The observer gate keeps the per-command snapshot work (subscription
275    /// scan, PRAGMA page counts, SUM aggregates, serialization) off every
276    /// unobserved command and transport poll.
277    /// `capturedAtMs` is excluded from the fingerprint so polling and read-only
278    /// commands do not create event noise. Expected-but-unregistered intent is
279    /// request-local and is obtained through `diagnosticsSnapshot` directly.
280    fn emit_diagnostics_if_changed(&mut self) {
281        if !self.diagnostics_observed {
282            return;
283        }
284        let Some(client) = self.client.as_ref() else {
285            return;
286        };
287        if client.security_preflight() {
288            return;
289        }
290        let Ok(snapshot) = client.diagnostics_snapshot(&ClientDiagnosticsRequest::default()) else {
291            return;
292        };
293        let Ok(mut fingerprint) = serde_json::to_value(&snapshot) else {
294            return;
295        };
296        if let Some(object) = fingerprint.as_object_mut() {
297            object.remove("capturedAtMs");
298        }
299        if self.last_diagnostics_fingerprint.as_ref() == Some(&fingerprint) {
300            return;
301        }
302        self.last_diagnostics_fingerprint = Some(fingerprint);
303        self.push(json!({ "type": "diagnostics", "snapshot": snapshot }));
304    }
305}
306
307/// A presence fanout control frame (§8.6.2) — `{"event":"presence",...}`, the
308/// one inbound realtime event a native host surfaces directly.
309fn is_presence_control(text: &str) -> bool {
310    serde_json::from_str::<Value>(text)
311        .ok()
312        .and_then(|v| {
313            v.get("event")
314                .and_then(Value::as_str)
315                .map(|e| e == "presence")
316        })
317        .unwrap_or(false)
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323
324    fn simple_schema() -> Value {
325        json!({
326            "version": 1,
327            "tables": [{
328                "name": "todo",
329                "primaryKey": "id",
330                "columns": [
331                    { "name": "id", "type": "string", "nullable": false },
332                    { "name": "title", "type": "string", "nullable": false },
333                    { "name": "done", "type": "boolean", "nullable": false }
334                ],
335                "scopes": []
336            }]
337        })
338    }
339
340    fn create(core: &mut SyncularCore) {
341        let reply = core.command(&json!({
342            "method": "create",
343            "params": { "clientId": "c1", "schema": simple_schema() }
344        }));
345        assert_eq!(reply["result"], json!({}), "create ok: {reply}");
346    }
347
348    #[test]
349    fn command_round_trip_create_mutate_query() {
350        let mut core = SyncularCore::new(&json!({})).unwrap();
351        create(&mut core);
352
353        let sub = core.command(&json!({
354            "method": "subscribe",
355            "params": { "id": "s1", "table": "todo", "scopes": {} }
356        }));
357        assert_eq!(sub["result"], json!({}));
358
359        let mutate = core.command(&json!({
360            "method": "mutate",
361            "params": { "mutations": [{
362                "op": "upsert", "table": "todo",
363                "values": { "id": "t1", "title": "hello", "done": false }
364            }] }
365        }));
366        assert!(mutate["result"]["clientCommitId"].is_string(), "{mutate}");
367
368        // The query fast path sees the optimistic overlay immediately.
369        let rows = core.query("SELECT id, title FROM todo ORDER BY id", Value::Null);
370        let list = rows["result"]["rows"].as_array().expect("rows");
371        assert_eq!(list.len(), 1);
372        assert_eq!(list[0]["title"], "hello");
373        assert_eq!(list[0]["id"], "t1");
374    }
375
376    #[test]
377    fn query_binds_params() {
378        let mut core = SyncularCore::new(&json!({})).unwrap();
379        create(&mut core);
380        core.command(&json!({
381            "method": "mutate",
382            "params": { "mutations": [
383                { "op": "upsert", "table": "todo", "values": { "id": "a", "title": "A", "done": false } },
384                { "op": "upsert", "table": "todo", "values": { "id": "b", "title": "B", "done": true } }
385            ] }
386        }));
387        let rows = core.query("SELECT id FROM todo WHERE done = ?", json!([true]));
388        let list = rows["result"]["rows"].as_array().expect("rows");
389        assert_eq!(list.len(), 1);
390        assert_eq!(list[0]["id"], "b");
391    }
392
393    #[test]
394    fn events_derived_after_mutate() {
395        let mut core = SyncularCore::new(&json!({})).unwrap();
396        // Before create, no events.
397        create(&mut core);
398        // Register a diagnostics consumer so mutate-driven snapshots flow.
399        let enabled = core.command(&json!({ "method": "enableDiagnostics", "params": {} }));
400        assert_eq!(enabled["result"], json!({}));
401        let _ = core.drain_events();
402        core.command(&json!({
403            "method": "mutate",
404            "params": { "mutations": [{
405                "op": "upsert", "table": "todo",
406                "values": { "id": "t1", "title": "x", "done": false }
407            }] }
408        }));
409        let events = core.drain_events();
410        // A local mutate writes the optimistic overlay and revision in one
411        // transaction, then emits the exact committed change batch.
412        let kinds: Vec<&str> = events
413            .iter()
414            .filter_map(|e| e.json.get("type").and_then(Value::as_str))
415            .collect();
416        assert!(kinds.contains(&"change"), "kinds: {kinds:?}");
417        assert!(kinds.contains(&"diagnostics"), "kinds: {kinds:?}");
418        let change = events
419            .iter()
420            .find(|event| event.json["type"] == "change")
421            .expect("change event");
422        assert_eq!(change.json["batch"]["revision"], "1");
423        assert_eq!(change.json["batch"]["tables"][0]["table"], "todo");
424        assert_eq!(change.json["batch"]["status"]["outbox"], 1);
425        // `syncNeeded` is an inbound pull/catch-up signal. Local push work is
426        // represented exactly by `outbox` and by the interactive sync intent.
427        assert_eq!(change.json["batch"]["status"]["syncNeeded"], false);
428        assert!(matches!(core.take_sync_intent(), SyncIntent::Interactive));
429        // Draining is exhaustive.
430        assert!(core.drain_events().is_empty());
431    }
432
433    #[test]
434    fn diagnostics_events_wait_for_a_registered_consumer() {
435        let mut core = SyncularCore::new(&json!({})).unwrap();
436        create(&mut core);
437        let _ = core.drain_events();
438        core.command(&json!({
439            "method": "mutate",
440            "params": { "mutations": [{
441                "op": "upsert", "table": "todo",
442                "values": { "id": "t1", "title": "x", "done": false }
443            }] }
444        }));
445        let kinds: Vec<String> = core
446            .drain_events()
447            .iter()
448            .filter_map(|e| e.json.get("type").and_then(Value::as_str))
449            .map(str::to_owned)
450            .collect();
451        assert!(kinds.contains(&"change".to_owned()), "kinds: {kinds:?}");
452        // Without a registered consumer the snapshot is never computed.
453        assert!(
454            !kinds.contains(&"diagnostics".to_owned()),
455            "kinds: {kinds:?}"
456        );
457
458        // Registration delivers a first snapshot on the same drain.
459        let enabled = core.command(&json!({ "method": "enableDiagnostics", "params": {} }));
460        assert_eq!(enabled["result"], json!({}));
461        let events = core.drain_events();
462        assert!(
463            events.iter().any(|e| e.json["type"] == "diagnostics"),
464            "events: {events:?}"
465        );
466
467        // Subsequent status changes keep flowing through the fingerprint gate.
468        core.command(&json!({
469            "method": "mutate",
470            "params": { "mutations": [{
471                "op": "upsert", "table": "todo",
472                "values": { "id": "t2", "title": "y", "done": false }
473            }] }
474        }));
475        let events = core.drain_events();
476        assert!(
477            events.iter().any(|e| e.json["type"] == "diagnostics"),
478            "events: {events:?}"
479        );
480    }
481
482    #[test]
483    fn a_snapshot_pull_registers_the_diagnostics_consumer() {
484        let mut core = SyncularCore::new(&json!({})).unwrap();
485        create(&mut core);
486        let _ = core.drain_events();
487        let reply = core.command(&json!({ "method": "diagnosticsSnapshot", "params": {} }));
488        assert_eq!(reply["result"]["version"], 1);
489        let _ = core.drain_events();
490        core.command(&json!({
491            "method": "mutate",
492            "params": { "mutations": [{
493                "op": "upsert", "table": "todo",
494                "values": { "id": "t1", "title": "x", "done": false }
495            }] }
496        }));
497        let events = core.drain_events();
498        assert!(
499            events.iter().any(|e| e.json["type"] == "diagnostics"),
500            "events: {events:?}"
501        );
502    }
503
504    #[test]
505    fn diagnostics_are_versioned_bounded_and_payload_free() {
506        let mut core = SyncularCore::new(&json!({})).unwrap();
507        create(&mut core);
508        let reply = core.command(&json!({
509            "method": "diagnosticsSnapshot",
510            "params": {
511                "expectedSubscriptions": [{ "id": "membership", "table": "todo" }]
512            }
513        }));
514        assert_eq!(reply["result"]["version"], 1);
515        assert_eq!(reply["result"]["subscriptions"][0]["state"], "unregistered");
516        let encoded = reply.to_string();
517        assert!(!encoded.contains("clientId"));
518        assert!(!encoded.contains("dbPath"));
519        assert!(!encoded.contains("operations"));
520    }
521
522    #[test]
523    fn sync_without_native_transport_fails_loud() {
524        let mut core = SyncularCore::new(&json!({})).unwrap();
525        create(&mut core);
526        let outcome = core.command(&json!({ "method": "sync", "params": {} }));
527        assert_eq!(outcome["result"]["ok"], json!(false), "{outcome}");
528        assert_eq!(outcome["result"]["errorCode"], "transport.unavailable");
529    }
530
531    #[test]
532    fn file_db_persists_across_reopen() {
533        let dir = std::env::temp_dir();
534        let path = dir.join(format!("syncular-tauri-test-{}.db", std::process::id()));
535        let path_str = path.to_string_lossy().to_string();
536        let _ = std::fs::remove_file(&path);
537
538        {
539            let mut core = SyncularCore::new(&json!({})).unwrap();
540            let reply = core.command(&json!({
541                "method": "create",
542                "params": { "clientId": "c1", "schema": simple_schema(), "dbPath": path_str }
543            }));
544            assert_eq!(reply["result"], json!({}), "create with dbPath: {reply}");
545            core.command(&json!({
546                "method": "mutate",
547                "params": { "mutations": [{
548                    "op": "upsert", "table": "todo",
549                    "values": { "id": "persisted", "title": "kept", "done": false }
550                }] }
551            }));
552            let revision = core.command(&json!({
553                "method": "localRevision", "params": {}
554            }));
555            assert_eq!(revision["result"]["revision"], "1");
556        }
557        // Reopen without supplying an id: identity, revision, outbox/status,
558        // and the optimistic visible row all come from the durable database.
559        {
560            let mut core = SyncularCore::new(&json!({})).unwrap();
561            let reopened = core.command(&json!({
562                "method": "create",
563                "params": { "schema": simple_schema(), "dbPath": path_str }
564            }));
565            assert_eq!(reopened["result"], json!({}), "reopen: {reopened}");
566            let rows = core.query("SELECT title FROM todo", Value::Null);
567            let list = rows["result"]["rows"].as_array().expect("rows");
568            assert_eq!(list.len(), 1, "reopened db: {rows}");
569            assert_eq!(list[0]["title"], "kept");
570            let revision = core.command(&json!({
571                "method": "localRevision", "params": {}
572            }));
573            assert_eq!(revision["result"]["revision"], "1");
574            let pending = core.command(&json!({
575                "method": "pendingCommitIds", "params": {}
576            }));
577            assert_eq!(pending["result"]["ids"].as_array().map(Vec::len), Some(1));
578            let status = core.command(&json!({
579                "method": "statusSnapshot", "params": {}
580            }));
581            assert_eq!(status["result"]["outbox"], 1);
582            assert_eq!(status["result"]["syncNeeded"], true);
583            assert!(matches!(core.take_sync_intent(), SyncIntent::Interactive));
584        }
585        {
586            let mut core = SyncularCore::new(&json!({})).unwrap();
587            let mismatch = core.command(&json!({
588                "method": "create",
589                "params": { "clientId": "different", "schema": simple_schema(), "dbPath": path_str }
590            }));
591            assert_eq!(mismatch["error"]["code"], "client.identity_mismatch");
592        }
593        let _ = std::fs::remove_file(&path);
594    }
595
596    #[test]
597    fn config_validation_rejects_baseurl_without_native_feature() {
598        let result = SyncularCore::new(&json!({ "baseUrl": "http://localhost:9/sync" }));
599        #[cfg(not(feature = "native-transport"))]
600        assert!(
601            result.is_err(),
602            "baseUrl must be refused without native-transport"
603        );
604        #[cfg(feature = "native-transport")]
605        assert!(result.is_ok(), "baseUrl builds with native-transport");
606    }
607}