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
use super::object_map::{ObjectMap, ObjectMapRef};
use super::visitor::*;
use crate::*;

use async_std::sync::Mutex as AsyncMutex;
use std::any::Any;
use std::collections::{hash_map::Entry, HashMap};
use std::sync::{Arc, Mutex};

/*
ObjectMap的缓存设计
每个op_env有独立的写缓存,用以暂存所有写入操作,在commit时候写入下层缓存
每个root共享一个读缓存
*/

// objectmap的依赖的noc接口,实现了object的最终保存和加载
#[async_trait::async_trait]
pub trait ObjectMapNOCCache: Send + Sync {
    async fn exists(&self, dec: Option<ObjectId>, object_id: &ObjectId) -> BuckyResult<bool>;

    async fn get_object_map(&self, dec: Option<ObjectId>, object_id: &ObjectId) -> BuckyResult<Option<ObjectMap>>;

    async fn put_object_map(&self, dec: Option<ObjectId>, object_id: ObjectId, object: ObjectMap) -> BuckyResult<()>;
}

pub type ObjectMapNOCCacheRef = Arc<Box<dyn ObjectMapNOCCache>>;

// 简单的内存版本的noc
pub(crate) struct ObjectMapMemoryNOCCache {
    cache: Mutex<HashMap<ObjectId, ObjectMap>>,
}

impl ObjectMapMemoryNOCCache {
    pub fn new() -> ObjectMapNOCCacheRef {
        let ret = Self {
            cache: Mutex::new(HashMap::new()),
        };

        Arc::new(Box::new(ret))
    }
}

#[async_trait::async_trait]
impl ObjectMapNOCCache for ObjectMapMemoryNOCCache {
    async fn exists(&self, dec_id: Option<ObjectId>, object_id: &ObjectId) -> BuckyResult<bool> {
        info!("[memory_noc] exists object: dec={:?}, {}", dec_id, object_id);

        Ok(self.cache.lock().unwrap().contains_key(object_id))
    }

    async fn get_object_map(&self, dec_id: Option<ObjectId>, object_id: &ObjectId) -> BuckyResult<Option<ObjectMap>> {
        info!("[memory_noc] load object: dec={:?}, {}", dec_id, object_id);

        let cache = self.cache.lock().unwrap();
        Ok(cache.get(object_id).map(|v| v.clone()))
    }

    async fn put_object_map(&self, dec_id: Option<ObjectId>, object_id: ObjectId, object: ObjectMap) -> BuckyResult<()> {
        info!("[memory_noc] save object: dec={:?}, {}", dec_id, object_id);

        {
            let mut cache = self.cache.lock().unwrap();
            cache.insert(object_id, object);
        }

        Ok(())
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////
///  同一个root共享的一个cache
#[async_trait::async_trait]
pub trait ObjectMapRootCache: Send + Sync {
    async fn exists(&self, object_id: &ObjectId) -> BuckyResult<bool>;

    async fn get_object_map(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>>;

    async fn put_object_map(&self, object_id: ObjectId, object: ObjectMap) -> BuckyResult<()>;
}

pub type ObjectMapRootCacheRef = Arc<Box<dyn ObjectMapRootCache>>;

pub struct ObjectMapRootMemoryCache {
    // None for system dec
    dec_id: Option<ObjectId>,

    // 依赖的底层缓存,一般是noc层的缓存
    noc: ObjectMapNOCCacheRef,

    // 用来缓存从noc加载的objectmap和subs
    cache: Arc<Mutex<lru_time_cache::LruCache<ObjectId, ObjectMapRef>>>,
}

impl ObjectMapRootMemoryCache {
    pub fn new(dec_id: Option<ObjectId>, noc: ObjectMapNOCCacheRef, timeout_in_secs: u64, capacity: usize) -> Self {
        let cache = lru_time_cache::LruCache::with_expiry_duration_and_capacity(
            std::time::Duration::from_secs(timeout_in_secs),
            capacity,
        );

        Self {
            dec_id,
            noc,
            cache: Arc::new(Mutex::new(cache)),
        }
    }

    pub fn new_ref(dec_id: Option<ObjectId>, noc: ObjectMapNOCCacheRef, timeout_in_secs: u64, capacity: usize) -> ObjectMapRootCacheRef {
        Arc::new(Box::new(Self::new(dec_id, noc, timeout_in_secs, capacity)))
    }

    pub fn new_default_ref(dec_id: Option<ObjectId>, noc: ObjectMapNOCCacheRef) -> ObjectMapRootCacheRef {
        Arc::new(Box::new(Self::new(dec_id, noc, 60 * 5, 1024)))
    }

    async fn exists(&self, object_id: &ObjectId) -> BuckyResult<bool> {
        if self.cache.lock().unwrap().contains_key(object_id) {
            return Ok(true);
        }

        self.noc.exists(self.dec_id.clone(), object_id).await
    }

    async fn get_object_map(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        let obj = self.get_object_map_impl(object_id).await?;

        // FIXME 校验一次id是否是最新的
        if let Some(obj) = &obj {
            let current = obj.lock().await;
            let real_id = current.flush_id_without_cache();
            assert_eq!(real_id, *object_id);

            let current_id = current.cached_object_id();
            assert_eq!(current_id, Some(real_id));
        }

        Ok(obj)
    }

    async fn get_object_map_impl(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        // 首先查看缓存
        if let Some(v) = self.cache.lock().unwrap().get(object_id) {
            return Ok(Some(v.to_owned()));
        }

        // 最后尝试从noc加载
        let ret = self.noc.get_object_map(self.dec_id.clone(), object_id).await?;
        if ret.is_none() {
            return Ok(None);
        }

        let obj = ret.unwrap();

        let obj = Arc::new(AsyncMutex::new(obj));

        // 缓存
        {
            let mut cache = self.cache.lock().unwrap();
            if let Some(_) = cache.insert(object_id.to_owned(), obj.clone()) {
                warn!(
                    "insert objectmap to memory cache but already exists! id={}",
                    object_id
                );
            }
        }

        Ok(Some(obj))
    }

    async fn put_object_map(&self, object_id: ObjectId, object: ObjectMap) -> BuckyResult<()> {
        // TODO 这里是否需要更新缓存?

        // FIXME 校验一次id是否是最新的
        assert_eq!(Some(object_id), object.cached_object_id());
        let current_id = object.flush_id();
        assert_eq!(object_id, current_id);
        let real_id = object.flush_id_without_cache();
        assert_eq!(real_id, current_id);

        self.noc.put_object_map(self.dec_id.clone(), object_id, object).await
    }
}

#[async_trait::async_trait]
impl ObjectMapRootCache for ObjectMapRootMemoryCache {
    async fn exists(&self, object_id: &ObjectId) -> BuckyResult<bool> {
        Self::exists(&self, object_id).await
    }

    async fn get_object_map(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        Self::get_object_map(&self, object_id).await
    }

    async fn put_object_map(&self, object_id: ObjectId, object: ObjectMap) -> BuckyResult<()> {
        Self::put_object_map(&self, object_id, object).await
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/// ObjectMap op_env操作粒度的cache
#[async_trait::async_trait]
pub trait ObjectMapOpEnvCache: Send + Sync {
    // from pending list and lower cache
    async fn get_object_map(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>>;

    // check if target object exists, in cache and in lower cache, not only for ObjectMap
    async fn exists(&self, object_id: &ObjectId) -> BuckyResult<bool>;

    // 同步的put,放置到暂存区
    fn put_object_map(&self, object_id: &ObjectId, object: ObjectMap) -> BuckyResult<ObjectMapRef>;

    // 从暂存区移除先前已经提交的操作(put_sub之后,commit之前)
    fn remove_object_map(&self, object_id: &ObjectId) -> BuckyResult<ObjectMapRef>;

    // 提交所有的暂存操作到下一级缓存/存储
    async fn commit(&self) -> BuckyResult<()>;

    // gc before commit, clear all untouchable objects from target
    async fn gc(&self, single: bool, target: &ObjectId) -> BuckyResult<()>;

    // 清除所有待提交的对象
    fn abort(&self);
}

pub type ObjectMapOpEnvCacheRef = Arc<Box<dyn ObjectMapOpEnvCache>>;

struct ObjectMapPendingItem {
    is_touched: bool,
    item: ObjectMapRef,
}

// 写操作缓存
struct ObjectMapOpEnvMemoryCachePendingList {
    pending: HashMap<ObjectId, ObjectMapPendingItem>,
}

impl ObjectMapOpEnvMemoryCachePendingList {
    pub fn new() -> Self {
        Self {
            pending: HashMap::new(),
        }
    }

    fn exists(&mut self, object_id: &ObjectId) -> bool {
        self.pending.contains_key(object_id)
    }

    fn get_object_map(&mut self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        if let Some(v) = self.pending.get(object_id) {
            return Ok(Some(v.item.to_owned()));
        }

        // 缺页错误
        Ok(None)
    }

    fn remove_object_map(&mut self, object_id: &ObjectId) -> BuckyResult<ObjectMapRef> {
        match self.pending.remove(object_id) {
            Some(ret) => {
                info!("will remove pending objectmap from cache! id={}", object_id);
                Ok(ret.item)
            }
            None => {
                let msg = format!(
                    "remove pending objectmap from cache but not found! id={}",
                    object_id
                );
                error!("{}", msg);
                Err(BuckyError::new(BuckyErrorCode::NotFound, msg))
            }
        }
    }

    fn put_object_map(
        &mut self,
        object_id: &ObjectId,
        object: ObjectMap,
    ) -> BuckyResult<ObjectMapRef> {
        let object = Arc::new(AsyncMutex::new(object));

        match self.pending.entry(object_id.to_owned()) {
            Entry::Occupied(mut o) => {
                warn!(
                    "insert object to objectmap memory cache but already exists! id={}",
                    object_id
                );
                let v = ObjectMapPendingItem {
                    is_touched: false,
                    item: object.clone(),
                };
                o.insert(v);
            }
            Entry::Vacant(v) => {
                debug!("insert object to objectmap memory cache! id={}", object_id);
                let item = ObjectMapPendingItem {
                    is_touched: false,
                    item: object.clone(),
                };
                v.insert(item);
            }
        };

        Ok(object)
    }

    async fn commit(
        pending: HashMap<ObjectId, ObjectMapPendingItem>,
        root_cache: ObjectMapRootCacheRef,
    ) -> BuckyResult<()> {
        let count = pending.len();
        for (object_id, value) in pending {
            let value = value.item;

            assert!(Arc::strong_count(&value) == 1);
            let value = Arc::try_unwrap(value).unwrap();
            let obj = value.into_inner();

            if let Err(e) = root_cache.put_object_map(object_id.clone(), obj).await {
                let msg = format!("commit pending objectmap error! obj={}, {}", object_id, e);
                error!("{}", msg);
                return Err(e);
            }
        }

        info!("commit all pending objectmap success! count={}", count);
        Ok(())
    }
}

pub struct ObjectMapOpEnvMemoryCache {
    // 依赖的底层root缓存
    root_cache: ObjectMapRootCacheRef,

    pending: Mutex<ObjectMapOpEnvMemoryCachePendingList>,
}

impl ObjectMapOpEnvMemoryCache {
    pub fn new(root_cache: ObjectMapRootCacheRef) -> Self {
        Self {
            root_cache,
            pending: Mutex::new(ObjectMapOpEnvMemoryCachePendingList::new()),
        }
    }

    pub fn new_ref(root_cache: ObjectMapRootCacheRef) -> ObjectMapOpEnvCacheRef {
        Arc::new(Box::new(Self::new(root_cache)))
    }
}

#[async_trait::async_trait]
impl ObjectMapOpEnvCache for ObjectMapOpEnvMemoryCache {
    async fn exists(&self, object_id: &ObjectId) -> BuckyResult<bool> {
        if self.pending.lock().unwrap().exists(object_id) {
            return Ok(true);
        }

        self.root_cache.exists(object_id).await
    }

    async fn get_object_map(&self, object_id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        // 首先从当前写缓存里面查找
        if let Some(obj) = self.pending.lock().unwrap().get_object_map(object_id)? {
            return Ok(Some(obj));
        }

        // 最后尝试从root_cache加载
        self.root_cache.get_object_map(object_id).await
    }

    fn put_object_map(&self, object_id: &ObjectId, object: ObjectMap) -> BuckyResult<ObjectMapRef> {
        self.pending
            .lock()
            .unwrap()
            .put_object_map(object_id, object)
    }

    fn remove_object_map(&self, object_id: &ObjectId) -> BuckyResult<ObjectMapRef> {
        self.pending.lock().unwrap().remove_object_map(object_id)
    }

    async fn commit(&self) -> BuckyResult<()> {
        // FIXME 这里提交操作会清空所有的pending对象,所以只能操作一次
        let mut pending = HashMap::new();
        {
            let mut inner = self.pending.lock().unwrap();
            std::mem::swap(&mut inner.pending, &mut pending);
        }
        ObjectMapOpEnvMemoryCachePendingList::commit(pending, self.root_cache.clone()).await
    }

    fn abort(&self) {
        self.pending.lock().unwrap().pending.clear();
    }

    async fn gc(&self, single: bool, target: &ObjectId) -> BuckyResult<()> {
        info!("objectmap op_env cache will gc, single={}, target={}", single, target);

        let mut pending = HashMap::new();
        {
            let mut inner = self.pending.lock().unwrap();
            std::mem::swap(&mut inner.pending, &mut pending);
        }

        let prev_count = pending.len();
        let gc = ObjectMapOpEnvMemoryCacheGC::new(pending);
        let result = if single {
            gc.single_gc(target).await?
        } else {
            gc.path_gc(target).await?
        };

        let mut result: HashMap<ObjectId, ObjectMapPendingItem> = result.into_iter().filter(|item| {
            item.1.is_touched
        }).collect();

        info!("gc for target single={}, target={}, {} -> {}", single, target, prev_count, result.len());

        {
            let mut inner = self.pending.lock().unwrap();
            std::mem::swap(&mut inner.pending, &mut result);
        }

        Ok(())
    }
}


struct ObjectMapOpEnvMemoryCacheGC {
    pending: HashMap<ObjectId, ObjectMapPendingItem>,
}

impl ObjectMapOpEnvMemoryCacheGC {
    pub fn new(pending: HashMap<ObjectId, ObjectMapPendingItem>) -> Self {
        Self {
            pending,
        }
    }

    fn touch_item(&mut self, id: &ObjectId) {
        debug!("gc touch item: {}", id);
        if id.is_data()  {
            return;
        }

        if let Some(v) = self.pending.get_mut(id) {
            v.is_touched = true;
        }
    }

    pub async fn single_gc(
        mut self,
        target: &ObjectId,
    ) -> BuckyResult<HashMap<ObjectId, ObjectMapPendingItem>> {
        self.touch_item(target);

        let mut visitor = ObjectMapFullVisitor::new(Box::new(self));
        visitor.visit(target).await?;

        let loader = visitor.into_provider();
        let this = loader.into_any().downcast::<Self>().unwrap();
        Ok(this.pending)
    }

    pub async fn path_gc(mut self, root: &ObjectId) -> BuckyResult<HashMap<ObjectId, ObjectMapPendingItem>> {
        // first touch the root
        self.touch_item(root);

        let mut visitor = ObjectMapPathVisitor::new(Box::new(self));
        visitor.visit(root).await?;

        let visitor = visitor.into_provider();
        let this = visitor.into_any().downcast::<Self>().unwrap();
        Ok(this.pending)
    }
}

#[async_trait::async_trait]
impl ObjectMapVisitLoader for ObjectMapOpEnvMemoryCacheGC {
    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        self
    }

    async fn get_object_map(&mut self, id: &ObjectId) -> BuckyResult<Option<ObjectMapRef>> {
        if let Some(v) = self.pending.get(id) {
            return Ok(Some(v.item.clone()));
        }

        debug!("object not exists: {}", id);
        // 缺页错误
        Ok(None)
    }
}

#[async_trait::async_trait]
impl ObjectMapVisitor for ObjectMapOpEnvMemoryCacheGC {
    async fn visit_hub_item(&mut self, item: &ObjectId) -> BuckyResult<()> {
        self.touch_item(&item);

        Ok(())
    }

    async fn visit_map_item(&mut self, _key: &str, item: &ObjectId) -> BuckyResult<()> {
        self.touch_item(&item);

        Ok(())
    }

    async fn visit_set_item(&mut self, item: &ObjectId) -> BuckyResult<()> {
        self.touch_item(&item);

        Ok(())
    }

    async fn visit_diff_map_item(
        &mut self,
        _key: &str,
        item: &ObjectMapDiffMapItem,
    ) -> BuckyResult<()> {
        if let Some(id) = &item.diff {
            self.touch_item(&id);
        }

        Ok(())
    }

    async fn visit_diff_set_item(&mut self, _item: &ObjectMapDiffSetItem) -> BuckyResult<()> {
        Ok(())
    }
}

impl ObjectMapVisitorProvider for ObjectMapOpEnvMemoryCacheGC {}