Skip to main content

syncular/
lib.rs

1//! # syncular-ffi — the Syncular v2 Rust client core as a C-ABI native library
2//!
3//! The POC client crate, packaged for shipping. Five C functions expose the
4//! whole client over a JSON command surface — the v1-proven bindings shape,
5//! and the SAME `syncular-command` router the conformance shim locks:
6//!
7//! ```c
8//! void*  syncular_client_new(const char* config_json);
9//! char*  syncular_client_command(void* handle, const char* command_json);
10//! char*  syncular_client_poll_event(void* handle, int64_t timeout_ms);
11//! void   syncular_client_close(void* handle);
12//! void   syncular_free_string(char* ptr);
13//! ```
14//!
15//! `command_json` is `{"method": "...", "params": {...}}` — every method the
16//! shim speaks (create/subscribe/mutate/sync/syncUntilIdle/readRows/…). The
17//! reply is `{"result": ...}` or `{"error": {"code", "message"}}`. Bytes ride
18//! as `{"$bytes": "<hex>"}`, unchanged from the driver protocol, so a
19//! JSI/TurboModule bridge marshals plain JSON.
20//!
21//! ## Transport ownership (native vs. inverted)
22//!
23//! The conformance shim inverts transport to the harness (the host holds the
24//! sync/segment/realtime endpoints). A native app cannot do that — there is
25//! no host loop to call back into. So under the `native-transport` feature
26//! this crate OWNS a real HTTP + WS transport (see [`transport`]); the config
27//! carries a `baseUrl` and the core drives the network itself. Without the
28//! feature (the dependency-lean default), network commands fail loudly with
29//! `transport.unavailable` and only client-local commands run — which is all
30//! the C smoke test and pure-logic tests need.
31//!
32//! ## Events (lean queue over exact core output)
33//!
34//! The client core exposes no callbacks. Each observer transaction instead
35//! commits an exact revisioned change batch, and commands which create network
36//! work emit an explicit sync intent. After every command — and after draining
37//! inbound realtime traffic — the FFI forwards those outputs verbatim as
38//! `change` and `sync-intent` events. `poll_event` drains them. Native hosts do
39//! not infer changes by diffing counters or method names.
40
41use std::collections::VecDeque;
42use std::ffi::{c_char, CStr, CString};
43use std::os::raw::c_longlong;
44use std::sync::{Arc, Condvar, Mutex};
45
46use serde_json::{json, Value};
47use syncular_client::{ClientDiagnosticsRequest, SyncClient};
48use syncular_command::{dispatch, CreateEffects};
49
50pub mod transport;
51
52use transport::HostTransport;
53
54/// One client-observable event (§8 realtime signals + §6 conflicts + §1.6
55/// schema floor + §7.3 lease). JSON-able; delivered by `poll_event`.
56#[derive(Debug, Clone)]
57struct Event {
58    json: Value,
59}
60
61/// The opaque handle behind the `void*`. One `SyncClient` instance, its owned
62/// transport, and the exact core-output queue, guarded for cross-thread polling.
63pub struct Handle {
64    client: Option<SyncClient>,
65    transport: HostTransport,
66    effects: CreateEffects,
67    queue: Arc<EventQueue>,
68    last_diagnostics_fingerprint: Option<Value>,
69}
70
71/// A bounded, blocking event queue: `poll_event` waits up to `timeout_ms` for
72/// the next event. The native WS reader thread and the command path both push.
73pub(crate) struct EventQueue {
74    inner: Mutex<VecDeque<Event>>,
75    ready: Condvar,
76}
77
78impl EventQueue {
79    fn new() -> Self {
80        EventQueue {
81            inner: Mutex::new(VecDeque::new()),
82            ready: Condvar::new(),
83        }
84    }
85
86    fn push(&self, event: Event) {
87        let mut guard = self.inner.lock().expect("event queue lock");
88        guard.push_back(event);
89        self.ready.notify_one();
90    }
91
92    /// Pop the next event, waiting up to `timeout_ms` (< 0 = block until one
93    /// arrives, 0 = non-blocking). Returns `None` on timeout.
94    fn pop(&self, timeout_ms: i64) -> Option<Event> {
95        let mut guard = self.inner.lock().expect("event queue lock");
96        if let Some(event) = guard.pop_front() {
97            return Some(event);
98        }
99        if timeout_ms == 0 {
100            return None;
101        }
102        if timeout_ms < 0 {
103            loop {
104                guard = self.ready.wait(guard).expect("event queue wait");
105                if let Some(event) = guard.pop_front() {
106                    return Some(event);
107                }
108            }
109        }
110        let dur = std::time::Duration::from_millis(timeout_ms as u64);
111        let (mut guard2, _timeout) = self
112            .ready
113            .wait_timeout(guard, dur)
114            .expect("event queue wait_timeout");
115        guard2.pop_front()
116    }
117}
118
119impl Handle {
120    fn new(config: &Value) -> Result<Self, String> {
121        let queue = Arc::new(EventQueue::new());
122        let transport = HostTransport::from_config(config)?;
123        Ok(Handle {
124            client: None,
125            transport,
126            effects: CreateEffects::default(),
127            queue,
128            last_diagnostics_fingerprint: None,
129        })
130    }
131
132    /// Run one JSON command through the shared router, then drain inbound
133    /// realtime traffic and forward exact core outputs.
134    fn command(&mut self, command: &Value) -> Value {
135        let method = command.get("method").and_then(Value::as_str).unwrap_or("");
136        let params = command.get("params").cloned().unwrap_or(Value::Null);
137        let result = dispatch(
138            &mut self.transport,
139            &mut self.client,
140            &mut self.effects,
141            method,
142            &params,
143        );
144        if method == "create" {
145            self.last_diagnostics_fingerprint = None;
146            self.transport.set_signed_urls(self.effects.signed_urls);
147        }
148        // Command-local work is an explicit router effect (mutation and
149        // window changes); realtime/retry work is drained from the core queue
150        // below. Forward both sources without inferring from the method name.
151        if let Ok(value) = &result {
152            if let Some(intent) = value.pointer("/effects/sync") {
153                if intent.get("kind").and_then(Value::as_str) != Some("none") {
154                    self.queue.push(Event {
155                        json: json!({ "type": "sync-intent", "intent": intent }),
156                    });
157                }
158            }
159        }
160        // Deliver any realtime traffic the owned transport buffered, then
161        // forward the core's committed observation output.
162        self.drain_realtime();
163        self.drain_core_outputs();
164        self.emit_diagnostics_if_changed();
165        match result {
166            Ok(value) => json!({ "result": value }),
167            Err((code, message)) => json!({ "error": { "code": code, "message": message } }),
168        }
169    }
170
171    /// Feed buffered inbound WS frames to the client (which may send acks back
172    /// through the same transport). A no-op without a native socket.
173    fn drain_realtime(&mut self) {
174        let Some(client) = self.client.as_mut() else {
175            return;
176        };
177        for frame in self.transport.take_inbound() {
178            match frame {
179                transport::Inbound::Text(text) => {
180                    // A presence fanout is the client-observable event a native
181                    // host wants pushed; detect it on the wire (the core has no
182                    // presence callback) before handing the control frame off.
183                    if is_presence_control(&text) {
184                        self.queue.push(Event {
185                            json: json!({ "type": "presence" }),
186                        });
187                    }
188                    client.on_realtime_text(&text);
189                }
190                transport::Inbound::Binary(bytes) => {
191                    client.on_realtime_binary(&mut self.transport, &bytes)
192                }
193            }
194        }
195    }
196
197    /// Forward exact observer batches and sync intents produced by the Rust
198    /// core. The FFI is a manual-sync host; consumers may schedule an intent
199    /// on their own event loop without polling core state.
200    fn drain_core_outputs(&mut self) {
201        let Some(client) = self.client.as_mut() else {
202            return;
203        };
204        for batch in client.drain_change_batches() {
205            self.queue.push(Event {
206                json: json!({ "type": "change", "batch": batch }),
207            });
208        }
209        for intent in client.drain_sync_intents() {
210            self.queue.push(Event {
211                json: json!({ "type": "sync-intent", "intent": intent }),
212            });
213        }
214    }
215
216    /// Forward a privacy-safe snapshot only when its state (excluding capture
217    /// time) changes. This keeps the event atomic with the command/realtime
218    /// observation while avoiding noise from read-only calls and polling.
219    fn emit_diagnostics_if_changed(&mut self) {
220        let Some(client) = self.client.as_ref() else {
221            return;
222        };
223        if client.security_preflight() {
224            return;
225        }
226        let Ok(snapshot) = client.diagnostics_snapshot(&ClientDiagnosticsRequest::default()) else {
227            return;
228        };
229        let Ok(mut fingerprint) = serde_json::to_value(&snapshot) else {
230            return;
231        };
232        if let Some(object) = fingerprint.as_object_mut() {
233            object.remove("capturedAtMs");
234        }
235        if self.last_diagnostics_fingerprint.as_ref() == Some(&fingerprint) {
236            return;
237        }
238        self.last_diagnostics_fingerprint = Some(fingerprint);
239        self.queue.push(Event {
240            json: json!({ "type": "diagnostics", "snapshot": snapshot }),
241        });
242    }
243}
244
245/// A presence fanout control frame (§8.6.2) — `{"event":"presence",...}`, the
246/// one inbound realtime event a native host surfaces as an event.
247fn is_presence_control(text: &str) -> bool {
248    serde_json::from_str::<Value>(text)
249        .ok()
250        .and_then(|v| {
251            v.get("event")
252                .and_then(Value::as_str)
253                .map(|e| e == "presence")
254        })
255        .unwrap_or(false)
256}
257
258// -- C-ABI surface (the 5 functions kept exactly in sync with rust/ffi.h) ----
259
260/// Turn a Rust string into a heap `char*` the caller frees with
261/// `syncular_free_string`. Never returns null for a valid string.
262fn into_c_string(value: String) -> *mut c_char {
263    match CString::new(value) {
264        Ok(s) => s.into_raw(),
265        // A NUL byte cannot occur in our JSON output, but never panic across
266        // the FFI boundary: fall back to an empty string.
267        Err(_) => CString::new("").expect("empty CString").into_raw(),
268    }
269}
270
271fn c_str_to_value(ptr: *const c_char) -> Result<Value, String> {
272    if ptr.is_null() {
273        return Err("null pointer".to_owned());
274    }
275    // Safety: the caller contract is a valid NUL-terminated C string.
276    let bytes = unsafe { CStr::from_ptr(ptr) };
277    let text = bytes
278        .to_str()
279        .map_err(|_| "config is not UTF-8".to_owned())?;
280    serde_json::from_str(text).map_err(|e| format!("config is not JSON: {e}"))
281}
282
283/// Create a client core. `config_json` is a JSON object: `{}` for the
284/// dependency-lean default (client-local commands only); with the
285/// `native-transport` feature it carries `{"baseUrl": "...", ...}` for the
286/// owned HTTP+WS transport. Returns an opaque handle, or null on a malformed
287/// config.
288///
289/// # Safety
290/// `config_json` must be a valid NUL-terminated UTF-8 C string (or null).
291#[no_mangle]
292pub extern "C" fn syncular_client_new(config_json: *const c_char) -> *mut Handle {
293    let config = match c_str_to_value(config_json) {
294        Ok(value) => value,
295        Err(_) => return std::ptr::null_mut(),
296    };
297    match Handle::new(&config) {
298        Ok(handle) => Box::into_raw(Box::new(handle)),
299        Err(_) => std::ptr::null_mut(),
300    }
301}
302
303/// Run one JSON command (`{"method","params"}`) against the client. Returns a
304/// freshly-allocated `{"result"|"error"}` JSON string the caller frees with
305/// `syncular_free_string`. Returns null only on a null handle.
306///
307/// # Safety
308/// `handle` must be a live handle from `syncular_client_new`; `command_json`
309/// a valid NUL-terminated UTF-8 C string.
310#[allow(clippy::not_unsafe_ptr_arg_deref)]
311#[no_mangle]
312pub extern "C" fn syncular_client_command(
313    handle: *mut Handle,
314    command_json: *const c_char,
315) -> *mut c_char {
316    if handle.is_null() {
317        return std::ptr::null_mut();
318    }
319    // Safety: non-null per the contract; we do not free it here.
320    let handle = unsafe { &mut *handle };
321    let command = match c_str_to_value(command_json) {
322        Ok(value) => value,
323        Err(message) => {
324            return into_c_string(
325                json!({ "error": { "code": "client.failed", "message": message } }).to_string(),
326            )
327        }
328    };
329    let reply = handle.command(&command);
330    into_c_string(reply.to_string())
331}
332
333/// Poll the next client-observable event, waiting up to `timeout_ms`
334/// (negative = block until one arrives, 0 = non-blocking). Returns a
335/// freshly-allocated event JSON string, or null if none arrived in time.
336///
337/// # Safety
338/// `handle` must be a live handle from `syncular_client_new`.
339#[allow(clippy::not_unsafe_ptr_arg_deref)]
340#[no_mangle]
341pub extern "C" fn syncular_client_poll_event(
342    handle: *mut Handle,
343    timeout_ms: c_longlong,
344) -> *mut c_char {
345    if handle.is_null() {
346        return std::ptr::null_mut();
347    }
348    // Safety: non-null per the contract.
349    let handle = unsafe { &*handle };
350    match handle.queue.pop(timeout_ms) {
351        Some(event) => into_c_string(event.json.to_string()),
352        None => std::ptr::null_mut(),
353    }
354}
355
356/// Close a client core, releasing its database, transport, and socket thread.
357/// The handle is invalid after this call.
358///
359/// # Safety
360/// `handle` must be a live handle from `syncular_client_new`, closed once.
361#[allow(clippy::not_unsafe_ptr_arg_deref)]
362#[no_mangle]
363pub extern "C" fn syncular_client_close(handle: *mut Handle) {
364    if handle.is_null() {
365        return;
366    }
367    // Safety: reclaim the Box; dropping shuts down the transport/socket.
368    let mut handle = unsafe { Box::from_raw(handle) };
369    handle.transport.shutdown();
370    drop(handle);
371}
372
373/// Free a string returned by `syncular_client_command` /
374/// `syncular_client_poll_event`.
375///
376/// # Safety
377/// `ptr` must be a string from one of those functions, freed once.
378#[allow(clippy::not_unsafe_ptr_arg_deref)]
379#[no_mangle]
380pub extern "C" fn syncular_free_string(ptr: *mut c_char) {
381    if ptr.is_null() {
382        return;
383    }
384    // Safety: reclaim the CString allocation to drop it.
385    unsafe {
386        let _ = CString::from_raw(ptr);
387    }
388}
389
390#[cfg(test)]
391mod tests;
392
393#[cfg(test)]
394mod round_tests;