rusmes-storage 0.1.2

Storage abstraction layer for RusMES — trait-based mailbox and message store with filesystem (maildir), PostgreSQL, and AmateRS distributed backends
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
//! MODSEQ (Modification Sequence) tracking for IMAP CONDSTORE
//!
//! This module implements modification sequence numbers (MODSEQ) for tracking
//! message and mailbox changes, as required by RFC 7162 (CONDSTORE/QRESYNC).

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

/// Modification sequence number
///
/// MODSEQ is a 64-bit unsigned integer that increases monotonically
/// for each change to a mailbox or message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModSeq(pub u64);

impl ModSeq {
    /// Create a new MODSEQ with value 0 (invalid/initial state)
    pub const fn zero() -> Self {
        Self(0)
    }

    /// Create a new MODSEQ with value 1 (first valid MODSEQ)
    pub const fn one() -> Self {
        Self(1)
    }

    /// Create a new MODSEQ from a u64 value
    pub const fn new(value: u64) -> Self {
        Self(value)
    }

    /// Get the u64 value
    pub const fn value(&self) -> u64 {
        self.0
    }

    /// Check if this is a valid MODSEQ (non-zero)
    pub const fn is_valid(&self) -> bool {
        self.0 > 0
    }

    /// Increment and return the new value
    pub fn increment(&mut self) -> Self {
        self.0 += 1;
        *self
    }
}

impl std::fmt::Display for ModSeq {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<u64> for ModSeq {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<ModSeq> for u64 {
    fn from(modseq: ModSeq) -> u64 {
        modseq.0
    }
}

/// MODSEQ generator for creating unique modification sequence numbers
///
/// This is a thread-safe atomic counter that ensures MODSEQs are
/// monotonically increasing across the entire server.
#[derive(Debug, Clone)]
pub struct ModSeqGenerator {
    counter: Arc<AtomicU64>,
}

impl ModSeqGenerator {
    /// Create a new MODSEQ generator starting from 1
    pub fn new() -> Self {
        Self {
            counter: Arc::new(AtomicU64::new(1)),
        }
    }

    /// Create a new MODSEQ generator starting from a specific value
    pub fn with_start_value(start: u64) -> Self {
        Self {
            counter: Arc::new(AtomicU64::new(start.max(1))),
        }
    }

    /// Generate the next MODSEQ value
    pub fn next(&self) -> ModSeq {
        let value = self.counter.fetch_add(1, Ordering::SeqCst);
        ModSeq(value)
    }

    /// Get the current MODSEQ value without incrementing
    pub fn current(&self) -> ModSeq {
        let value = self.counter.load(Ordering::SeqCst);
        ModSeq(value.saturating_sub(1).max(1))
    }

    /// Get the highest MODSEQ value (next - 1)
    pub fn highest(&self) -> ModSeq {
        self.current()
    }
}

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

/// Message metadata with MODSEQ tracking
#[derive(Debug, Clone)]
pub struct MessageModSeq {
    /// Message UID
    pub uid: u32,
    /// Current MODSEQ value for this message
    pub modseq: ModSeq,
}

impl MessageModSeq {
    /// Create new message metadata
    pub fn new(uid: u32, modseq: ModSeq) -> Self {
        Self { uid, modseq }
    }
}

/// Mailbox metadata with MODSEQ tracking
#[derive(Debug, Clone)]
pub struct MailboxModSeq {
    /// Mailbox name
    pub name: String,
    /// Highest MODSEQ in this mailbox
    pub highestmodseq: ModSeq,
    /// UIDVALIDITY value
    pub uidvalidity: u32,
    /// Next UID to be assigned
    pub uidnext: u32,
}

impl MailboxModSeq {
    /// Create new mailbox metadata
    pub fn new(name: String, uidvalidity: u32, uidnext: u32) -> Self {
        Self {
            name,
            highestmodseq: ModSeq::one(),
            uidvalidity,
            uidnext,
        }
    }

    /// Update the highest MODSEQ if the given value is higher
    pub fn update_modseq(&mut self, modseq: ModSeq) {
        if modseq > self.highestmodseq {
            self.highestmodseq = modseq;
        }
    }
}

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

    #[test]
    fn test_modseq_creation() {
        let modseq = ModSeq::zero();
        assert_eq!(modseq.value(), 0);
        assert!(!modseq.is_valid());

        let modseq = ModSeq::one();
        assert_eq!(modseq.value(), 1);
        assert!(modseq.is_valid());

        let modseq = ModSeq::new(42);
        assert_eq!(modseq.value(), 42);
        assert!(modseq.is_valid());
    }

    #[test]
    fn test_modseq_increment() {
        let mut modseq = ModSeq::one();
        assert_eq!(modseq.value(), 1);

        let new_modseq = modseq.increment();
        assert_eq!(new_modseq.value(), 2);
        assert_eq!(modseq.value(), 2);
    }

    #[test]
    fn test_modseq_increment_multiple() {
        let mut modseq = ModSeq::zero();
        for i in 1..=10 {
            let result = modseq.increment();
            assert_eq!(result.value(), i);
            assert_eq!(modseq.value(), i);
        }
    }

    #[test]
    fn test_modseq_ordering() {
        let modseq1 = ModSeq::new(10);
        let modseq2 = ModSeq::new(20);

        assert!(modseq1 < modseq2);
        assert!(modseq2 > modseq1);
        assert_eq!(modseq1, modseq1.clone());
    }

    #[test]
    fn test_modseq_ordering_edge_cases() {
        let zero = ModSeq::zero();
        let one = ModSeq::one();
        let max = ModSeq::new(u64::MAX);

        assert!(zero < one);
        assert!(one < max);
        assert!(zero < max);
    }

    #[test]
    fn test_modseq_equality() {
        let m1 = ModSeq::new(100);
        let m2 = ModSeq::new(100);
        let m3 = ModSeq::new(200);

        assert_eq!(m1, m2);
        assert_ne!(m1, m3);
    }

    #[test]
    fn test_modseq_hash() {
        let mut set = HashSet::new();
        set.insert(ModSeq::new(1));
        set.insert(ModSeq::new(2));
        set.insert(ModSeq::new(1)); // Duplicate

        assert_eq!(set.len(), 2);
        assert!(set.contains(&ModSeq::new(1)));
        assert!(set.contains(&ModSeq::new(2)));
    }

    #[test]
    fn test_modseq_generator() {
        let gen = ModSeqGenerator::new();

        let modseq1 = gen.next();
        assert_eq!(modseq1.value(), 1);

        let modseq2 = gen.next();
        assert_eq!(modseq2.value(), 2);

        let modseq3 = gen.next();
        assert_eq!(modseq3.value(), 3);
    }

    #[test]
    fn test_modseq_generator_with_start() {
        let gen = ModSeqGenerator::with_start_value(100);

        let modseq1 = gen.next();
        assert_eq!(modseq1.value(), 100);

        let modseq2 = gen.next();
        assert_eq!(modseq2.value(), 101);
    }

    #[test]
    fn test_modseq_generator_with_zero_start() {
        // Zero should be converted to 1
        let gen = ModSeqGenerator::with_start_value(0);
        let modseq = gen.next();
        assert_eq!(modseq.value(), 1);
    }

    #[test]
    fn test_modseq_generator_current() {
        let gen = ModSeqGenerator::new();

        let _m1 = gen.next();
        let _m2 = gen.next();
        let _m3 = gen.next();

        let current = gen.current();
        assert_eq!(current.value(), 3);

        let highest = gen.highest();
        assert_eq!(highest, current);
    }

    #[test]
    fn test_modseq_generator_current_before_first_next() {
        let gen = ModSeqGenerator::new();
        let current = gen.current();
        assert_eq!(current.value(), 1);
    }

    #[test]
    fn test_modseq_generator_clone() {
        let gen1 = ModSeqGenerator::new();
        let _m1 = gen1.next();
        let _m2 = gen1.next();

        // Cloning shares the same Arc<AtomicU64>, so both generators use the same counter
        let gen2 = gen1.clone();
        let m3 = gen2.next();
        let m4 = gen1.next();

        assert_eq!(m3.value(), 3);
        assert_eq!(m4.value(), 4); // gen1 continues from where gen2 left off
    }

    #[test]
    fn test_modseq_generator_thread_safety() {
        use std::thread;

        let gen = ModSeqGenerator::new();
        let gen1 = gen.clone();
        let gen2 = gen.clone();

        let handle1 = thread::spawn(move || {
            let mut values = Vec::new();
            for _ in 0..10 {
                values.push(gen1.next().value());
            }
            values
        });

        let handle2 = thread::spawn(move || {
            let mut values = Vec::new();
            for _ in 0..10 {
                values.push(gen2.next().value());
            }
            values
        });

        let values1 = handle1.join().unwrap();
        let values2 = handle2.join().unwrap();

        // All values should be unique
        let mut all_values: Vec<_> = values1.into_iter().chain(values2).collect();
        all_values.sort_unstable();
        all_values.dedup();
        assert_eq!(all_values.len(), 20);
    }

    #[test]
    fn test_message_modseq() {
        let msg = MessageModSeq::new(42, ModSeq::new(100));
        assert_eq!(msg.uid, 42);
        assert_eq!(msg.modseq.value(), 100);
    }

    #[test]
    fn test_message_modseq_clone() {
        let msg1 = MessageModSeq::new(42, ModSeq::new(100));
        let msg2 = msg1.clone();
        assert_eq!(msg1.uid, msg2.uid);
        assert_eq!(msg1.modseq, msg2.modseq);
    }

    #[test]
    fn test_mailbox_modseq_new() {
        let mbox = MailboxModSeq::new("INBOX".to_string(), 123, 456);
        assert_eq!(mbox.name, "INBOX");
        assert_eq!(mbox.highestmodseq, ModSeq::one());
        assert_eq!(mbox.uidvalidity, 123);
        assert_eq!(mbox.uidnext, 456);
    }

    #[test]
    fn test_mailbox_modseq_update() {
        let mut mbox = MailboxModSeq::new("INBOX".to_string(), 1, 1);
        assert_eq!(mbox.highestmodseq.value(), 1);

        mbox.update_modseq(ModSeq::new(10));
        assert_eq!(mbox.highestmodseq.value(), 10);

        // Should not decrease
        mbox.update_modseq(ModSeq::new(5));
        assert_eq!(mbox.highestmodseq.value(), 10);

        // Should increase
        mbox.update_modseq(ModSeq::new(15));
        assert_eq!(mbox.highestmodseq.value(), 15);
    }

    #[test]
    fn test_mailbox_modseq_update_same_value() {
        let mut mbox = MailboxModSeq::new("INBOX".to_string(), 1, 1);
        mbox.update_modseq(ModSeq::new(10));
        assert_eq!(mbox.highestmodseq.value(), 10);

        // Updating with same value should not change anything
        mbox.update_modseq(ModSeq::new(10));
        assert_eq!(mbox.highestmodseq.value(), 10);
    }

    #[test]
    fn test_mailbox_modseq_clone() {
        let mbox1 = MailboxModSeq::new("INBOX".to_string(), 123, 456);
        let mbox2 = mbox1.clone();
        assert_eq!(mbox1.name, mbox2.name);
        assert_eq!(mbox1.highestmodseq, mbox2.highestmodseq);
        assert_eq!(mbox1.uidvalidity, mbox2.uidvalidity);
        assert_eq!(mbox1.uidnext, mbox2.uidnext);
    }

    #[test]
    fn test_modseq_from_u64() {
        let modseq: ModSeq = 42u64.into();
        assert_eq!(modseq.value(), 42);

        let value: u64 = modseq.into();
        assert_eq!(value, 42);
    }

    #[test]
    fn test_modseq_from_u64_max() {
        let modseq: ModSeq = u64::MAX.into();
        assert_eq!(modseq.value(), u64::MAX);
    }

    #[test]
    fn test_modseq_display() {
        let modseq = ModSeq::new(12345);
        assert_eq!(modseq.to_string(), "12345");
    }

    #[test]
    fn test_modseq_display_zero() {
        let modseq = ModSeq::zero();
        assert_eq!(modseq.to_string(), "0");
    }

    #[test]
    fn test_modseq_display_large() {
        let modseq = ModSeq::new(u64::MAX);
        assert_eq!(modseq.to_string(), u64::MAX.to_string());
    }

    #[test]
    fn test_modseq_generator_default() {
        let gen = ModSeqGenerator::default();
        let modseq = gen.next();
        assert_eq!(modseq.value(), 1);
    }

    #[test]
    fn test_modseq_const_functions() {
        const ZERO: ModSeq = ModSeq::zero();
        const ONE: ModSeq = ModSeq::one();
        const CUSTOM: ModSeq = ModSeq::new(42);

        assert_eq!(ZERO.value(), 0);
        assert_eq!(ONE.value(), 1);
        assert_eq!(CUSTOM.value(), 42);
    }
}