commy 0.4.1

A hierarchical, multi-tenant shared memory coordination system for Windows enabling secure, efficient data sharing between multiple processes via WebSocket and direct memory-mapping
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
//! Vector Clock Implementation for Multi-Server Consistency
//!
//! Vector clocks enable causality tracking across distributed servers.
//! They detect concurrent events and enable deterministic conflict resolution.
//!
//! # Overview
//!
//! A vector clock is a logical clock that assigns a vector of integers to each event.
//! Each server maintains one component of the vector, incremented when it performs an operation.
//!
//! ## Properties
//!
//! - **Causality Detection**: If VC(A) < VC(B), then A happened before B
//! - **Concurrency Detection**: If VC(A) || VC(B), then A and B are concurrent
//! - **Server Identification**: Each server has a unique ID in the vector
//!
//! ## Usage
//!
//! ```ignore
//! let mut vc = VectorClock::new(&["server1", "server2", "server3"]);
//! vc.increment("server1");  // Happens on server1
//! let vc_copy = vc.clone();
//! vc.increment("server2");  // Happens on server2
//! assert!(vc.happens_before(&vc_copy).is_none());  // Concurrent
//! ```

use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;

/// A vector clock for tracking causality in distributed systems.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct VectorClock {
    /// Timestamp for each server (server_id -> logical_time)
    clocks: HashMap<String, u64>,
    /// All known server IDs in deterministic order
    server_ids: Vec<String>,
}

impl VectorClock {
    /// Create a new vector clock with the given server IDs.
    ///
    /// # Arguments
    ///
    /// * `server_ids` - List of all server IDs in the cluster (must be sorted)
    pub fn new(server_ids: &[&str]) -> Self {
        let mut clocks = HashMap::new();
        let server_ids: Vec<String> = server_ids.iter().map(|s| s.to_string()).collect();

        for server_id in &server_ids {
            clocks.insert(server_id.clone(), 0);
        }

        VectorClock { clocks, server_ids }
    }

    /// Increment the clock for a specific server.
    ///
    /// # Arguments
    ///
    /// * `server_id` - The server that performed the operation
    ///
    /// # Panics
    ///
    /// Panics if the server_id is not in the vector clock's known servers.
    pub fn increment(&mut self, server_id: &str) {
        if let Some(clock) = self.clocks.get_mut(server_id) {
            *clock += 1;
        } else {
            panic!("Unknown server_id: {}", server_id);
        }
    }

    /// Merge with another vector clock (take maximum of each component).
    ///
    /// This is used when receiving an event from another server.
    pub fn merge(&mut self, other: &VectorClock) {
        for server_id in &self.server_ids {
            let other_time = other.clocks.get(server_id).copied().unwrap_or(0);
            let self_time = self.clocks.get(server_id).copied().unwrap_or(0);
            self.clocks
                .insert(server_id.clone(), self_time.max(other_time));
        }
    }

    /// Get the timestamp for a specific server.
    pub fn get(&self, server_id: &str) -> u64 {
        self.clocks.get(server_id).copied().unwrap_or(0)
    }

    /// Check if this vector clock happens before another.
    ///
    /// Returns:
    /// - `Some(Ordering::Less)` if self < other (self happened before)
    /// - `Some(Ordering::Greater)` if self > other (self happened after)
    /// - `Some(Ordering::Equal)` if self == other (same event)
    /// - `None` if clocks are concurrent (neither happened before the other)
    pub fn compare(&self, other: &VectorClock) -> Option<Ordering> {
        let mut has_less = false;
        let mut has_greater = false;

        for server_id in &self.server_ids {
            let self_time = self.clocks.get(server_id).copied().unwrap_or(0);
            let other_time = other.clocks.get(server_id).copied().unwrap_or(0);

            match self_time.cmp(&other_time) {
                Ordering::Less => has_less = true,
                Ordering::Greater => has_greater = true,
                Ordering::Equal => {}
            }
        }

        match (has_less, has_greater) {
            (false, false) => Some(Ordering::Equal),
            (true, false) => Some(Ordering::Less),
            (false, true) => Some(Ordering::Greater),
            (true, true) => None, // Concurrent
        }
    }

    /// Check if this vector clock happened before another.
    pub fn happens_before(&self, other: &VectorClock) -> Option<bool> {
        self.compare(other).map(|ord| ord == Ordering::Less)
    }

    /// Check if this vector clock happened after another.
    pub fn happens_after(&self, other: &VectorClock) -> Option<bool> {
        self.compare(other).map(|ord| ord == Ordering::Greater)
    }

    /// Check if clocks are concurrent (neither happened before the other).
    pub fn is_concurrent(&self, other: &VectorClock) -> bool {
        self.compare(other).is_none()
    }

    /// Get all server IDs known to this clock.
    pub fn server_ids(&self) -> &[String] {
        &self.server_ids
    }

    /// Get the vector as a sorted list of (server_id, time) tuples.
    ///
    /// Useful for display and debugging.
    pub fn as_vec(&self) -> Vec<(String, u64)> {
        let mut result: Vec<_> = self.clocks.iter().map(|(k, v)| (k.clone(), *v)).collect();
        result.sort_by(|a, b| a.0.cmp(&b.0));
        result
    }
}

/// Represents a versioned value with its vector clock.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VersionedValue<T: Clone> {
    /// The actual value
    pub value: T,
    /// Vector clock at the time this value was created/updated
    pub version: VectorClock,
    /// Which server last modified this value
    pub last_modified_by: String,
}

impl<T: Clone> VersionedValue<T> {
    /// Create a new versioned value.
    pub fn new(value: T, version: VectorClock, last_modified_by: String) -> Self {
        VersionedValue {
            value,
            version,
            last_modified_by,
        }
    }

    /// Check if this version happened before another.
    pub fn happens_before(&self, other: &VersionedValue<T>) -> Option<bool> {
        self.version.happens_before(&other.version)
    }

    /// Check if this version is concurrent with another.
    pub fn is_concurrent(&self, other: &VersionedValue<T>) -> bool {
        self.version.is_concurrent(&other.version)
    }
}

/// Conflict resolution strategy for concurrent writes.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum ConflictResolution<T: Clone> {
    /// Keep the value that has higher sum of vector clock components
    /// Serves as a tie-breaker for concurrent updates
    HighestLogicalTime,

    /// Keep the value from the server with lexicographically highest ID
    /// Only used when logical time is equal
    ServerPriority,

    /// User-defined resolution: return both conflicting values
    /// Application must decide which to keep
    ApplicationDefined(Vec<T>),
}

/// Result of applying a remote write locally.
#[derive(Clone, Debug)]
pub enum WriteResult<T: Clone> {
    /// Remote write happened after local, apply it
    Applied,

    /// Local write happened after remote, keep local
    Ignored,

    /// Both writes are concurrent
    Conflict(Vec<T>),
}

/// Merge function type for resolving conflicts.
pub type MergeFn<T> = fn(&VersionedValue<T>, &VersionedValue<T>) -> VersionedValue<T>;

/// Applies a remote value update to a local value, respecting causality.
///
/// # Arguments
///
/// * `local` - Current local value
/// * `remote` - Remote value received
/// * `resolve_conflict` - Function to resolve concurrent writes
///
/// # Returns
///
/// Returns the new local value and whether it was changed.
pub fn apply_remote_write<T: Clone>(
    local: &VersionedValue<T>,
    remote: &VersionedValue<T>,
    resolve_conflict: MergeFn<T>,
) -> (VersionedValue<T>, bool) {
    match local.version.compare(&remote.version) {
        Some(Ordering::Less) => {
            // Remote happened after local, apply it
            (remote.clone(), true)
        }
        Some(Ordering::Greater) | Some(Ordering::Equal) => {
            // Local happened after or is same, keep local
            (local.clone(), false)
        }
        None => {
            // Concurrent, resolve conflict
            let resolved = resolve_conflict(local, remote);
            (resolved, true)
        }
    }
}

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

    #[test]
    fn test_vector_clock_creation() {
        let vc = VectorClock::new(&["server1", "server2", "server3"]);
        assert_eq!(vc.get("server1"), 0);
        assert_eq!(vc.get("server2"), 0);
        assert_eq!(vc.get("server3"), 0);
    }

    #[test]
    fn test_vector_clock_increment() {
        let mut vc = VectorClock::new(&["server1", "server2"]);
        vc.increment("server1");
        assert_eq!(vc.get("server1"), 1);
        assert_eq!(vc.get("server2"), 0);

        vc.increment("server1");
        assert_eq!(vc.get("server1"), 2);
    }

    #[test]
    fn test_vector_clock_happens_before() {
        let mut vc1 = VectorClock::new(&["server1", "server2"]);
        let mut vc2 = VectorClock::new(&["server1", "server2"]);

        vc1.increment("server1");
        vc1.merge(&vc2);
        vc2.increment("server1");
        vc2.increment("server2");

        assert_eq!(vc1.happens_before(&vc2), Some(true));
        assert_eq!(vc2.happens_before(&vc1), Some(false));
    }

    #[test]
    fn test_vector_clock_concurrent() {
        let mut vc1 = VectorClock::new(&["server1", "server2"]);
        let mut vc2 = VectorClock::new(&["server1", "server2"]);

        vc1.increment("server1");
        vc2.increment("server2");

        assert!(vc1.is_concurrent(&vc2));
        assert!(vc2.is_concurrent(&vc1));
        assert_eq!(vc1.compare(&vc2), None);
    }

    #[test]
    fn test_vector_clock_merge() {
        let mut vc1 = VectorClock::new(&["server1", "server2"]);
        let mut vc2 = VectorClock::new(&["server1", "server2"]);

        vc1.increment("server1");
        vc1.increment("server1");
        vc2.increment("server2");

        vc1.merge(&vc2);

        assert_eq!(vc1.get("server1"), 2);
        assert_eq!(vc1.get("server2"), 1);
    }

    #[test]
    fn test_vector_clock_equality() {
        let mut vc1 = VectorClock::new(&["server1", "server2"]);
        let mut vc2 = VectorClock::new(&["server1", "server2"]);

        vc1.increment("server1");
        vc2.increment("server1");

        assert_eq!(vc1, vc2);
        assert_eq!(vc1.compare(&vc2), Some(Ordering::Equal));
    }

    #[test]
    fn test_versioned_value() {
        let vc = VectorClock::new(&["server1", "server2"]);
        let v = VersionedValue::new(42, vc, "server1".to_string());

        assert_eq!(v.value, 42);
        assert_eq!(v.last_modified_by, "server1");
    }

    #[test]
    fn test_apply_remote_write_happens_before() {
        let mut local_vc = VectorClock::new(&["server1", "server2"]);
        let mut remote_vc = VectorClock::new(&["server1", "server2"]);

        local_vc.increment("server1");
        local_vc.merge(&remote_vc);
        remote_vc.increment("server1");
        remote_vc.increment("server2");

        let local = VersionedValue::new(10, local_vc, "server1".to_string());
        let remote = VersionedValue::new(20, remote_vc, "server2".to_string());

        let resolve = |_l: &VersionedValue<i32>, r: &VersionedValue<i32>| r.clone();

        let (result, changed) = apply_remote_write(&local, &remote, resolve);
        assert!(changed);
        assert_eq!(result.value, 20);
    }

    #[test]
    fn test_apply_remote_write_happens_after() {
        let mut local_vc = VectorClock::new(&["server1", "server2"]);
        let mut remote_vc = VectorClock::new(&["server1", "server2"]);

        remote_vc.increment("server1");
        local_vc.increment("server1");
        local_vc.increment("server2");

        let local = VersionedValue::new(10, local_vc, "server2".to_string());
        let remote = VersionedValue::new(20, remote_vc, "server1".to_string());

        let resolve = |_l: &VersionedValue<i32>, r: &VersionedValue<i32>| r.clone();

        let (result, changed) = apply_remote_write(&local, &remote, resolve);
        assert!(!changed);
        assert_eq!(result.value, 10);
    }

    #[test]
    fn test_apply_remote_write_concurrent() {
        let mut local_vc = VectorClock::new(&["server1", "server2"]);
        let mut remote_vc = VectorClock::new(&["server1", "server2"]);

        local_vc.increment("server1");
        remote_vc.increment("server2");

        let local = VersionedValue::new(10, local_vc, "server1".to_string());
        let remote = VersionedValue::new(20, remote_vc, "server2".to_string());

        let resolve = |_l: &VersionedValue<i32>, r: &VersionedValue<i32>| r.clone();

        let (result, changed) = apply_remote_write(&local, &remote, resolve);
        assert!(changed);
        assert_eq!(result.value, 20); // Resolution chose remote
    }

    #[test]
    fn test_vector_clock_as_vec() {
        let mut vc = VectorClock::new(&["server1", "server2", "server3"]);
        vc.increment("server1");
        vc.increment("server3");

        let vec = vc.as_vec();
        assert_eq!(vec.len(), 3);
        assert_eq!(vec[0], ("server1".to_string(), 1));
        assert_eq!(vec[1], ("server2".to_string(), 0));
        assert_eq!(vec[2], ("server3".to_string(), 1));
    }

    #[test]
    fn test_causality_chain() {
        let mut vc1 = VectorClock::new(&["server1", "server2"]);
        let mut vc2 = VectorClock::new(&["server1", "server2"]);
        let mut vc3 = VectorClock::new(&["server1", "server2"]);

        // vc1: server1 increments
        vc1.increment("server1");

        // vc2: server2 receives vc1, then increments
        vc2.merge(&vc1);
        vc2.increment("server2");

        // vc3: server1 receives vc2, then increments
        vc3.merge(&vc2);
        vc3.increment("server1");

        // Verify causality chain
        assert_eq!(vc1.happens_before(&vc2), Some(true));
        assert_eq!(vc2.happens_before(&vc3), Some(true));
        assert_eq!(vc1.happens_before(&vc3), Some(true));
    }

    #[test]
    fn test_multiple_concurrent_events() {
        let mut vc1 = VectorClock::new(&["server1", "server2", "server3"]);
        let mut vc2 = VectorClock::new(&["server1", "server2", "server3"]);
        let mut vc3 = VectorClock::new(&["server1", "server2", "server3"]);

        vc1.increment("server1");
        vc2.increment("server2");
        vc3.increment("server3");

        assert!(vc1.is_concurrent(&vc2));
        assert!(vc2.is_concurrent(&vc3));
        assert!(vc1.is_concurrent(&vc3));
    }
}