solidb 1.2.2

A lightweight, high-performance structured database server written in Rust.
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Sync Session Management for Offline-First Clients
//!
//! Tracks the sync state of individual clients (devices) including:
//! - Last sync vector (what version they have)
//! - Subscription filters (which documents they care about)
//! - Device authentication

use crate::sync::version_vector::{ConflictInfo, VersionVector};
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::RwLock;

/// Upper bound on sessions a single principal may hold. Registering past it
/// evicts that principal's least recently active session (audit M2): a
/// client that re-registers on every launch keeps working, and nobody can
/// grow the map on their own.
pub const MAX_SESSIONS_PER_PRINCIPAL: usize = 64;
/// Upper bound on sessions across every principal. Past it, registration is
/// refused once expired sessions have been dropped.
pub const MAX_TOTAL_SESSIONS: usize = 10_000;
/// Upper bound on collections one session may subscribe to.
pub const MAX_SUBSCRIPTIONS: usize = 128;
/// Upper bound on the length of one subscription (collection name).
pub const MAX_SUBSCRIPTION_LEN: usize = 256;
/// Upper bound on a session's `filter_query`. It is evaluated against every
/// pulled entry, so it has no reason to be large.
pub const MAX_FILTER_QUERY_LEN: usize = 4096;
/// Upper bound on a client-supplied device id.
pub const MAX_DEVICE_ID_LEN: usize = 128;
/// How often the background task drops expired sessions.
const CLEANUP_INTERVAL: std::time::Duration = std::time::Duration::from_secs(600);

/// Validate a client-supplied device id: 1..=128 chars of `[A-Za-z0-9._-]`.
///
/// It is embedded in the session id and shown in logs, so it is kept to a
/// charset that cannot confuse either.
pub fn validate_device_id(device_id: &str) -> Result<(), String> {
    if device_id.is_empty() || device_id.len() > MAX_DEVICE_ID_LEN {
        return Err(format!(
            "device_id must be 1 to {} characters",
            MAX_DEVICE_ID_LEN
        ));
    }
    if !device_id
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
    {
        return Err("device_id may contain only letters, digits, '-', '_' and '.'".to_string());
    }
    Ok(())
}

type HmacSha256 = Hmac<Sha256>;

/// Sign data with HMAC-SHA256
fn sign_hmac(data: &str, secret: &[u8]) -> String {
    let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC can take key of any size");
    mac.update(data.as_bytes());
    hex::encode(mac.finalize().into_bytes())
}

/// Verify HMAC signature
fn verify_hmac(data: &str, signature: &str, secret: &[u8]) -> bool {
    let expected = sign_hmac(data, secret);
    // Use constant-time comparison
    if expected.len() != signature.len() {
        return false;
    }
    let mut result = 0u8;
    for (a, b) in expected.bytes().zip(signature.bytes()) {
        result |= a ^ b;
    }
    result == 0
}

/// A sync session represents the state of a client device
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncSession {
    /// Unique session ID (device ID + client-generated nonce)
    pub session_id: String,
    /// Client device ID
    pub device_id: String,
    /// User ID this device belongs to
    pub user_id: Option<String>,
    /// API key used for authentication
    pub api_key: String,
    /// Last known sync vector for this device
    pub last_vector: VersionVector,
    /// Last synced sequence number (for sequence-based pull)
    pub last_sequence: u64,
    /// Optional filter query (SDBQL) for partial sync
    pub filter_query: Option<String>,
    /// Collections this device subscribes to
    pub subscriptions: Vec<String>,
    /// When the session was created
    pub created_at: u64,
    /// Last activity timestamp
    pub last_activity: u64,
    /// Is this session currently online?
    pub is_online: bool,
    /// Client capabilities (for feature negotiation)
    pub capabilities: ClientCapabilities,
}

/// Client capabilities for feature negotiation
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ClientCapabilities {
    /// Supports delta sync (JSON Patch)
    pub delta_sync: bool,
    /// Supports CRDT data types
    pub crdt_types: bool,
    /// Supports binary compression
    pub compression: bool,
    /// Maximum batch size in bytes
    pub max_batch_size: usize,
}

impl SyncSession {
    /// Create a new sync session
    pub fn new(
        session_id: impl Into<String>,
        device_id: impl Into<String>,
        api_key: impl Into<String>,
    ) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;

        Self {
            session_id: session_id.into(),
            device_id: device_id.into(),
            user_id: None,
            api_key: api_key.into(),
            last_vector: VersionVector::new(),
            last_sequence: 0,
            filter_query: None,
            subscriptions: Vec::new(),
            created_at: now,
            last_activity: now,
            is_online: true,
            capabilities: ClientCapabilities::default(),
        }
    }

    /// Create a new secure sync session with HMAC-signed session ID
    ///
    /// The session ID format is: `{device_id}-{nonce}-{signature}`
    /// where signature = HMAC-SHA256(device_id + nonce + api_key, secret)
    pub fn new_secure(
        device_id: impl Into<String>,
        api_key: impl Into<String>,
        secret: &[u8],
    ) -> Self {
        let device_id = device_id.into();
        let api_key = api_key.into();
        let nonce = uuid::Uuid::new_v4().to_string();

        // Create signature over device_id + nonce + api_key
        let data = format!("{}{}{}", device_id, nonce, api_key);
        let signature = sign_hmac(&data, secret);

        // Session ID format: device_id-nonce-signature
        let session_id = format!("{}-{}-{}", device_id, nonce, signature);

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;

        Self {
            session_id,
            device_id,
            user_id: None,
            api_key,
            last_vector: VersionVector::new(),
            last_sequence: 0,
            filter_query: None,
            subscriptions: Vec::new(),
            created_at: now,
            last_activity: now,
            is_online: true,
            capabilities: ClientCapabilities::default(),
        }
    }

    /// Verify a session ID was signed with the correct secret
    ///
    /// Returns true if the session ID is valid and the signature matches.
    /// The api_key must be provided separately for verification.
    pub fn verify_session_id(session_id: &str, api_key: &str, secret: &[u8]) -> bool {
        // Session ID format: device_id-nonce-signature
        // Note: device_id and nonce are UUIDs which contain hyphens
        // So we need to find the signature (last 64 chars - hex encoded SHA256)

        // A SHA256 HMAC signature is 64 hex characters
        if session_id.len() < 65 {
            return false;
        }

        // Find the last hyphen before the signature
        let signature_start = session_id.len() - 64;
        if session_id.as_bytes().get(signature_start.saturating_sub(1)) != Some(&b'-') {
            return false;
        }

        let signature = &session_id[signature_start..];
        let prefix = &session_id[..signature_start.saturating_sub(1)];

        // Find the nonce (36 chars UUID) - it's at the end of prefix
        if prefix.len() < 37 {
            return false;
        }

        let nonce_start = prefix.len() - 36;
        if prefix.as_bytes().get(nonce_start.saturating_sub(1)) != Some(&b'-') {
            return false;
        }

        let nonce = &prefix[nonce_start..];
        let device_id = &prefix[..nonce_start.saturating_sub(1)];

        // Reconstruct the signed data
        let data = format!("{}{}{}", device_id, nonce, api_key);

        verify_hmac(&data, signature, secret)
    }

    /// Extract the device_id from a session ID
    pub fn extract_device_id(session_id: &str) -> Option<String> {
        // Session ID format: device_id-nonce-signature
        // Signature is 64 hex chars, nonce is 36 chars UUID

        if session_id.len() < 65 + 37 {
            return None;
        }

        let signature_start = session_id.len() - 64;
        let prefix = &session_id[..signature_start.saturating_sub(1)];

        if prefix.len() < 37 {
            return None;
        }

        let nonce_start = prefix.len() - 36;
        let device_id = &prefix[..nonce_start.saturating_sub(1)];

        Some(device_id.to_string())
    }

    /// Update the last sync vector
    pub fn update_vector(&mut self, vector: &VersionVector) {
        self.last_vector = vector.clone();
        self.last_activity = current_timestamp();
    }

    /// Update the last synced sequence number
    pub fn update_sequence(&mut self, sequence: u64) {
        self.last_sequence = sequence;
        self.last_activity = current_timestamp();
    }

    /// Add a collection subscription
    pub fn subscribe(&mut self, collection: impl Into<String>) {
        let coll = collection.into();
        if !self.subscriptions.contains(&coll) {
            self.subscriptions.push(coll);
        }
        self.last_activity = current_timestamp();
    }

    /// Remove a collection subscription
    pub fn unsubscribe(&mut self, collection: &str) {
        self.subscriptions.retain(|c| c != collection);
        self.last_activity = current_timestamp();
    }

    /// Mark session as online
    pub fn set_online(&mut self, online: bool) {
        self.is_online = online;
        if online {
            self.last_activity = current_timestamp();
        }
    }

    /// Check if session has expired (no activity for too long)
    pub fn is_expired(&self, max_inactive_ms: u64) -> bool {
        let now = current_timestamp();
        now.saturating_sub(self.last_activity) > max_inactive_ms
    }

    /// Convert to JSON value for storage
    pub fn to_value(&self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or_default()
    }

    /// Create from JSON value
    pub fn from_value(value: &serde_json::Value) -> Option<Self> {
        serde_json::from_value(value.clone()).ok()
    }
}

/// Manages all active sync sessions
pub struct SyncSessionManager {
    /// Active sessions by session ID
    sessions: Arc<RwLock<HashMap<String, SyncSession>>>,
    /// Index by device ID for quick lookup
    device_index: Arc<RwLock<HashMap<String, Vec<String>>>>,
    /// Maximum inactive time before session expires (default: 7 days)
    max_inactive_ms: u64,
    /// Set once the periodic cleanup task has been spawned.
    cleanup_started: AtomicBool,
}

impl SyncSessionManager {
    /// Create a new session manager
    pub fn new() -> Self {
        Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            device_index: Arc::new(RwLock::new(HashMap::new())),
            max_inactive_ms: 7 * 24 * 60 * 60 * 1000, // 7 days
            cleanup_started: AtomicBool::new(false),
        }
    }

    /// Create a session with custom expiration time
    pub fn with_expiration(max_inactive_ms: u64) -> Self {
        Self {
            sessions: Arc::new(RwLock::new(HashMap::new())),
            device_index: Arc::new(RwLock::new(HashMap::new())),
            max_inactive_ms,
            cleanup_started: AtomicBool::new(false),
        }
    }

    /// Spawn the task that periodically drops expired sessions (audit M2:
    /// `cleanup_expired` used to have no caller, so sessions lived forever).
    ///
    /// Idempotent per manager. Holds only a `Weak`, so the task ends when the
    /// manager is dropped. A no-op outside a Tokio runtime.
    pub fn spawn_cleanup_task(self: &Arc<Self>) {
        let Ok(handle) = tokio::runtime::Handle::try_current() else {
            return;
        };
        if self
            .cleanup_started
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_err()
        {
            return;
        }
        let weak = Arc::downgrade(self);
        handle.spawn(async move {
            let mut tick = tokio::time::interval(CLEANUP_INTERVAL);
            tick.tick().await; // the first tick fires immediately
            loop {
                tick.tick().await;
                let Some(manager) = weak.upgrade() else {
                    break;
                };
                let removed = manager.cleanup_expired().await;
                if removed > 0 {
                    tracing::debug!("sync sessions: dropped {} expired", removed);
                }
            }
        });
    }

    /// Register a session under the per-principal and total caps.
    ///
    /// The principal is `session.user_id`. When it already holds
    /// `max_per_owner` sessions, its least recently active ones are evicted.
    /// When the map holds `max_total`, expired sessions are dropped first and
    /// the registration is refused if that frees nothing.
    pub async fn register_session_bounded(
        &self,
        session: SyncSession,
        max_per_owner: usize,
        max_total: usize,
    ) -> Result<(), String> {
        let session_id = session.session_id.clone();
        let device_id = session.device_id.clone();
        let mut evicted: Vec<SyncSession> = Vec::new();

        let mut sessions = self.sessions.write().await;

        if let Some(owner) = session.user_id.as_deref() {
            let mut owned: Vec<(u64, String)> = sessions
                .values()
                .filter(|s| s.user_id.as_deref() == Some(owner))
                .map(|s| (s.last_activity, s.session_id.clone()))
                .collect();
            if owned.len() >= max_per_owner {
                owned.sort();
                let excess = owned.len() + 1 - max_per_owner.max(1);
                for (_, id) in owned.into_iter().take(excess) {
                    if let Some(s) = sessions.remove(&id) {
                        evicted.push(s);
                    }
                }
            }
        }

        if sessions.len() >= max_total {
            let expired: Vec<String> = sessions
                .values()
                .filter(|s| s.is_expired(self.max_inactive_ms))
                .map(|s| s.session_id.clone())
                .collect();
            for id in expired {
                if let Some(s) = sessions.remove(&id) {
                    evicted.push(s);
                }
            }
        }

        let result = if sessions.len() >= max_total {
            Err(format!(
                "too many sync sessions on this server (limit {})",
                max_total
            ))
        } else {
            sessions.insert(session_id.clone(), session);
            Ok(())
        };
        drop(sessions);

        let mut index = self.device_index.write().await;
        for s in &evicted {
            if let Some(ids) = index.get_mut(&s.device_id) {
                ids.retain(|id| id != &s.session_id);
                if ids.is_empty() {
                    index.remove(&s.device_id);
                }
            }
        }
        if result.is_ok() {
            index.entry(device_id).or_default().push(session_id);
        }

        result
    }

    /// Register a new session
    pub async fn register_session(&self, session: SyncSession) {
        let session_id = session.session_id.clone();
        let device_id = session.device_id.clone();

        // Add to sessions map
        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id.clone(), session);
        drop(sessions);

        // Update device index
        let mut index = self.device_index.write().await;
        index
            .entry(device_id)
            .or_insert_with(Vec::new)
            .push(session_id);
    }

    /// Get a session by ID
    pub async fn get_session(&self, session_id: &str) -> Option<SyncSession> {
        let sessions = self.sessions.read().await;
        sessions.get(session_id).cloned()
    }

    /// Get all sessions for a device
    pub async fn get_device_sessions(&self, device_id: &str) -> Vec<SyncSession> {
        let index = self.device_index.read().await;
        let session_ids = index.get(device_id).cloned().unwrap_or_default();
        drop(index);

        let sessions = self.sessions.read().await;
        session_ids
            .iter()
            .filter_map(|id| sessions.get(id).cloned())
            .collect()
    }

    /// Update a session
    pub async fn update_session(&self, session: &SyncSession) {
        let mut sessions = self.sessions.write().await;
        if sessions.contains_key(&session.session_id) {
            sessions.insert(session.session_id.clone(), session.clone());
        }
    }

    /// Update just the sync vector for a session
    pub async fn update_session_vector(&self, session_id: &str, vector: &VersionVector) {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.update_vector(vector);
        }
    }

    /// Update the last synced sequence for a session
    pub async fn update_session_sequence(&self, session_id: &str, sequence: u64) {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.update_sequence(sequence);
        }
    }

    /// Remove a session
    pub async fn remove_session(&self, session_id: &str) {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.remove(session_id) {
            drop(sessions);

            // Remove from device index
            let mut index = self.device_index.write().await;
            if let Some(ids) = index.get_mut(&session.device_id) {
                ids.retain(|id| id != session_id);
                if ids.is_empty() {
                    index.remove(&session.device_id);
                }
            }
        }
    }

    /// Remove all sessions for a device
    pub async fn remove_device_sessions(&self, device_id: &str) {
        let index = self.device_index.read().await;
        let session_ids = index.get(device_id).cloned().unwrap_or_default();
        drop(index);

        for session_id in session_ids {
            self.remove_session(&session_id).await;
        }
    }

    /// Mark a session as online/offline
    pub async fn set_session_online(&self, session_id: &str, online: bool) {
        let mut sessions = self.sessions.write().await;
        if let Some(session) = sessions.get_mut(session_id) {
            session.set_online(online);
        }
    }

    /// Get all active (online) sessions
    pub async fn get_active_sessions(&self) -> Vec<SyncSession> {
        let sessions = self.sessions.read().await;
        sessions.values().filter(|s| s.is_online).cloned().collect()
    }

    /// Get all sessions subscribing to a collection
    pub async fn get_subscribers(&self, collection: &str) -> Vec<SyncSession> {
        let sessions = self.sessions.read().await;
        sessions
            .values()
            .filter(|s| s.subscriptions.contains(&collection.to_string()))
            .cloned()
            .collect()
    }

    /// Clean up expired sessions
    pub async fn cleanup_expired(&self) -> usize {
        let expired: Vec<String> = {
            let sessions = self.sessions.read().await;
            sessions
                .values()
                .filter(|s| s.is_expired(self.max_inactive_ms))
                .map(|s| s.session_id.clone())
                .collect()
        };

        for session_id in &expired {
            self.remove_session(session_id).await;
        }

        expired.len()
    }

    /// Get count of active sessions
    pub async fn session_count(&self) -> usize {
        let sessions = self.sessions.read().await;
        sessions.len()
    }

    /// Get count of online sessions
    pub async fn online_count(&self) -> usize {
        let sessions = self.sessions.read().await;
        sessions.values().filter(|s| s.is_online).count()
    }
}

impl Default for SyncSessionManager {
    fn default() -> Self {
        Self::new()
    }
}

fn current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Request to register a new sync session
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterSessionRequest {
    pub device_id: String,
    pub api_key: String,
    pub capabilities: Option<ClientCapabilities>,
    pub subscriptions: Option<Vec<String>>,
}

/// Response to session registration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterSessionResponse {
    pub session_id: String,
    pub server_capabilities: ClientCapabilities,
}

/// Request to pull changes from server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncPullRequest {
    pub session_id: String,
    /// Version vector of client (what they already have)
    pub client_vector: VersionVector,
    /// Optional filter query (SDBQL)
    pub filter: Option<String>,
    /// Maximum number of changes to return
    pub limit: Option<usize>,
}

/// Response with changes from server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncPullResponse {
    /// Changes to apply
    pub changes: Vec<SyncChange>,
    /// Server's version vector after these changes
    pub server_vector: VersionVector,
    /// Whether there are more changes to fetch
    pub has_more: bool,
}

/// Request to push changes to server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncPushRequest {
    pub session_id: String,
    /// Changes from client
    pub changes: Vec<SyncChange>,
    /// Client's version vector before these changes
    pub client_vector: VersionVector,
}

/// Response to push request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncPushResponse {
    /// Server's new version vector after applying changes
    pub server_vector: VersionVector,
    /// Conflicts that occurred (if any)
    pub conflicts: Vec<ConflictInfo>,
    /// Number of changes accepted
    pub accepted: usize,
    /// Number of changes rejected
    pub rejected: usize,
}

/// A single change entry in sync
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncChange {
    /// Database name
    pub database: String,
    /// Collection name
    pub collection: String,
    /// Document key
    pub document_key: String,
    /// Operation type
    pub operation: ChangeOperation,
    /// Document data (for insert/update)
    pub document_data: Option<serde_json::Value>,
    /// Parent version vectors (causal history)
    pub parent_vectors: Vec<VersionVector>,
    /// Vector clock after this change
    pub vector: VersionVector,
    /// HLC timestamp
    pub timestamp: u64,
    /// Is this a delta (patch) or full document?
    pub is_delta: bool,
    /// Delta patch (if is_delta is true)
    pub delta_patch: Option<serde_json::Value>,
}

/// Type of change operation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChangeOperation {
    Insert,
    Update,
    Delete,
}

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

    #[tokio::test]
    async fn test_session_lifecycle() {
        let manager = SyncSessionManager::new();

        // Register session
        let session = SyncSession::new("sess-1", "device-1", "api-key-1");
        manager.register_session(session.clone()).await;

        assert_eq!(manager.session_count().await, 1);

        // Get session
        let retrieved = manager.get_session("sess-1").await;
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().device_id, "device-1");

        // Update vector
        let mut vector = VersionVector::new();
        vector.increment("device-1");
        manager.update_session_vector("sess-1", &vector).await;

        let updated = manager.get_session("sess-1").await.unwrap();
        assert_eq!(updated.last_vector.get("device-1"), 1);

        // Remove session
        manager.remove_session("sess-1").await;
        assert_eq!(manager.session_count().await, 0);
    }

    #[tokio::test]
    async fn test_subscriptions() {
        let manager = SyncSessionManager::new();

        let mut session = SyncSession::new("sess-1", "device-1", "api-key-1");
        session.subscribe("orders");
        session.subscribe("products");
        manager.register_session(session).await;

        let subscribers = manager.get_subscribers("orders").await;
        assert_eq!(subscribers.len(), 1);

        let subscribers = manager.get_subscribers("users").await;
        assert_eq!(subscribers.len(), 0);
    }

    #[tokio::test]
    async fn test_bounded_registration_evicts_oldest_of_owner() {
        let manager = SyncSessionManager::new();
        for i in 0..3 {
            let mut s = SyncSession::new(format!("sess-{}", i), "dev", "k");
            s.user_id = Some("alice".to_string());
            s.last_activity = i as u64 + 1;
            manager.register_session_bounded(s, 3, 100).await.unwrap();
        }
        let mut s = SyncSession::new("sess-new", "dev", "k");
        s.user_id = Some("alice".to_string());
        manager.register_session_bounded(s, 3, 100).await.unwrap();

        assert_eq!(manager.session_count().await, 3);
        assert!(manager.get_session("sess-0").await.is_none());
        assert!(manager.get_session("sess-new").await.is_some());
        assert_eq!(manager.get_device_sessions("dev").await.len(), 3);
    }

    #[tokio::test]
    async fn test_bounded_registration_total_cap() {
        let manager = SyncSessionManager::new();
        for i in 0..2 {
            let mut s = SyncSession::new(format!("sess-{}", i), "dev", "k");
            s.user_id = Some(format!("user-{}", i));
            manager.register_session_bounded(s, 10, 2).await.unwrap();
        }
        let mut s = SyncSession::new("sess-x", "dev", "k");
        s.user_id = Some("mallory".to_string());
        assert!(manager.register_session_bounded(s, 10, 2).await.is_err());
        assert_eq!(manager.session_count().await, 2);

        // An expired session makes room.
        let manager = SyncSessionManager::with_expiration(1000);
        let mut old = SyncSession::new("old", "dev", "k");
        old.last_activity = 0;
        manager.register_session(old).await;
        let s = SyncSession::new("fresh", "dev", "k");
        manager.register_session_bounded(s, 10, 1).await.unwrap();
        assert!(manager.get_session("old").await.is_none());
    }

    #[test]
    fn test_validate_device_id() {
        assert!(validate_device_id("iphone-12_a.b").is_ok());
        assert!(validate_device_id("").is_err());
        assert!(validate_device_id(&"a".repeat(MAX_DEVICE_ID_LEN + 1)).is_err());
        assert!(validate_device_id("node b").is_err());
        assert!(validate_device_id("10.0.0.1:6745").is_err());
    }

    #[test]
    fn test_session_expiration() {
        let mut session = SyncSession::new("sess-1", "device-1", "api-key-1");
        session.last_activity = 0; // Very old

        assert!(session.is_expired(1000));
        assert!(!session.is_expired(u64::MAX));
    }

    #[test]
    fn test_secure_session_creation() {
        let secret = b"test-cluster-secret-key-12345678";
        let session = SyncSession::new_secure("device-123", "api-key-abc", secret);

        // Session should have the device_id
        assert_eq!(session.device_id, "device-123");
        assert_eq!(session.api_key, "api-key-abc");

        // Session ID should be properly formatted
        assert!(session.session_id.starts_with("device-123-"));
        // Should end with 64 hex chars (SHA256 signature)
        assert!(session.session_id.len() > 64);
    }

    #[test]
    fn test_verify_session_id_valid() {
        let secret = b"test-cluster-secret-key-12345678";
        let session = SyncSession::new_secure("device-123", "api-key-abc", secret);

        // Should verify correctly with same api_key and secret
        assert!(SyncSession::verify_session_id(
            &session.session_id,
            "api-key-abc",
            secret
        ));
    }

    #[test]
    fn test_verify_session_id_wrong_api_key() {
        let secret = b"test-cluster-secret-key-12345678";
        let session = SyncSession::new_secure("device-123", "api-key-abc", secret);

        // Should fail with wrong api_key
        assert!(!SyncSession::verify_session_id(
            &session.session_id,
            "wrong-api-key",
            secret
        ));
    }

    #[test]
    fn test_verify_session_id_wrong_secret() {
        let secret = b"test-cluster-secret-key-12345678";
        let wrong_secret = b"wrong-cluster-secret-key-1234567";
        let session = SyncSession::new_secure("device-123", "api-key-abc", secret);

        // Should fail with wrong secret
        assert!(!SyncSession::verify_session_id(
            &session.session_id,
            "api-key-abc",
            wrong_secret
        ));
    }

    #[test]
    fn test_verify_session_id_tampered() {
        let secret = b"test-cluster-secret-key-12345678";
        let session = SyncSession::new_secure("device-123", "api-key-abc", secret);

        // Tamper with the session ID
        let mut tampered = session.session_id.clone();
        if let Some(last_char) = tampered.pop() {
            // Change the last character
            let new_char = if last_char == 'a' { 'b' } else { 'a' };
            tampered.push(new_char);
        }

        // Should fail verification
        assert!(!SyncSession::verify_session_id(
            &tampered,
            "api-key-abc",
            secret
        ));
    }

    #[test]
    fn test_extract_device_id() {
        let secret = b"test-cluster-secret-key-12345678";
        let session = SyncSession::new_secure("my-device-id", "api-key-abc", secret);

        let extracted = SyncSession::extract_device_id(&session.session_id);
        assert_eq!(extracted, Some("my-device-id".to_string()));
    }

    #[test]
    fn test_extract_device_id_invalid() {
        // Too short session ID
        assert!(SyncSession::extract_device_id("short").is_none());

        // Session ID without proper format
        assert!(SyncSession::extract_device_id("invalid-session-id").is_none());
    }
}