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
use super::cache::*;
use super::lock::*;
use super::path_env::*;
use super::single_env::*;
use crate::*;

use std::str::FromStr;
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex};

#[derive(Clone, Debug, Copy, Eq, PartialEq)]
pub enum ObjectMapOpEnvType {
    Path,
    Single,
}

impl ToString for ObjectMapOpEnvType {
    fn to_string(&self) -> String {
        match *self {
            Self::Path => "path",
            Self::Single => "single",
        }
        .to_owned()
    }
}

impl FromStr for ObjectMapOpEnvType {
    type Err = BuckyError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let ret = match value {
            "path" => Self::Path,
            "single" => Self::Single,

            v @ _ => {
                let msg = format!("unknown op env type: {}", v);
                error!("{}", msg);

                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
            }
        };

        Ok(ret)
    }
}

#[derive(Clone, Debug, Copy)]
pub struct OpEnvSessionIDHelper;

// 最高位两位表示op_env的类型
const OP_ENV_PATH_FLAGS: u8 = 0b_00000000;
const OP_ENV_SINGLE_FLAGS: u8 = 0b_00000001;

impl OpEnvSessionIDHelper {
    pub fn get_flags(sid: u64) -> u8 {
        (sid >> 62) as u8
    }

    pub fn get_type(sid: u64) -> BuckyResult<ObjectMapOpEnvType> {
        let flags = Self::get_flags(sid);
        if flags == OP_ENV_PATH_FLAGS {
            Ok(ObjectMapOpEnvType::Path)
        } else if flags == OP_ENV_SINGLE_FLAGS {
            Ok(ObjectMapOpEnvType::Single)
        } else {
            let msg = format!("unknown op_ev sid flags: sid={}, flags={}", sid, flags);
            error!("{}", msg);
            Err(BuckyError::new(BuckyErrorCode::InvalidFormat, msg))
        }
    }

    pub fn set_type(sid: u64, op_env_type: ObjectMapOpEnvType) -> u64 {
        let flags = match op_env_type {
            ObjectMapOpEnvType::Path => OP_ENV_PATH_FLAGS,
            ObjectMapOpEnvType::Single => OP_ENV_SINGLE_FLAGS,
        };

        //assert!(Self::get_flags(sid) == 0);
        //println!("prev clear: {:#x}", sid);
        let sid = sid & 0b_00111111_11111111_11111111_11111111_11111111_11111111_11111111_11111111;
        //println!("after clear: {:#x}", sid);

        let sid = sid | ((flags as u64) << 62);
        //println!("after set: {:#x}", sid);

        sid
    }
}

#[cfg(test)]
mod test_sid {
    use super::OpEnvSessionIDHelper;
    use crate::*;

    #[test]
    fn test_sid() {
        let sid = 123;
        let t = OpEnvSessionIDHelper::get_type(sid).unwrap();
        assert_eq!(t, ObjectMapOpEnvType::Path);
        let sid = OpEnvSessionIDHelper::set_type(sid, ObjectMapOpEnvType::Single);
        let t = OpEnvSessionIDHelper::get_type(sid).unwrap();
        assert_eq!(t, ObjectMapOpEnvType::Single);

        let sid = OpEnvSessionIDHelper::set_type(sid, ObjectMapOpEnvType::Path);
        let t = OpEnvSessionIDHelper::get_type(sid).unwrap();
        assert_eq!(t, ObjectMapOpEnvType::Path);
    }
}

#[derive(Clone)]
pub enum ObjectMapOpEnv {
    Path(ObjectMapPathOpEnvRef),
    Single(ObjectMapSingleOpEnvRef),
}

impl ObjectMapOpEnv {
    pub fn sid(&self) -> u64 {
        match self {
            Self::Path(value) => value.sid(),
            Self::Single(value) => value.sid(),
        }
    }

    pub fn path_op_env(&self, sid: u64) -> BuckyResult<ObjectMapPathOpEnvRef> {
        match self {
            Self::Path(value) => Ok(value.clone()),
            _ => {
                let msg = format!(
                    "unmatch env type, path_op_env expected, got single_op_env! sid={}",
                    sid
                );
                error!("{}", msg);
                Err(BuckyError::new(BuckyErrorCode::Unmatch, msg))
            }
        }
    }

    pub fn single_op_env(&self, sid: u64) -> BuckyResult<ObjectMapSingleOpEnvRef> {
        match self {
            Self::Single(value) => Ok(value.clone()),
            _ => {
                let msg = format!(
                    "unmatch env type, single_op_env expected, got path_op_env! sid={}",
                    sid
                );
                error!("{}", msg);
                Err(BuckyError::new(BuckyErrorCode::Unmatch, msg))
            }
        }
    }

    pub async fn get_current_root(&self) -> BuckyResult<ObjectId> {
        match self {
            ObjectMapOpEnv::Path(env) => Ok(env.root()),
            ObjectMapOpEnv::Single(env) => match env.get_current_root().await {
                Some(root) => Ok(root),
                None => {
                    let msg = format!("single op_env root not been init yet! sid={}", env.sid());
                    error!("{}", msg);
                    Err(BuckyError::new(BuckyErrorCode::ErrorState, msg))
                }
            },
        }
    }

    pub async fn update(&self) -> BuckyResult<ObjectId> {
        match self {
            ObjectMapOpEnv::Path(env) => env.update().await,
            ObjectMapOpEnv::Single(env) => env.update().await,
        }
    }

    pub async fn commit(self) -> BuckyResult<ObjectId> {
        match self {
            ObjectMapOpEnv::Path(env) => env.commit().await,
            ObjectMapOpEnv::Single(env) => env.commit().await,
        }
    }

    pub fn abort(self) -> BuckyResult<()> {
        match self {
            ObjectMapOpEnv::Path(env) => env.abort(),
            ObjectMapOpEnv::Single(env) => env.abort(),
        }
    }

    pub fn is_dropable(&self) -> bool {
        match self {
            ObjectMapOpEnv::Path(env) => env.is_dropable(),
            ObjectMapOpEnv::Single(env) => env.is_dropable(),
        }
    }
}

use std::collections::HashMap;

struct ObjectMapOpEnvHolder {
    last_access: u64,
    op_env: ObjectMapOpEnv,
}

const OP_ENV_EXPIRED_DURATION: u64 = 1000 * 1000 * 60 * 60;

impl ObjectMapOpEnvHolder {
    fn new(op_env: ObjectMapOpEnv) -> Self {
        Self {
            last_access: bucky_time_now(),
            op_env,
        }
    }

    fn op_env(&self) -> &ObjectMapOpEnv {
        &self.op_env
    }

    fn into_op_env(self) -> ObjectMapOpEnv {
        self.op_env
    }

    fn is_gc_able(&self, now: u64) -> bool {
        if self.op_env.is_dropable() {
            if now - self.last_access > OP_ENV_EXPIRED_DURATION {
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    fn touch(&mut self) {
        self.last_access = bucky_time_now();
    }
}


#[derive(Clone)]
pub struct ObjectMapOpEnvContainer {
    all: Arc<Mutex<HashMap<u64, ObjectMapOpEnvHolder>>>,
}

impl ObjectMapOpEnvContainer {
    pub(crate) fn new() -> Self {
        let ret = Self {
            all: Arc::new(Mutex::new(HashMap::new())),
        };

        // 自动启动定期gc
        ret.start_monitor();

        ret
    }

    pub fn start_monitor(&self) {
        let this = self.clone();
        async_std::task::spawn(async move {
            loop {
                async_std::task::sleep(std::time::Duration::from_secs(60)).await;
                this.gc_once();
            }
        });
    }

    fn gc_once(&self) {
        let mut expired_list = vec![];
        let now = bucky_time_now();
        self.all.lock().unwrap().retain(|sid, op_env| {
            if op_env.is_gc_able(now) {
                expired_list.push((*sid, op_env.op_env().to_owned()));
                false
            } else {
                true
            }
        });

        self.gc_list(expired_list);
    }

    // 回收超时的op_env列表
    fn gc_list(&self, expired_list: Vec<(u64, ObjectMapOpEnv)>) {
        for (sid, op_env) in expired_list {
            warn!("will gc managed op_env on timeout: sid={}", sid);
            if let Err(e) = op_env.abort() {
                error!("op_env abort error! sid={}, {}", sid, e);
            }
        }
    }

    pub fn add_env(&self, env: ObjectMapOpEnv) {
        let sid = env.sid();
        let holder = ObjectMapOpEnvHolder::new(env);
        let prev = self.all.lock().unwrap().insert(sid, holder);
        assert!(prev.is_none());
    }

    pub fn get_op_env(&self, sid: u64) -> BuckyResult<ObjectMapOpEnv> {
        let mut list = self.all.lock().unwrap();
        let ret = list.get_mut(&sid);
        match ret {
            Some(value) => {
                value.touch();
                Ok(value.op_env().to_owned())
            }
            None => {
                let msg = format!("op_env not found! sid={}", sid);
                error!("{}", msg);
                Err(BuckyError::new(BuckyErrorCode::NotFound, msg))
            }
        }
    }

    pub fn get_path_op_env(&self, sid: u64) -> BuckyResult<ObjectMapPathOpEnvRef> {
        let op_env = self.get_op_env(sid)?;
        op_env.path_op_env(sid)
    }

    pub fn get_single_op_env(&self, sid: u64) -> BuckyResult<ObjectMapSingleOpEnvRef> {
        let op_env = self.get_op_env(sid)?;
        op_env.single_op_env(sid)
    }

    pub async fn get_current_root(&self, sid: u64) -> BuckyResult<ObjectId> {
        let op_env = self.get_op_env(sid)?;

        op_env.get_current_root().await
    }

    pub async fn update(&self, sid: u64) -> BuckyResult<ObjectId> {
        let op_env = self.get_op_env(sid)?;

        op_env.update().await
    }

    pub async fn commit(&self, sid: u64) -> BuckyResult<ObjectId> {
        let ret = self.all.lock().unwrap().remove(&sid);
        if ret.is_none() {
            let msg = format!("op_env not found! sid={}", sid);
            error!("{}", msg);
            return Err(BuckyError::new(BuckyErrorCode::NotFound, msg));
        }

        ret.unwrap().into_op_env().commit().await
    }

    pub fn abort(&self, sid: u64) -> BuckyResult<()> {
        let ret = self.all.lock().unwrap().remove(&sid);
        if ret.is_none() {
            let msg = format!("op_env not found! sid={}", sid);
            error!("{}", msg);
            return Err(BuckyError::new(BuckyErrorCode::NotFound, msg));
        }

        ret.unwrap().into_op_env().abort()
    }
}

// 用来管理root的管理器
pub struct ObjectMapRootManager {
    // ObjectMap的核心属性
    owner: Option<ObjectId>,
    dec_id: Option<ObjectId>,

    // 为每个op_env分配唯一的sid
    next_sid: AtomicU64,

    // 所属的root
    root: ObjectMapRootHolder,

    // 一个root所有env共享一个锁管理器
    lock: ObjectMapPathLock,

    // root级别的cache
    cache: ObjectMapRootCacheRef,

    // 所有托管的env
    all_envs: ObjectMapOpEnvContainer,
}

impl ObjectMapRootManager {
    pub fn new(
        owner: Option<ObjectId>,
        dec_id: Option<ObjectId>,
        noc: ObjectMapNOCCacheRef,
        root: ObjectMapRootHolder,
    ) -> Self {
        let lock = ObjectMapPathLock::new();
        let cache = ObjectMapRootMemoryCache::new_ref(noc, 60 * 5, 1024);
        Self {
            owner,
            dec_id,
            next_sid: AtomicU64::new(1),
            root,
            lock,
            cache,
            all_envs: ObjectMapOpEnvContainer::new(),
        }
    }

    fn next_sid(&self, op_env_type: ObjectMapOpEnvType) -> u64 {
        let sid = self
            .next_sid
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        // 设置类型
        OpEnvSessionIDHelper::set_type(sid, op_env_type)
    }

    pub fn get_current_root(&self) -> ObjectId {
        self.root.get_current_root()
    }

    pub fn root_holder(&self) -> &ObjectMapRootHolder {
        &self.root
    }

    pub fn root_cache(&self) -> &ObjectMapRootCacheRef {
        &self.cache
    }

    pub fn managed_envs(&self) -> &ObjectMapOpEnvContainer {
        &self.all_envs
    }

    pub async fn create_op_env(&self) -> BuckyResult<ObjectMapPathOpEnvRef> {
        let sid = self.next_sid(ObjectMapOpEnvType::Path);
        let env = ObjectMapPathOpEnv::new(sid, &self.root, &self.lock, &self.cache).await;
        let env = ObjectMapPathOpEnvRef::new(env);

        Ok(env)
    }

    pub async fn create_managed_op_env(&self) -> BuckyResult<ObjectMapPathOpEnvRef> {
        let env = self.create_op_env().await?;

        self.all_envs.add_env(ObjectMapOpEnv::Path(env.clone()));

        Ok(env)
    }

    pub fn create_single_op_env(&self) -> BuckyResult<ObjectMapSingleOpEnvRef> {
        let sid = self.next_sid(ObjectMapOpEnvType::Single);
        let env = ObjectMapSingleOpEnv::new(
            sid,
            &self.root,
            &self.cache,
            self.owner.clone(),
            self.dec_id.clone(),
        );
        let env = ObjectMapSingleOpEnvRef::new(env);

        Ok(env)
    }

    pub fn create_managed_single_op_env(&self) -> BuckyResult<ObjectMapSingleOpEnvRef> {
        let env = self.create_single_op_env()?;
        self.all_envs.add_env(ObjectMapOpEnv::Single(env.clone()));

        Ok(env)
    }
}

pub type ObjectMapRootManagerRef = Arc<ObjectMapRootManager>;

mod test_root {
    use crate::*;
    use std::future::Future;

    async fn update_root<F, Fut>(update_root_fn: F) -> BuckyResult<()>
    where
        F: FnOnce(i32, i32) -> Fut,
        Fut: Future<Output = BuckyResult<i32>>,
    {
        info!("begin exec update fn...");
        let result = update_root_fn(1, 2).await?;
        info!("end exec update fn: {}", result);

        assert_eq!(result, 3);
        Ok(())
    }

    #[test]
    fn test_fn() {
        crate::init_simple_log("test-root-fn", Some("debug"));

        let update = |first: i32, second: i32| async move {
            info!("will exec add: {} + {}", first, second);
            Ok(first + second)
        };

        async_std::task::block_on(async move {
            update_root(update).await.unwrap();
        });
    }
}