dorea 0.4.0

A key-value storage system
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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
use std::fs::{self, rename};
use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::{collections::HashMap, path::PathBuf};

use log::info;
use nom::AsBytes;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};

use bytes::{BufMut, BytesMut};
use dashmap::DashMap;
use serde_json::json;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::sync::{Mutex, RwLock};

use crate::configure::{self, DataBaseConfig, DoreaFileConfig};
use crate::value::DataValue;
use crate::Result;

use anyhow::anyhow;

// 单个数据库占全系统可用
const INDEX_PROPORTION_FOR_DB: u16 = 4;

// 全局索引计数(原子操作,替代原来的 Mutex<TotalInfo>)
static TOTAL_INDEX_NUMBER: AtomicU32 = AtomicU32::new(0);
static MAX_INDEX_NUMBER: AtomicU32 = AtomicU32::new(u32::MAX);

/// 数据管理结构
/// db_list 数据库列表(当前系统已加载的所有数据)
/// location 数据加载位置
/// config 数据库配置
#[derive(Debug)]
pub struct DataBaseManager {
    pub(crate) db_list: DashMap<String, Arc<RwLock<DataBase>>>,
    pub(crate) location: PathBuf,
    pub(crate) config: DoreaFileConfig,
    pub(crate) eli_queue: Mutex<HashMap<String, isize>>,
}

#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct DataBase {
    name: String,
    index: HashMap<String, IndexInfo>,
    timestamp: i64,
    location: PathBuf,
    file: DataFile,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DataNode {
    crc: u32,
    key: String,
    pub(crate) value: DataValue,
    time_stamp: (i64, u64),
}

pub static DB_STATE: Lazy<Mutex<HashMap<String, DataBaseState>>> =
    Lazy::new(|| Mutex::new(HashMap::new()));

#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DataBaseState {
    NORMAL,
    LOCKED,
    LOADING,
    UNLOAD,
}

impl std::fmt::Display for DataBaseState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            DataBaseState::NORMAL => write!(f, "Normal"),
            DataBaseState::LOCKED => write!(f, "Locked"),
            DataBaseState::LOADING => write!(f, "Loading"),
            DataBaseState::UNLOAD => write!(f, "Unload"),
        }
    }
}

pub const CASTAGNOLI: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISCSI);

impl DataBaseManager {
    pub async fn new(location: PathBuf) -> Self {
        let config = configure::load_config(&location).unwrap();

        MAX_INDEX_NUMBER.store(config.database.max_index_number, Ordering::Relaxed);

        let (db_list, eli_que) = DataBaseManager::load_database(&config, location.clone()).await;

        Self {
            db_list,
            location: location.clone(),
            config,
            eli_queue: Mutex::new(eli_que),
        }
    }

    /// 确保指定数据库已加载
    pub async fn ensure_loaded(&self, name: &str, db_config: &DataBaseConfig) {
        if self.db_list.contains_key(name) {
            return;
        }

        let state = DataBase::state(name.to_string(), self.location.clone())
            .await
            .unwrap_or(StateInfo {
                index_number: 0,
                init_version: crate::DOREA_VERSION.to_string(),
                update_time: chrono::Local::now().timestamp(),
            });

        if self.check_eli_db(state.index_number as u64).await.is_err() {
            log::error!("eviction check failed when loading database '{}'", name);
        }

        let db = DataBase::init(
            name.to_string(),
            self.location.clone().join("storage"),
            db_config.clone(),
        )
        .await;

        self.db_list
            .insert(name.to_string(), Arc::new(RwLock::new(db)));
        self.eli_queue
            .lock()
            .await
            .insert(name.to_string(), 1);
    }

    // 切换数据库
    pub async fn select_to(&self, name: &str) -> Result<()> {
        if self.db_list.contains_key(name) {
            return Ok(());
        }

        let state = DataBase::state(name.to_string(), self.location.clone())
            .await
            .unwrap_or(StateInfo {
                index_number: 0,
                init_version: crate::DOREA_VERSION.to_string(),
                update_time: chrono::Local::now().timestamp(),
            });

        self.check_eli_db(state.index_number as u64).await?;

        let db = DataBase::init(
            name.to_string(),
            self.location.clone().join("storage"),
            self.config.database.clone(),
        )
        .await;

        self.db_list
            .insert(name.to_string(), Arc::new(RwLock::new(db)));
        self.eli_queue
            .lock()
            .await
            .insert(name.to_string(), 2);

        Ok(())
    }

    pub async fn load_from(&self, name: &str, db: Arc<RwLock<DataBase>>) -> Result<()> {
        let db_size = db.read().await.size() as u64;
        self.check_eli_db(db_size).await?;

        self.db_list.insert(name.to_string(), db);
        self.eli_queue
            .lock()
            .await
            .insert(name.to_string(), 1);

        Ok(())
    }

    // 预加载所需要的数据库数据
    async fn load_database(
        config: &DoreaFileConfig,
        location: PathBuf,
    ) -> (DashMap<String, Arc<RwLock<DataBase>>>, HashMap<String, isize>) {
        let config = config.clone();

        let db_list = DashMap::new();
        let mut eli_que = HashMap::new();

        let groups = &config.database.pre_load_group;

        for db in groups {
            db_list.insert(
                db.to_string(),
                Arc::new(RwLock::new(
                    DataBase::init(
                        db.to_string(),
                        location.clone().join("storage"),
                        config.database.clone(),
                    )
                    .await,
                )),
            );
            eli_que.insert(db.to_string(), 2);
        }

        let total = TOTAL_INDEX_NUMBER.load(Ordering::Relaxed);
        let max = MAX_INDEX_NUMBER.load(Ordering::Relaxed);
        info!("total index loaded number: {} [MAX: {}].", total, max);

        (db_list, eli_que)
    }

    pub async fn add_weight(&self, db: String, num: isize) -> bool {
        let mut eli = self.eli_queue.lock().await;
        if eli.contains_key(&db) {
            let old = match eli.get(&db) {
                None => return false,
                Some(v) => *v,
            };
            eli.insert(db.to_string(), old + num);

            log::debug!("[{}] weight update to {}.", db, old + num);

            return true;
        }

        false
    }

    pub async fn unload_database(&self, db: String) -> crate::Result<()> {
        let db_index_size = match self.db_list.get(&db) {
            Some(v) => {
                let db_guard = v.read().await;
                db_guard.save_state_json().await?;
                db_guard.size() as u32
            }
            None => 0,
        };

        TOTAL_INDEX_NUMBER.fetch_sub(db_index_size, Ordering::Relaxed);
        self.db_list.remove(&db);
        self.eli_queue.lock().await.remove(&db);

        Ok(())
    }

    pub async fn check_eli_db(&self, need: u64) -> crate::Result<()> {
        let total_index_number = TOTAL_INDEX_NUMBER.load(Ordering::Relaxed);
        let max_index_number = MAX_INDEX_NUMBER.load(Ordering::Relaxed);

        if (total_index_number + need as u32) >= max_index_number {
            let group_max_index_number = (max_index_number / 4) as usize;

            let mut minimum = (String::new(), u64::MAX);

            let eli = self.eli_queue.lock().await;

            for entry in self.db_list.iter() {
                let name = entry.key();
                let num = match eli.get(name) {
                    Some(v) => *v,
                    None => continue,
                };

                let db_guard = entry.value().read().await;
                let db_index_number = db_guard.size() as u64;

                if db_index_number < need {
                    continue;
                }

                if crate::server::db_stat_exist(name.to_string()).await {
                    continue;
                }

                if *DB_STATE
                    .lock()
                    .await
                    .get(name)
                    .unwrap_or(&DataBaseState::NORMAL)
                    == DataBaseState::LOCKED
                {
                    continue;
                }

                let final_weight = num as u64 * (group_max_index_number as u64 / db_index_number);

                if minimum.1 > final_weight {
                    minimum = (name.to_string(), final_weight);
                }
            }

            drop(eli);

            if minimum.1 != u64::MAX {
                log::info!(
                    "weight judge: @{}[:{}] will be eliminate.",
                    minimum.0,
                    minimum.1
                );
                self.unload_database(minimum.0.to_string()).await?;
            } else {
                log::error!("no database can be eliminate.");
                return Err(anyhow!("no database can be eliminate."));
            }
        }
        Ok(())
    }
}

#[allow(dead_code)]
#[derive(Deserialize, Clone, Debug)]
pub struct StateInfo {
    pub(crate) index_number: usize,
    pub(crate) init_version: String,
    pub(crate) update_time: i64,
}

#[allow(dead_code)]
impl DataBase {
    pub async fn state(name: String, location: PathBuf) -> crate::Result<StateInfo> {
        let location = location.join("storage").join(&name);

        let v = fs::read_to_string(location.join("state.json"))?;
        let s = serde_json::from_str::<StateInfo>(&v)?;

        Ok(s)
    }

    pub async fn init(name: String, location: PathBuf, _config: DataBaseConfig) -> Self {
        let location = location.join(&name);

        let data_file = DataFile::new(&location, name.clone());

        let mut index_list = HashMap::new();

        let _ = data_file.load_index(&mut index_list).await;

        let obj = Self {
            name: name.clone(),
            index: index_list,
            timestamp: chrono::Local::now().timestamp(),
            file: data_file,
            location,
        };

        let _ = obj.save_state_json().await;

        obj
    }

    pub async fn save_state_json(&self) -> crate::Result<()> {
        let path = self.location.clone();

        fs::write(
            path.join("state.json"),
            serde_json::json!({
                "index_number": self.size(),
                "init_version": crate::DOREA_VERSION,
                "update_time": chrono::Local::now().timestamp(),
            })
            .to_string()
            .as_bytes(),
        )?;

        Ok(())
    }

    pub async fn set(&mut self, key: &str, value: DataValue, expire: u64) -> Result<()> {
        if !self.contains_key(key).await && value != DataValue::None {
            let max_index_number = MAX_INDEX_NUMBER.load(Ordering::Relaxed);

            if TOTAL_INDEX_NUMBER.load(Ordering::Relaxed) >= max_index_number {
                return Err(anyhow!("exceeded system max index number"));
            }

            if (self.index.len() as u32) >= (max_index_number / (INDEX_PROPORTION_FOR_DB as u32)) {
                return Err(anyhow!("exceeded group max index number"));
            }
        }

        let mut crc_digest = CASTAGNOLI.digest();
        crc_digest.update(value.to_string().as_bytes());

        let data_node = DataNode {
            crc: crc_digest.finalize(),
            key: key.to_string(),
            value: value.clone(),
            time_stamp: (chrono::Local::now().timestamp(), expire),
        };

        self.file.write(data_node, &mut self.index).await
    }

    pub async fn get(&self, key: &str) -> Option<DataValue> {
        let res = self.file.read(key.to_string(), &self.index).await;
        match res {
            Some(d) => {
                if d.time_stamp.1 != 0
                    && (d.time_stamp.0 as u64 + d.time_stamp.1)
                        < chrono::Local::now().timestamp() as u64
                {
                    return Some(DataValue::None);
                }

                Some(d.value)
            }
            None => None,
        }
    }

    pub async fn meta_data(&self, key: &str) -> Option<DataNode> {
        self.file.read(key.to_string(), &self.index).await
    }

    pub async fn delete(&mut self, key: &str) -> Result<()> {
        return match self.set(key, DataValue::None, 0).await {
            Ok(_) => {
                TOTAL_INDEX_NUMBER.fetch_sub(1, Ordering::Relaxed);
                self.index.remove(key);
                Ok(())
            }
            Err(e) => Err(e),
        };
    }

    pub async fn contains_key(&self, key: &str) -> bool {
        self.index.contains_key(key)
    }

    pub async fn clean(&mut self) -> Result<()> {
        TOTAL_INDEX_NUMBER.fetch_sub(self.index.len() as u32, Ordering::Relaxed);
        for entry in walkdir::WalkDir::new(&self.location)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            if entry.path().is_file() {
                fs::remove_file(entry.path())?;
            }
        }

        self.index = HashMap::new();

        self.file.init_db()?;

        info!("@{} group has been clean.", self.name);

        Ok(())
    }

    pub async fn keys(&self) -> Vec<String> {
        let mut temp = vec![];
        for i in self.index.keys() {
            temp.push(i.to_string());
        }

        temp
    }

    pub fn record_count(&self) -> usize {
        self.file.record_count()
    }

    pub fn size(&self) -> usize {
        self.index.len()
    }

    pub async fn merge(&mut self) -> crate::Result<()> {
        self.file.merge_struct(&mut self.index).await
    }
}

impl DataNode {
    pub(crate) fn timestamp(&self) -> (i64, u64) {
        self.time_stamp
    }
    pub(crate) fn weight(self) -> f64 {
        self.value.weight()
    }
}

#[derive(Debug, Clone)]
struct DataFile {
    root: PathBuf,
    name: String,
}

impl DataFile {
    pub fn new(root: &Path, name: String) -> Self {
        let mut db = Self {
            root: root.to_path_buf(),
            name,
        };

        db.init_db().unwrap();

        db
    }

    pub async fn load_index(&self, index: &mut HashMap<String, IndexInfo>) -> crate::Result<()> {
        if !self.root.is_dir() {
            return Err(anyhow!("root dir not found"));
        }

        let mut count = 0;

        for entry in walkdir::WalkDir::new(&self.root)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            if entry.path().is_file() {
                let file_name = entry.path().file_name().unwrap().to_str().unwrap();

                let info: nom::IResult<&str, &str> = nom::sequence::delimited(
                    nom::bytes::complete::tag("archive-"),
                    nom::character::complete::digit1,
                    nom::bytes::complete::tag(".db"),
                )(file_name);

                if info.is_ok() || file_name == "active.db" {
                    let file_id = if file_name == "active.db" {
                        self.get_file_id()
                    } else {
                        info.as_ref().unwrap().1.parse::<u32>().unwrap()
                    };

                    let mut file = match OpenOptions::new().read(true).open(entry.path()) {
                        Ok(v) => v,
                        Err(_) => {
                            continue;
                        }
                    };

                    let file_size = file.metadata().unwrap().len();
                    let file_size = file_size - 34;
                    let mut readed_size = 0;

                    file.seek(SeekFrom::Start(34))?;

                    let mut legacy: Vec<u8> = vec![];
                    let mut position: (u64, u64) = (34, 34);
                    let mut buf = [0_u8; 1024];

                    while readed_size < file_size {
                        let v = file.read(&mut buf)?;
                        let mut bs = bytes::BytesMut::with_capacity(v);

                        bs.put(&buf[0..v]);

                        let mut slice_symbol: bool = false;

                        for rec in 0..bs.len() {
                            if bs[rec] == b'\r' {
                                if rec == (bs.len() - 1) {
                                    let mut read_one = [0_u8; 1];
                                    match file.read(&mut read_one) {
                                        Ok(_amount) => {
                                            readed_size += 1;

                                            if read_one[0] != b'\n' {
                                                legacy.push(bs[rec]);
                                                position.1 += 1;

                                                continue;
                                            }
                                        }
                                        Err(e) => {
                                            panic!("{}", e.to_string());
                                        }
                                    };
                                } else if bs[rec + 1] != b'\n' {
                                    legacy.push(bs[rec]);
                                    position.1 += 1;
                                    continue;
                                }

                                let v = match serde_json::from_slice::<DataNode>(&legacy[..]) {
                                    Ok(v) => v,
                                    Err(_) => break,
                                };

                                let info = IndexInfo {
                                    file_id,
                                    start_position: position.0,
                                    end_position: position.1,
                                    time_stamp: v.time_stamp,
                                };

                                if v.value != DataValue::None {
                                    if !index.contains_key(&v.key) {
                                        count += 1;
                                    }
                                    index.insert(v.key.clone(), info);
                                } else if index.contains_key(&v.key) {
                                    index.remove(&v.key);
                                    count -= 1;
                                }

                                slice_symbol = true;
                                position = (position.1 + 2, position.1 + 2);

                                legacy.clear();
                            } else if slice_symbol && bs[rec] == b'\n' {
                                slice_symbol = false;
                            } else {
                                legacy.push(bs[rec]);
                                position.1 += 1;
                            }
                        }

                        readed_size += v as u64;
                    }
                }
            }
        }

        info!(
            "index information loaded from {:?} [{}].",
            self.root.file_name().unwrap(),
            count,
        );
        TOTAL_INDEX_NUMBER.fetch_add(count, Ordering::Relaxed);

        Ok(())
    }

    fn init_db(&mut self) -> crate::Result<()> {
        if self.check_db().is_err() {
            if !self.root.is_dir() {
                fs::create_dir_all(&self.root)?;
            }

            let save_file = self.root.join("active.db");

            if !save_file.is_file() {
                self.active()?;
            }

            let record_in = self.root.join("record.in");

            if !record_in.is_file() {
                fs::write(record_in, b"1")?;
            }

            let state_json = self.root.join("state.json");
            if !state_json.is_file() {
                fs::write(
                    state_json,
                    json!({
                        "index_number": 0,
                        "init_version": crate::DOREA_VERSION,
                        "update_time": chrono::Local::now().timestamp(),
                    })
                    .to_string()
                    .as_bytes(),
                )?;
            }
        }

        Ok(())
    }

    fn rename_dfile(&mut self, new_name: &str) -> crate::Result<()> {
        let new_root = self.root.parent().unwrap().join(new_name);

        if new_root.is_dir() {
            fs::remove_dir_all(&new_root)?;
        }

        fs::rename(&self.root, &new_root)?;

        self.name = new_name.into();
        self.root = new_root;

        Ok(())
    }

    fn check_db(&self) -> crate::Result<()> {
        let mut result: crate::Result<()> = Ok(());

        if !self.root.is_dir() {
            result = Err(anyhow!("root dir not found"));
        }

        let save_file = self.root.join("active.db");
        let index_dir = self.root.join("record.in");

        if !save_file.is_file() || !index_dir.is_file() {
            result = Err(anyhow!("file not found"));
        }

        let mut file = fs::File::open(save_file)?;

        let mut buf = [0; 33];

        file.read_exact(&mut buf)?;

        if buf.get(buf.len() - 2).unwrap() == &b'\r' && buf.get(buf.len() - 2).unwrap() == &b'\n' {
            result = Err(anyhow!("version nonsupport"));
        }

        let check_code = String::from_utf8_lossy(&buf[0..buf.len() - 1]).to_string();

        if !crate::COMPATIBLE_VERSION.contains(&check_code) {
            panic!("database storage structure unsupported.");
        }

        result
    }

    pub async fn write(
        &self,
        data: DataNode,
        index: &mut HashMap<String, IndexInfo>,
    ) -> Result<()> {
        self.check_file().await?;

        let file = self.root.join("active.db");

        let mut v = serde_json::to_vec(&data).expect("serialize failed");

        v.push(13);
        v.push(10);

        let mut f = tokio::fs::OpenOptions::new()
            .append(true)
            .open(&file)
            .await?;

        let start_position = f.metadata().await?.len();

        f.write_all(&v[..]).await?;

        let end_position: u64 = start_position + v.len() as u64;
        let end_position: u64 = end_position - 2;

        let index_info = IndexInfo {
            file_id: self.get_file_id(),
            start_position,
            end_position,
            time_stamp: data.time_stamp,
        };

        if !index.contains_key(&data.key) {
            TOTAL_INDEX_NUMBER.fetch_add(1, Ordering::Relaxed);
        }

        index.insert(data.key.clone(), index_info);

        Ok(())
    }

    pub async fn read(&self, key: String, index: &HashMap<String, IndexInfo>) -> Option<DataNode> {
        match index.get(&key) {
            Some(v) => self.read_with_index_info(v).await,
            None => None,
        }
    }

    #[allow(clippy::slow_vector_initialization)]
    pub async fn read_with_index_info(&self, index_info: &IndexInfo) -> Option<DataNode> {
        let data_file = if index_info.file_id == self.get_file_id() {
            self.root.join("active.db")
        } else {
            self.root.join(format!("archive-{}.db", index_info.file_id))
        };

        if !data_file.is_file() {
            return None;
        }

        let mut file = tokio::fs::File::open(&data_file).await.ok()?;

        file.seek(SeekFrom::Start(index_info.start_position))
            .await
            .ok()?;

        let mut buf: Vec<u8> =
            Vec::with_capacity((index_info.end_position - index_info.start_position) as usize);

        buf.resize(
            (index_info.end_position - index_info.start_position) as usize,
            0,
        );

        let len = file.read(&mut buf).await.ok()?;

        let v = match serde_json::from_slice::<DataNode>(buf[0..len].as_bytes()) {
            Ok(v) => v,
            Err(_) => {
                return None;
            }
        };

        Some(v)
    }

    pub async fn check_file(&self) -> crate::Result<()> {
        let file = self.root.join("active.db");

        if !file.is_file() {
            self.active()?;
        }

        let size = tokio::fs::metadata(&file).await?.len();

        if size >= (1024 * 1024 * 64) {
            self.archive()?;
        }

        Ok(())
    }

    pub async fn merge_struct(
        &mut self,
        index: &mut HashMap<String, IndexInfo>,
    ) -> crate::Result<()> {
        let root_path = self.root.clone();

        let record = tokio::fs::read_to_string(root_path.join("record.in")).await?;
        let record = record.parse::<usize>()?;

        if record <= 3 {
            return Ok(());
        }

        let temp_dfile = root_path.parent().unwrap().join(format!("~{}", self.name));
        let mut temp_dfile = DataFile::new(&temp_dfile, format!("~{}", self.name));
        let mut temp_index = HashMap::new();

        for (_, index_info) in index.iter() {
            let val = self.read_with_index_info(index_info).await;
            temp_dfile
                .write(val.unwrap(), &mut temp_index)
                .await
                .unwrap();
        }

        *index = temp_index.clone();

        temp_dfile.rename_dfile(&self.name)?;

        log::info!("merge success: {}", self.name);

        Ok(())
    }

    fn active(&self) -> crate::Result<()> {
        let file = self.root.join("active.db");

        let mut content = BytesMut::new();

        let header_info = format!("Dorea::{}", crate::DOREA_VERSION);

        let digest = md5::compute(header_info.as_bytes());

        content.put(format!("{:x}", digest).as_bytes());

        content.put("\r\n".as_bytes());

        fs::write(&file, content)?;

        Ok(())
    }

    fn archive(&self) -> crate::Result<()> {
        let file = self.root.join("active.db");

        let count = self.get_file_id();

        rename(&file, self.root.join(format!("archive-{}.db", count)))?;

        let mut f = OpenOptions::new()
            .write(true)
            .open(self.root.join("record.in"))?;

        f.write_all((self.get_file_id() + 1).to_string().as_bytes())?;

        self.active()?;

        Ok(())
    }

    fn get_file_id(&self) -> u32 {
        let fp = self.root.join("record.in");

        let mut fp = OpenOptions::new().read(true).open(fp).unwrap();

        let mut num = String::new();

        fp.read_to_string(&mut num).unwrap();

        num.parse::<u32>().unwrap_or(1)
    }

    pub fn record_count(&self) -> usize {
        let fp = self.root.join("record.in");
        fs::read_to_string(fp)
            .ok()
            .and_then(|s| s.parse::<usize>().ok())
            .unwrap_or(1)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct IndexInfo {
    file_id: u32,
    start_position: u64,
    end_position: u64,
    time_stamp: (i64, u64),
}

pub async fn total_index_number() -> (u32, u32) {
    (
        TOTAL_INDEX_NUMBER.load(Ordering::Relaxed),
        MAX_INDEX_NUMBER.load(Ordering::Relaxed),
    )
}