1use 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#[derive(Debug, Clone)]
39pub struct Event {
40 pub json: Value,
41}
42
43pub struct SyncularCore {
46 client: Option<SyncClient>,
47 transport: HostTransport,
48 effects: CreateEffects,
49 queue: VecDeque<Event>,
50 last_diagnostics_fingerprint: Option<Value>,
51 diagnostics_observed: bool,
56 interactive_sync: bool,
57 background_sync_ms: Option<u64>,
58}
59
60impl SyncularCore {
61 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 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 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 self.diagnostics_observed = true;
106 }
107 let result = dispatch(
108 &mut self.transport,
109 &mut self.client,
110 &mut self.effects,
111 method,
112 ¶ms,
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 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 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 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 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 pub fn poll_transport(&mut self) {
186 self.drain_realtime();
187 self.drain_core_outputs();
188 self.emit_diagnostics_if_changed();
189 }
190
191 pub fn drain_events(&mut self) -> Vec<Event> {
194 self.queue.drain(..).collect()
195 }
196
197 pub fn set_headers(&mut self, headers: Vec<(String, String)>) {
201 self.transport.set_headers(headers);
202 }
203
204 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 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 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 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 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
307fn 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 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 create(&mut core);
398 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 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 assert_eq!(change.json["batch"]["status"]["syncNeeded"], false);
428 assert!(matches!(core.take_sync_intent(), SyncIntent::Interactive));
429 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 assert!(
454 !kinds.contains(&"diagnostics".to_owned()),
455 "kinds: {kinds:?}"
456 );
457
458 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 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 {
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}