tauri-plugin-syncular 0.5.0

A native syncular client inside the Tauri process, exposed to the webview as commands + events (consumes the Rust client core directly — no FFI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! The transport-agnostic, Tauri-free CORE of the plugin.
//!
//! Everything here is plain Rust with no dependency on the `tauri` crate, so
//! it is unit-testable without a window or a mock runtime. The Tauri shell
//! (see `lib.rs`) is a thin layer that owns one [`SyncularCore`] on a
//! dedicated thread, forwards `syncular_command` / `syncular_query` invokes to
//! it, and pumps drained events onto the `syncular://event` Tauri channel.
//!
//! This mirrors the `syncular-ffi` `Handle`: one owned [`SyncClient`], one
//! owned [`HostTransport`] (native HTTP+WS via the `native-transport` feature),
//! and an exact core-output event queue. The plugin is the THIRD consumer of the shared
//! `syncular-command` router (after the conformance shim and the FFI core), so
//! the command surface stays conformance-locked.
//!
//! ## Thread-safety, honestly
//!
//! [`SyncClient`] is synchronous and NOT `Sync` — it owns a rusqlite
//! connection. The plugin follows the shim/FFI pattern: exactly ONE thread
//! owns the core, and all access arrives through a command MAILBOX (an mpsc
//! channel). The Tauri commands (running on Tauri's async runtime) never touch
//! the client directly; they post a [`Request`] to the owning thread and await
//! the reply. The background host loop (§8.4) runs ON that same owning thread,
//! interleaved with mailbox requests, so there is never concurrent access to
//! the connection.

use std::collections::VecDeque;

use serde_json::{json, Value};
use syncular_client::{SyncClient, SyncIntent};
use syncular_command::{dispatch, CreateEffects};

use crate::transport::{self, HostTransport};

/// One client-observable event (§8 realtime signals + §6 conflicts + §1.6
/// schema floor + §7.3 lease). JSON-able; delivered onto the Tauri channel.
/// The same event vocabulary the FFI `poll_event` surfaces.
#[derive(Debug, Clone)]
pub struct Event {
    pub json: Value,
}

/// The Tauri-free core: one client, its owned transport, explicit scheduling
/// state, and the pending exact-event queue. Lives on ONE owning thread.
pub struct SyncularCore {
    client: Option<SyncClient>,
    transport: HostTransport,
    effects: CreateEffects,
    queue: VecDeque<Event>,
    interactive_sync: bool,
    background_sync_ms: Option<u64>,
}

impl SyncularCore {
    /// Build a core from the plugin config JSON (`baseUrl`, `headers`, …). A
    /// `baseUrl` under the `native-transport` feature owns a real HTTP+WS
    /// transport; without it the core is client-local only (tests, offline).
    pub fn new(config: &Value) -> Result<Self, String> {
        Self::new_with_notify(config, None)
    }

    pub fn new_with_notify(
        config: &Value,
        notify: Option<std::sync::Arc<dyn Fn() + Send + Sync>>,
    ) -> Result<Self, String> {
        let transport = HostTransport::from_config_with_notify(config, notify)?;
        Ok(SyncularCore {
            client: None,
            transport,
            effects: CreateEffects::default(),
            queue: VecDeque::new(),
            interactive_sync: false,
            background_sync_ms: None,
        })
    }

    /// Run one JSON command (`{"method","params"}`) through the shared router,
    /// then drain inbound realtime traffic and exact core events. Returns the
    /// driver-protocol `{"result"|"error"}` reply.
    pub fn command(&mut self, command: &Value) -> Value {
        let method = command.get("method").and_then(Value::as_str).unwrap_or("");
        let params = command.get("params").cloned().unwrap_or(Value::Null);
        let result = dispatch(
            &mut self.transport,
            &mut self.client,
            &mut self.effects,
            method,
            &params,
        );
        if method == "create" {
            self.transport.set_signed_urls(self.effects.signed_urls);
        }
        if let Ok(value) = &result {
            if value.pointer("/effects/sync/kind").and_then(Value::as_str) == Some("interactive") {
                self.interactive_sync = true;
            }
        }
        self.drain_realtime();
        self.drain_core_outputs();
        match result {
            Ok(value) => json!({ "result": value }),
            Err((code, message)) => json!({ "error": { "code": code, "message": message } }),
        }
    }

    /// The `syncular_query` fast path: arbitrary read-only SQL over the local
    /// database. Routed through the same `query` command so there is one
    /// implementation (the router owns it); this wrapper spares the JS bridge
    /// from wrapping the method/params envelope for the hot live-query path.
    pub fn query(&mut self, sql: &str, params: Value) -> Value {
        let bind = match params {
            Value::Null => Value::Array(Vec::new()),
            other => other,
        };
        self.command(&json!({ "method": "query", "params": { "sql": sql, "params": bind } }))
    }

    /// Consume the next coalesced host schedule. Interactive work preempts a
    /// pending retry; background work keeps the earliest real deadline.
    pub fn take_sync_intent(&mut self) -> SyncIntent {
        if std::mem::take(&mut self.interactive_sync) {
            self.background_sync_ms = None;
            SyncIntent::Interactive
        } else if let Some(delay_ms) = self.background_sync_ms.take() {
            SyncIntent::Background { delay_ms }
        } else {
            SyncIntent::None
        }
    }

    /// Run one `syncUntilIdle` round for the background host loop, deriving
    /// events afterwards. A no-op (empty reply) before `create`.
    pub fn sync_until_idle(&mut self) -> Value {
        if self.client.is_none() {
            return json!({ "result": null });
        }
        self.command(&json!({ "method": "syncUntilIdle", "params": {} }))
    }

    /// Owner-mailbox wake from the native realtime reader.
    pub fn poll_transport(&mut self) {
        self.drain_realtime();
        self.drain_core_outputs();
    }

    /// Drain every event queued since the last call (the host thread pushes
    /// them onto the Tauri channel). Mirrors the FFI `poll_event`, batched.
    pub fn drain_events(&mut self) -> Vec<Event> {
        self.queue.drain(..).collect()
    }

    /// Replace the transport's request headers (RFC 0002 §2.3 — rotating
    /// auth without tearing the plugin down). See
    /// `HostTransport::set_headers` for the HTTP/WS pickup semantics.
    pub fn set_headers(&mut self, headers: Vec<(String, String)>) {
        self.transport.set_headers(headers);
    }

    /// Release the socket/reader thread. Idempotent.
    pub fn shutdown(&mut self) {
        self.transport.shutdown();
    }

    fn push(&mut self, json: Value) {
        self.queue.push_back(Event { json });
    }

    /// Feed buffered inbound WS frames to the client (which may ack back through
    /// the same transport). A no-op without a native socket.
    fn drain_realtime(&mut self) {
        if self.client.is_none() {
            return;
        }
        let frames = self.transport.take_inbound();
        for frame in frames {
            match frame {
                transport::Inbound::Text(text) => {
                    if is_presence_control(&text) {
                        self.push(json!({ "type": "presence" }));
                    }
                    if let Some(client) = self.client.as_mut() {
                        client.on_realtime_text(&text);
                    }
                }
                transport::Inbound::Binary(bytes) => {
                    if let Some(client) = self.client.as_mut() {
                        client.on_realtime_binary(&mut self.transport, &bytes);
                    }
                }
            }
        }
    }

    /// Drain exact observer batches and sync intents produced by the Rust core.
    fn drain_core_outputs(&mut self) {
        let Some(client) = self.client.as_mut() else {
            return;
        };
        let batches = client.drain_change_batches();
        let intents = client.drain_sync_intents();
        for batch in batches {
            self.push(json!({ "type": "change", "batch": batch }));
        }
        for intent in intents {
            match intent {
                SyncIntent::Interactive => self.interactive_sync = true,
                SyncIntent::Background { delay_ms } => {
                    self.background_sync_ms = Some(
                        self.background_sync_ms
                            .map_or(delay_ms, |current| current.min(delay_ms)),
                    );
                }
                SyncIntent::None => {}
            }
        }
    }
}

/// A presence fanout control frame (§8.6.2) — `{"event":"presence",...}`, the
/// one inbound realtime event a native host surfaces directly.
fn is_presence_control(text: &str) -> bool {
    serde_json::from_str::<Value>(text)
        .ok()
        .and_then(|v| {
            v.get("event")
                .and_then(Value::as_str)
                .map(|e| e == "presence")
        })
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_schema() -> Value {
        json!({
            "version": 1,
            "tables": [{
                "name": "todo",
                "primaryKey": "id",
                "columns": [
                    { "name": "id", "type": "string", "nullable": false },
                    { "name": "title", "type": "string", "nullable": false },
                    { "name": "done", "type": "boolean", "nullable": false }
                ],
                "scopes": []
            }]
        })
    }

    fn create(core: &mut SyncularCore) {
        let reply = core.command(&json!({
            "method": "create",
            "params": { "clientId": "c1", "schema": simple_schema() }
        }));
        assert_eq!(reply["result"], json!({}), "create ok: {reply}");
    }

    #[test]
    fn command_round_trip_create_mutate_query() {
        let mut core = SyncularCore::new(&json!({})).unwrap();
        create(&mut core);

        let sub = core.command(&json!({
            "method": "subscribe",
            "params": { "id": "s1", "table": "todo", "scopes": {} }
        }));
        assert_eq!(sub["result"], json!({}));

        let mutate = core.command(&json!({
            "method": "mutate",
            "params": { "mutations": [{
                "op": "upsert", "table": "todo",
                "values": { "id": "t1", "title": "hello", "done": false }
            }] }
        }));
        assert!(mutate["result"]["clientCommitId"].is_string(), "{mutate}");

        // The query fast path sees the optimistic overlay immediately.
        let rows = core.query("SELECT id, title FROM todo ORDER BY id", Value::Null);
        let list = rows["result"]["rows"].as_array().expect("rows");
        assert_eq!(list.len(), 1);
        assert_eq!(list[0]["title"], "hello");
        assert_eq!(list[0]["id"], "t1");
    }

    #[test]
    fn query_binds_params() {
        let mut core = SyncularCore::new(&json!({})).unwrap();
        create(&mut core);
        core.command(&json!({
            "method": "mutate",
            "params": { "mutations": [
                { "op": "upsert", "table": "todo", "values": { "id": "a", "title": "A", "done": false } },
                { "op": "upsert", "table": "todo", "values": { "id": "b", "title": "B", "done": true } }
            ] }
        }));
        let rows = core.query("SELECT id FROM todo WHERE done = ?", json!([true]));
        let list = rows["result"]["rows"].as_array().expect("rows");
        assert_eq!(list.len(), 1);
        assert_eq!(list[0]["id"], "b");
    }

    #[test]
    fn events_derived_after_mutate() {
        let mut core = SyncularCore::new(&json!({})).unwrap();
        // Before create, no events.
        create(&mut core);
        let _ = core.drain_events();
        core.command(&json!({
            "method": "mutate",
            "params": { "mutations": [{
                "op": "upsert", "table": "todo",
                "values": { "id": "t1", "title": "x", "done": false }
            }] }
        }));
        let events = core.drain_events();
        // A local mutate writes the optimistic overlay and revision in one
        // transaction, then emits the exact committed change batch.
        let kinds: Vec<&str> = events
            .iter()
            .filter_map(|e| e.json.get("type").and_then(Value::as_str))
            .collect();
        assert!(kinds.contains(&"change"), "kinds: {kinds:?}");
        let change = events
            .iter()
            .find(|event| event.json["type"] == "change")
            .expect("change event");
        assert_eq!(change.json["batch"]["revision"], "1");
        assert_eq!(change.json["batch"]["tables"][0]["table"], "todo");
        assert_eq!(change.json["batch"]["status"]["outbox"], 1);
        // `syncNeeded` is an inbound pull/catch-up signal. Local push work is
        // represented exactly by `outbox` and by the interactive sync intent.
        assert_eq!(change.json["batch"]["status"]["syncNeeded"], false);
        // Draining is exhaustive.
        assert!(core.drain_events().is_empty());
    }

    #[test]
    fn sync_without_native_transport_fails_loud() {
        let mut core = SyncularCore::new(&json!({})).unwrap();
        create(&mut core);
        let outcome = core.command(&json!({ "method": "sync", "params": {} }));
        assert_eq!(outcome["result"]["ok"], json!(false), "{outcome}");
        assert_eq!(outcome["result"]["errorCode"], "transport.unavailable");
    }

    #[test]
    fn file_db_persists_across_reopen() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("syncular-tauri-test-{}.db", std::process::id()));
        let path_str = path.to_string_lossy().to_string();
        let _ = std::fs::remove_file(&path);

        {
            let mut core = SyncularCore::new(&json!({})).unwrap();
            let reply = core.command(&json!({
                "method": "create",
                "params": { "clientId": "c1", "schema": simple_schema(), "dbPath": path_str }
            }));
            assert_eq!(reply["result"], json!({}), "create with dbPath: {reply}");
            core.command(&json!({
                "method": "mutate",
                "params": { "mutations": [{
                    "op": "upsert", "table": "todo",
                    "values": { "id": "persisted", "title": "kept", "done": false }
                }] }
            }));
            let revision = core.command(&json!({
                "method": "localRevision", "params": {}
            }));
            assert_eq!(revision["result"]["revision"], "1");
        }
        // Reopen without supplying an id: identity, revision, outbox/status,
        // and the optimistic visible row all come from the durable database.
        {
            let mut core = SyncularCore::new(&json!({})).unwrap();
            let reopened = core.command(&json!({
                "method": "create",
                "params": { "schema": simple_schema(), "dbPath": path_str }
            }));
            assert_eq!(reopened["result"], json!({}), "reopen: {reopened}");
            let rows = core.query("SELECT title FROM todo", Value::Null);
            let list = rows["result"]["rows"].as_array().expect("rows");
            assert_eq!(list.len(), 1, "reopened db: {rows}");
            assert_eq!(list[0]["title"], "kept");
            let revision = core.command(&json!({
                "method": "localRevision", "params": {}
            }));
            assert_eq!(revision["result"]["revision"], "1");
            let pending = core.command(&json!({
                "method": "pendingCommitIds", "params": {}
            }));
            assert_eq!(pending["result"]["ids"].as_array().map(Vec::len), Some(1));
            let status = core.command(&json!({
                "method": "statusSnapshot", "params": {}
            }));
            assert_eq!(status["result"]["outbox"], 1);
            assert_eq!(status["result"]["syncNeeded"], true);
            assert!(matches!(core.take_sync_intent(), SyncIntent::Interactive));
        }
        {
            let mut core = SyncularCore::new(&json!({})).unwrap();
            let mismatch = core.command(&json!({
                "method": "create",
                "params": { "clientId": "different", "schema": simple_schema(), "dbPath": path_str }
            }));
            assert_eq!(mismatch["error"]["code"], "client.identity_mismatch");
        }
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn config_validation_rejects_baseurl_without_native_feature() {
        let result = SyncularCore::new(&json!({ "baseUrl": "http://localhost:9/sync" }));
        #[cfg(not(feature = "native-transport"))]
        assert!(
            result.is_err(),
            "baseUrl must be refused without native-transport"
        );
        #[cfg(feature = "native-transport")]
        assert!(result.is_ok(), "baseUrl builds with native-transport");
    }
}