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
use std::ops::Deref;
use std::ops::DerefMut;
use std::hash::Hash;
use std::hash::Hasher;
use std::cmp::Eq;
use std::cmp::PartialEq;
use std::fmt;

pub type Epoch = i64;

/// Keep track of changes to object using epoch
/// for every changes to objects, epoch counter must be incremented
#[derive(Debug, Default, Clone)]
pub struct EpochCounter<T> {
    epoch: Epoch,
    inner: T,
}

impl<T> Hash for EpochCounter<T>
where
    T: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}

impl<T> PartialEq for EpochCounter<T>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl<T> Eq for EpochCounter<T> where T: Eq {}

impl<T> Deref for EpochCounter<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> DerefMut for EpochCounter<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<T> fmt::Display for EpochCounter<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "epoch: {}", self.epoch)
    }
}

impl<T> From<T> for EpochCounter<T> {
    fn from(inner: T) -> Self {
        Self { epoch: 0, inner }
    }
}

impl<T> EpochCounter<T> {
    pub fn new(inner: T) -> Self {
        Self { epoch: 0, inner }
    }

    pub fn new_with_epoch(inner: T, epoch: impl Into<i64>) -> Self {
        Self {
            epoch: epoch.into(),
            inner,
        }
    }

    pub fn inner(&self) -> &T {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.inner
    }

    pub fn inner_owned(self) -> T {
        self.inner
    }

    pub fn epoch(&self) -> Epoch {
        self.epoch
    }

    fn set_epoch(&mut self, epoch: Epoch) {
        self.epoch = epoch;
    }

    pub fn increment(&mut self) {
        self.epoch += 1;
    }

    pub fn decrement(&mut self) {
        self.epoch -= 1;
    }
}

pub use old_map::*;

mod old_map {

    use std::collections::HashMap;
    use std::hash::Hash;
    use std::borrow::Borrow;

    use super::*;

    /// use epoch counter for every value in the hashmap
    /// if value are deleted, it is moved to thrash can (deleted)
    /// using epoch counter, level changes can be calculated
    #[derive(Debug, Default)]
    pub struct EpochMap<K, V> {
        epoch: EpochCounter<()>,
        fence: EpochCounter<()>, // last changes
        map: HashMap<K, EpochCounter<V>>,
        deleted: Vec<EpochCounter<V>>,
    }

    impl<K, V> Deref for EpochMap<K, V> {
        type Target = HashMap<K, EpochCounter<V>>;

        fn deref(&self) -> &Self::Target {
            &self.map
        }
    }

    impl<K, V> DerefMut for EpochMap<K, V> {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.map
        }
    }

    impl<K, V> EpochMap<K, V> {
        pub fn increment_epoch(&mut self) {
            self.epoch.increment();
        }

        pub fn epoch(&self) -> Epoch {
            self.epoch.epoch()
        }

        /// fence history to current epoch,
        /// older before fence will be lost
        pub fn mark_fence(&mut self) {
            self.deleted = vec![];
            self.fence = self.epoch.clone();
        }
    }

    impl<K, V> EpochMap<K, V>
    where
        K: Eq + Hash,
    {
        pub fn new() -> Self {
            Self::new_with_map(HashMap::new())
        }

        pub fn new_with_map(map: HashMap<K, EpochCounter<V>>) -> Self {
            Self {
                epoch: EpochCounter::default(),
                fence: EpochCounter::default(),
                map,
                deleted: vec![],
            }
        }

        /// insert new value
        /// remove history from deleted set
        pub fn insert(&mut self, key: K, value: V) -> Option<EpochCounter<V>>
        where
            K: Clone,
        {
            let mut epoch_value: EpochCounter<V> = value.into();
            epoch_value.set_epoch(self.epoch.epoch());
            self.map.insert(key, epoch_value)
        }

        /// remove existing value
        /// if successful, remove are added to history
        pub fn remove<Q>(&mut self, k: &Q) -> Option<EpochCounter<V>>
        where
            K: Borrow<Q>,
            Q: ?Sized + Hash + Eq,
            V: Clone,
        {
            if let Some((_, mut old_value)) = self.map.remove_entry(k) {
                old_value.set_epoch(self.epoch.epoch());
                self.deleted.push(old_value.clone());
                Some(old_value)
            } else {
                None
            }
        }
    }

    impl<K, V> EpochMap<K, V>
    where
        K: Clone,
    {
        pub fn clone_keys(&self) -> Vec<K> {
            self.keys().cloned().collect()
        }
    }

    impl<K, V> EpochMap<K, V>
    where
        V: Clone,
        K: Clone,
    {
        pub fn clone_values(&self) -> Vec<V> {
            self.values().cloned().map(|c| c.inner_owned()).collect()
        }

        /// find all changes since a epoch
        /// if epoch is before fence, return full changes with epoch,
        /// otherwise return delta changes
        /// user should keep that epoch and do subsequent changes
        pub fn changes_since<E>(&self, epoch_value: E) -> EpochChanges<V>
        where
            Epoch: From<E>,
        {
            let epoch = epoch_value.into();
            if epoch < self.fence.epoch() {
                return EpochChanges {
                    epoch: self.epoch.epoch(),
                    changes: EpochDeltaChanges::SyncAll(self.clone_values()),
                };
            }

            if epoch == self.epoch() {
                return EpochChanges {
                    epoch: self.epoch.epoch(),
                    changes: EpochDeltaChanges::empty(),
                };
            }

            let updates = self
                .values()
                .filter_map(|v| {
                    if v.epoch > epoch {
                        Some(v.inner().clone())
                    } else {
                        None
                    }
                })
                .collect();

            let deletes = self
                .deleted
                .iter()
                .filter_map(|d| {
                    if d.epoch > epoch {
                        Some(d.inner().clone())
                    } else {
                        None
                    }
                })
                .collect();

            EpochChanges {
                epoch: self.epoch.epoch(),
                changes: EpochDeltaChanges::Changes((updates, deletes)),
            }
        }
    }

    pub struct EpochChanges<V> {
        // current epoch
        pub epoch: Epoch,
        changes: EpochDeltaChanges<V>,
    }

    impl<V: fmt::Debug> fmt::Debug for EpochChanges<V> {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.debug_struct("EpochChanges")
                .field("epoch", &self.epoch)
                .field("changes", &self.changes)
                .finish()
        }
    }

    impl<V> EpochChanges<V> {
        pub fn new(epoch: Epoch, changes: EpochDeltaChanges<V>) -> Self {
            Self { epoch, changes }
        }

        /// current epoch
        pub fn current_epoch(&self) -> &Epoch {
            &self.epoch
        }

        /// return all updates regardless of sync or changes
        /// (update,deletes)
        pub fn parts(self) -> (Vec<V>, Vec<V>) {
            match self.changes {
                EpochDeltaChanges::SyncAll(all) => (all, vec![]),
                EpochDeltaChanges::Changes(changes) => changes,
            }
        }

        pub fn is_empty(&self) -> bool {
            match &self.changes {
                EpochDeltaChanges::SyncAll(all) => all.is_empty(),
                EpochDeltaChanges::Changes(changes) => changes.0.is_empty() && changes.1.is_empty(),
            }
        }

        /// is change contain sync all
        pub fn is_sync_all(&self) -> bool {
            match &self.changes {
                EpochDeltaChanges::SyncAll(_) => true,
                EpochDeltaChanges::Changes(_) => false,
            }
        }
    }

    pub enum EpochDeltaChanges<V> {
        SyncAll(Vec<V>),
        Changes((Vec<V>, Vec<V>)),
    }

    impl<V> EpochDeltaChanges<V> {
        pub fn empty() -> Self {
            Self::Changes((vec![], vec![]))
        }
    }

    impl<V: fmt::Debug> fmt::Debug for EpochDeltaChanges<V> {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::SyncAll(all) => f.debug_tuple("SyncAll").field(all).finish(),
                Self::Changes((add, del)) => {
                    f.debug_tuple("Changes").field(add).field(del).finish()
                }
            }
        }
    }
}

#[cfg(test)]
mod test {

    use std::fmt::Display;

    use serde::{Serialize, Deserialize};

    use crate::core::{Spec, Status};
    use crate::store::DefaultMetadataObject;

    use super::EpochMap;

    // define test spec and status
    #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
    struct TestSpec {
        replica: u16,
    }

    impl Spec for TestSpec {
        const LABEL: &'static str = "Test";
        type IndexKey = String;
        type Owner = Self;
        type Status = TestStatus;
    }

    #[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
    struct TestStatus {
        up: bool,
    }

    impl Status for TestStatus {}

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

    type DefaultTest = DefaultMetadataObject<TestSpec>;

    type TestEpochMap = EpochMap<String, DefaultTest>;

    #[test]
    fn test_epoch_map_empty() {
        let map = TestEpochMap::new();
        assert_eq!(map.epoch(), 0);
    }

    #[test]
    fn test_epoch_map_insert() {
        let mut map = TestEpochMap::new();

        // increase epoch
        // epoch must be increased before any write occur manually here
        // in the store, this is done automatically but this is low level interface
        map.increment_epoch();

        let test1 = DefaultTest::with_key("t1");
        map.insert(test1.key_owned(), test1);

        assert_eq!(map.epoch(), 1);

        // test with before base epoch
        {
            let changes = map.changes_since(-1);
            assert_eq!(*changes.current_epoch(), 1); // current epoch is 1
            assert!(changes.is_sync_all()); // this is only delta

            let (updates, deletes) = changes.parts();
            assert_eq!(updates.len(), 1);
            assert_eq!(deletes.len(), 0);
        }

        // test with base epoch
        {
            let changes = map.changes_since(0);
            assert_eq!(*changes.current_epoch(), 1); // current epoch is 1
            assert!(!changes.is_sync_all()); // this is only delta

            let (updates, deletes) = changes.parts();
            assert_eq!(updates.len(), 1);
            assert_eq!(deletes.len(), 0);
        }

        // test with current epoch which should return empty
        {
            let changes = map.changes_since(1);
            assert_eq!(*changes.current_epoch(), 1); // current epoch is 1
            assert!(!changes.is_sync_all()); // this is only delta
            let (updates, deletes) = changes.parts();
            assert_eq!(updates.len(), 0);
            assert_eq!(deletes.len(), 0);
        }
    }

    #[test]
    fn test_epoch_map_insert_update() {
        let mut map = TestEpochMap::new();

        let test1 = DefaultTest::with_key("t1");
        let test2 = test1.clone();
        let test3 = DefaultTest::with_key("t2");

        // first epoch
        map.increment_epoch();
        map.insert(test1.key_owned(), test1);
        map.insert(test3.key_owned(), test3);

        // second epoch
        map.increment_epoch();
        map.insert(test2.key_owned(), test2);

        assert_eq!(map.epoch(), 2);

        // test with base epoch, this should return a single changes, both insert/update are consolidated into a single
        {
            let changes = map.changes_since(0);
            assert_eq!(*changes.current_epoch(), 2);
            assert!(!changes.is_sync_all());

            let (updates, deletes) = changes.parts();
            assert_eq!(updates.len(), 2);
            assert_eq!(deletes.len(), 0);
        }

        // test with middle epoch, this should still return a single changes
        {
            let changes = map.changes_since(1);
            assert_eq!(*changes.current_epoch(), 2);
            assert!(!changes.is_sync_all());
            let (updates, deletes) = changes.parts();
            assert_eq!(updates.len(), 1);
            assert_eq!(deletes.len(), 0);
        }
    }
}