diaryx_core 1.0.0

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Centralized sync client for native platforms (CLI, Tauri).
//!
//! `SyncClient` consolidates the duplicated WebSocket sync logic that was
//! previously copy-pasted between the CLI and Tauri frontends. It handles:
//!
//! - WebSocket connection via the `SyncTransport` trait
//! - Reconnection with exponential backoff
//! - Ping/keepalive
//! - Outgoing message channel (local CRDT changes → WebSocket)
//!
//! Protocol logic (handshake, message routing, framing, control messages) is
//! delegated to `SyncSession` in `sync_session.rs`, which is shared with WASM.
//!
//! # Usage
//!
//! ```ignore
//! use diaryx_core::crdt::{SyncClient, SyncClientConfig, SyncEvent, SyncEventHandler};
//!
//! struct MyHandler;
//! impl SyncEventHandler for MyHandler {
//!     fn on_event(&self, event: SyncEvent) {
//!         match event {
//!             SyncEvent::StatusChanged { status } => println!("Status: {:?}", status),
//!             SyncEvent::Progress { completed, total } => println!("{}/{}", completed, total),
//!             _ => {}
//!         }
//!     }
//! }
//!
//! let client = SyncClient::new(config, sync_manager, Arc::new(MyHandler));
//! client.run_persistent(running).await;
//! ```

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use super::sync::{format_body_doc_id, format_workspace_doc_id};
use super::sync_manager::RustSyncManager;
use super::sync_session::{IncomingEvent, SessionAction, SyncSession};
use super::sync_types::{SyncEvent, SyncSessionConfig, SyncStatus};
use super::tokio_transport::TokioTransport;
use super::transport::{SyncTransport, TransportError, WsMessage};
use crate::fs::{AsyncFileSystem, FileSystemEvent};

/// Configuration for the sync client.
#[derive(Debug, Clone)]
pub struct SyncClientConfig {
    /// Base server URL (e.g., "https://sync.diaryx.org").
    pub server_url: String,
    /// Workspace ID to sync.
    pub workspace_id: String,
    /// Authentication token (session token or share token).
    pub auth_token: Option<String>,
    /// Reconnection configuration.
    pub reconnect: ReconnectConfig,
}

/// Reconnection configuration.
#[derive(Debug, Clone)]
pub struct ReconnectConfig {
    /// Whether to automatically reconnect on disconnect.
    pub enabled: bool,
    /// Maximum number of reconnection attempts (0 = infinite).
    pub max_attempts: u32,
    /// Base delay in seconds for exponential backoff.
    pub base_delay_secs: u64,
    /// Maximum delay in seconds for exponential backoff.
    pub max_delay_secs: u64,
}

impl Default for ReconnectConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_attempts: 10,
            base_delay_secs: 2,
            max_delay_secs: 32,
        }
    }
}

/// Trait for receiving sync events.
///
/// Implementors translate `SyncEvent`s into frontend-specific actions
/// (e.g., CLI prints, Tauri event emissions).
pub trait SyncEventHandler: Send + Sync {
    /// Called when a sync event occurs.
    fn on_event(&self, event: SyncEvent);
}

/// Statistics from a one-shot sync operation.
#[derive(Debug, Default)]
pub struct SyncStats {
    /// Number of items pushed to the server.
    pub pushed: usize,
    /// Number of items pulled from the server.
    pub pulled: usize,
}

/// Centralized sync client for native platforms.
///
/// Wraps `SyncSession` and handles the WebSocket transport lifecycle
/// including connection, reconnection, and outgoing message channel.
/// Protocol logic is delegated to the shared `SyncSession`.
pub struct SyncClient<FS: AsyncFileSystem> {
    config: SyncClientConfig,
    sync_manager: Arc<RustSyncManager<FS>>,
    handler: Arc<dyn SyncEventHandler>,
    session: SyncSession<FS>,
}

impl<FS: AsyncFileSystem + 'static> SyncClient<FS> {
    /// Create a new sync client.
    pub fn new(
        config: SyncClientConfig,
        sync_manager: Arc<RustSyncManager<FS>>,
        handler: Arc<dyn SyncEventHandler>,
    ) -> Self {
        let session_config = SyncSessionConfig {
            workspace_id: config.workspace_id.clone(),
            write_to_disk: true,
        };
        let session = SyncSession::new(session_config, Arc::clone(&sync_manager));
        Self {
            config,
            sync_manager,
            handler,
            session,
        }
    }

    /// Build the WebSocket URL from the config.
    fn build_ws_url(&self) -> String {
        let ws_server = self
            .config
            .server_url
            .replace("https://", "wss://")
            .replace("http://", "ws://");
        if let Some(ref token) = self.config.auth_token {
            format!("{}/sync2?token={}", ws_server, token)
        } else {
            format!("{}/sync2", ws_server)
        }
    }

    /// Execute a list of session actions via the transport.
    async fn execute_actions(
        &self,
        actions: Vec<SessionAction>,
        transport: &mut TokioTransport,
    ) -> Result<(), TransportError> {
        for action in actions {
            match action {
                SessionAction::SendBinary(data) => {
                    transport.send_binary(data).await?;
                }
                SessionAction::SendText(text) => {
                    transport.send_text(text).await?;
                }
                SessionAction::Emit(event) => {
                    self.handler.on_event(event);
                }
                SessionAction::DownloadSnapshot { workspace_id } => {
                    // Native clients don't download snapshots via HTTP — send FilesReady
                    // immediately so the handshake continues (server will send CrdtState).
                    log::info!(
                        "[SyncClient] Snapshot download requested for {} — sending FilesReady (native)",
                        workspace_id
                    );
                    transport
                        .send_text(r#"{"type":"FilesReady"}"#.to_string())
                        .await?;
                }
            }
        }
        Ok(())
    }

    /// Run persistent sync with reconnection.
    ///
    /// This is the main entry point for continuous sync (replaces both
    /// CLI's `run_sync_loop_v2` and Tauri's `start_websocket_sync`).
    ///
    /// The loop runs until `running` is set to `false` or max reconnection
    /// attempts are exhausted.
    pub async fn run_persistent(&self, running: Arc<AtomicBool>) {
        let ws_url = self.build_ws_url();
        let mut attempt = 0u32;
        let rc = &self.config.reconnect;

        // Set up outgoing message channel for local CRDT changes.
        let (outgoing_tx, mut outgoing_rx) =
            tokio::sync::mpsc::unbounded_channel::<(String, Vec<u8>)>();

        // Wire up the sync_manager event callback.
        {
            let outgoing_tx = outgoing_tx.clone();
            let ws_id = self.config.workspace_id.clone();
            self.sync_manager.set_event_callback(Arc::new(move |event| {
                if let FileSystemEvent::SendSyncMessage {
                    doc_name,
                    message,
                    is_body,
                    ..
                } = event
                {
                    let doc_id = if *is_body {
                        format_body_doc_id(&ws_id, doc_name)
                    } else {
                        format_workspace_doc_id(&ws_id)
                    };
                    let _ = outgoing_tx.send((doc_id, message.clone()));
                }
            }));
        }

        while running.load(Ordering::SeqCst) {
            if rc.max_attempts > 0 && attempt >= rc.max_attempts {
                log::info!("[SyncClient] Max reconnection attempts reached");
                break;
            }

            // Backoff delay on reconnection
            if attempt > 0 {
                let delay = std::cmp::min(rc.base_delay_secs.pow(attempt), rc.max_delay_secs);
                self.handler.on_event(SyncEvent::StatusChanged {
                    status: SyncStatus::Reconnecting { attempt },
                });
                log::info!(
                    "[SyncClient] Reconnecting in {}s (attempt {}/{})",
                    delay,
                    attempt,
                    if rc.max_attempts == 0 {
                        "".to_string()
                    } else {
                        rc.max_attempts.to_string()
                    }
                );
                tokio::time::sleep(std::time::Duration::from_secs(delay)).await;
                if !running.load(Ordering::SeqCst) {
                    break;
                }
            }

            self.handler.on_event(SyncEvent::StatusChanged {
                status: SyncStatus::Connecting,
            });

            // Connect
            let mut transport = match TokioTransport::connect(&ws_url).await {
                Ok(t) => {
                    log::info!("[SyncClient] Connected to {}", ws_url);
                    attempt = 0; // Reset backoff on success
                    t
                }
                Err(e) => {
                    log::error!("[SyncClient] Connection failed: {}", e);
                    self.handler.on_event(SyncEvent::Error {
                        message: format!("Connection failed: {}", e),
                    });
                    attempt += 1;
                    continue;
                }
            };

            // Run the sync session (handshake + message loop)
            let result = self
                .run_session(&mut transport, &mut outgoing_rx, &running)
                .await;

            // Connection dropped
            let _ = transport.close().await;
            if running.load(Ordering::SeqCst) {
                if let Err(e) = result {
                    log::error!("[SyncClient] Session error: {}", e);
                    self.handler.on_event(SyncEvent::Error {
                        message: e.to_string(),
                    });
                }
                attempt += 1;
                self.session.reset();
                self.sync_manager.reset();
                self.handler.on_event(SyncEvent::StatusChanged {
                    status: SyncStatus::Disconnected,
                });
            }
        }

        // Final cleanup
        self.sync_manager.clear_event_callback();
        self.handler.on_event(SyncEvent::StatusChanged {
            status: SyncStatus::Disconnected,
        });
        log::info!("[SyncClient] Sync loop exited");
    }

    /// Run a one-shot sync (push + pull), then disconnect.
    ///
    /// Replaces CLI's `do_one_shot_sync_v2`. Connects, performs the handshake,
    /// exchanges SyncStep1/SyncStep2 for workspace and all bodies, then disconnects.
    pub async fn run_one_shot(&self) -> Result<SyncStats, TransportError> {
        use super::sync::{DocIdKind, parse_doc_id, unframe_message_v2};
        use std::collections::HashSet;

        let ws_url = self.build_ws_url();
        let mut transport = TokioTransport::connect(&ws_url).await?;

        // Use a one-shot session config (write_to_disk = false for push)
        let one_shot_session = SyncSession::new(
            SyncSessionConfig {
                workspace_id: self.config.workspace_id.clone(),
                write_to_disk: false,
            },
            Arc::clone(&self.sync_manager),
        );

        // Process Connected event
        let actions = one_shot_session.process(IncomingEvent::Connected).await;
        for action in actions {
            match action {
                SessionAction::SendBinary(data) => transport.send_binary(data).await?,
                SessionAction::SendText(text) => transport.send_text(text).await?,
                _ => {}
            }
        }

        // Handshake + collect SyncStep1s
        let hs_deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(10);

        loop {
            tokio::select! {
                msg = transport.recv() => {
                    match msg {
                        Some(Ok(WsMessage::Text(text))) => {
                            let actions = one_shot_session.process(IncomingEvent::TextMessage(text)).await;

                            // Check if session transitioned to Active (Syncing status emitted)
                            let has_syncing = actions.iter().any(|a| matches!(
                                a, SessionAction::Emit(SyncEvent::StatusChanged { status: SyncStatus::Syncing })
                            ));

                            for action in actions {
                                match action {
                                    SessionAction::SendBinary(data) => transport.send_binary(data).await?,
                                    SessionAction::SendText(text) => transport.send_text(text).await?,
                                    SessionAction::DownloadSnapshot { workspace_id } => {
                                        // Native one-shot: send FilesReady to continue handshake
                                        log::info!(
                                            "[SyncClient] One-shot snapshot request for {} — sending FilesReady",
                                            workspace_id
                                        );
                                        transport
                                            .send_text(r#"{"type":"FilesReady"}"#.to_string())
                                            .await?;
                                    }
                                    _ => {}
                                }
                            }

                            if has_syncing {
                                break; // Handshake complete, session is Active
                            }
                            // Otherwise keep looping (e.g., FileManifest received, waiting for CrdtState)
                        }
                        Some(Ok(WsMessage::Binary(data))) => {
                            // Server skipped handshake, process body step1s
                            let actions = one_shot_session.process(IncomingEvent::BinaryMessage(data)).await;
                            for action in actions {
                                match action {
                                    SessionAction::SendBinary(data) => transport.send_binary(data).await?,
                                    SessionAction::SendText(text) => transport.send_text(text).await?,
                                    _ => {}
                                }
                            }
                            break;
                        }
                        Some(Ok(WsMessage::Close)) | None => {
                            let _ = transport.close().await;
                            return Ok(SyncStats::default());
                        }
                        _ => {}
                    }
                }
                _ = tokio::time::sleep_until(hs_deadline) => {
                    break;
                }
            }
        }

        // Now in active state — exchange messages until sync is complete
        let file_paths = self.sync_manager.get_all_file_paths();
        let file_count = file_paths.len();
        let mut stats = SyncStats::default();
        let mut ws_handled = false;
        let mut body_files_handled: HashSet<String> = HashSet::new();

        let timeout_secs = (10 + file_count / 100).min(60) as u64;
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(timeout_secs);

        loop {
            let msg = tokio::select! {
                biased;
                msg = transport.recv() => msg,
                _ = tokio::time::sleep_until(deadline) => break,
            };
            match msg {
                Some(Ok(WsMessage::Binary(data))) => {
                    // Track stats before processing
                    if let Some((doc_id, _payload)) = unframe_message_v2(&data) {
                        match parse_doc_id(&doc_id) {
                            Some(DocIdKind::Workspace(_)) => {
                                ws_handled = true;
                            }
                            Some(DocIdKind::Body { file_path, .. }) => {
                                body_files_handled.insert(file_path);
                            }
                            None => {}
                        }
                    }

                    let actions = one_shot_session
                        .process(IncomingEvent::BinaryMessage(data))
                        .await;
                    for action in actions {
                        match action {
                            SessionAction::SendBinary(data) => {
                                transport.send_binary(data).await?;
                                stats.pushed += 1;
                            }
                            SessionAction::Emit(SyncEvent::FilesChanged { files })
                                if !files.is_empty() =>
                            {
                                stats.pulled += files.len();
                            }
                            SessionAction::Emit(SyncEvent::BodyChanged { .. }) => {
                                stats.pulled += 1;
                            }
                            _ => {}
                        }
                    }
                }
                Some(Ok(WsMessage::Text(text))) => {
                    let actions = one_shot_session
                        .process(IncomingEvent::TextMessage(text))
                        .await;
                    for action in actions {
                        match action {
                            SessionAction::SendBinary(data) => transport.send_binary(data).await?,
                            SessionAction::SendText(text) => transport.send_text(text).await?,
                            _ => {}
                        }
                    }
                }
                Some(Ok(WsMessage::Close)) | None => break,
                Some(Err(e)) => return Err(e),
                _ => continue,
            }

            if ws_handled && body_files_handled.len() >= file_count {
                break;
            }
        }

        let _ = transport.close().await;
        Ok(stats)
    }

    /// Run a single sync session (after connection is established).
    ///
    /// Feeds transport messages into `SyncSession::process()` and executes actions.
    async fn run_session(
        &self,
        transport: &mut TokioTransport,
        outgoing_rx: &mut tokio::sync::mpsc::UnboundedReceiver<(String, Vec<u8>)>,
        running: &Arc<AtomicBool>,
    ) -> Result<(), TransportError> {
        // Process Connected event
        let actions = self.session.process(IncomingEvent::Connected).await;
        self.execute_actions(actions, transport).await?;

        // Handshake loop: feed messages until session transitions to Active
        let handshake_deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(10);

        loop {
            tokio::select! {
                msg = transport.recv() => {
                    match msg {
                        Some(Ok(WsMessage::Text(text))) => {
                            let actions = self.session.process(IncomingEvent::TextMessage(text)).await;

                            // Check if we transitioned to Active (CrdtState triggers body SyncStep1s)
                            let has_syncing = actions.iter().any(|a| matches!(
                                a, SessionAction::Emit(SyncEvent::StatusChanged { status: SyncStatus::Syncing })
                            ));

                            self.execute_actions(actions, transport).await?;

                            if has_syncing {
                                break; // Handshake complete
                            }
                        }
                        Some(Ok(WsMessage::Binary(data))) => {
                            // Server skipped handshake
                            let actions = self.session.process(IncomingEvent::BinaryMessage(data)).await;
                            self.execute_actions(actions, transport).await?;
                            break;
                        }
                        Some(Ok(WsMessage::Close)) | None => {
                            log::warn!("[SyncClient] Connection closed during handshake");
                            return Err(TransportError::Closed);
                        }
                        _ => {}
                    }
                }
                _ = tokio::time::sleep_until(handshake_deadline) => {
                    log::debug!("[SyncClient] No handshake required, proceeding");
                    break;
                }
            }
        }

        // Main message loop
        let mut ping_interval = tokio::time::interval(std::time::Duration::from_secs(30));
        ping_interval.tick().await; // Consume first immediate tick

        loop {
            if !running.load(Ordering::SeqCst) {
                break;
            }

            tokio::select! {
                msg = transport.recv() => {
                    match msg {
                        Some(Ok(WsMessage::Binary(data))) => {
                            let actions = self.session.process(IncomingEvent::BinaryMessage(data)).await;
                            self.execute_actions(actions, transport).await?;
                        }
                        Some(Ok(WsMessage::Text(text))) => {
                            let actions = self.session.process(IncomingEvent::TextMessage(text)).await;
                            self.execute_actions(actions, transport).await?;
                        }
                        Some(Ok(WsMessage::Close)) => {
                            log::info!("[SyncClient] Connection closed by server");
                            break;
                        }
                        Some(Ok(WsMessage::Pong(_))) => {} // keepalive
                        Some(Err(e)) => {
                            log::error!("[SyncClient] WebSocket error: {}", e);
                            self.handler.on_event(SyncEvent::Error { message: e.to_string() });
                            break;
                        }
                        None => break,
                        _ => {}
                    }
                }
                outgoing = outgoing_rx.recv() => {
                    if let Some((doc_id, message)) = outgoing {
                        let actions = self.session.process(IncomingEvent::LocalUpdate { doc_id, data: message }).await;
                        self.execute_actions(actions, transport).await?;
                    }
                }
                _ = ping_interval.tick() => {
                    transport.send_ping().await?;
                }
            }
        }

        Ok(())
    }
}