block-db 0.2.0

Local, multi-threaded, durable byte DB.
Documentation
// Authors: Robert Lopez
#![allow(clippy::suspicious_open_options)]
pub mod clear;
pub mod compact;
pub mod data_block;
pub mod delete;
pub mod free;
pub mod read;
pub mod recover;
pub mod size;
pub mod util;
pub mod wal;
pub mod write;

use super::{error::Error, options::store::OptionsStore, util::fs::create_directory};
use data_block::DataBlock;
use std::{
    collections::{HashMap, VecDeque},
    io::SeekFrom,
    path::PathBuf,
    sync::Arc,
};
use tokio::{
    fs::{File, OpenOptions},
    io::AsyncSeekExt,
};
use wal::{DataFileState, DataFileWAL};

#[derive(Debug)]
pub struct DataFile {
    pub id: String,
    pub wal: DataFileWAL,
    pub file: File,
    pub path: PathBuf,
    pub size: usize,
    pub directory: PathBuf,
    pub free_bytes: usize,
    pub used_bytes: usize,
    pub data_blocks: HashMap<String, DataBlock>,
    pub options_store: Arc<OptionsStore>,
    pub free_chunk_offsets: VecDeque<usize>,
}

impl DataFile {
    pub async fn open(
        id: String,
        directory: PathBuf,
        options_store: Arc<OptionsStore>,
    ) -> Result<Self, Error> {
        create_directory(&directory).await?;

        let path = directory.join("df");
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .open(&path)
            .await?;

        file.seek(SeekFrom::Start(0)).await?;

        let mut wal = DataFileWAL::open(directory.join("wal")).await?;
        let DataFileState {
            used_bytes,
            free_bytes,
            data_blocks,
            free_chunk_offsets,
        } = wal.replay(Some(options_store.clone())).await?;

        Ok(Self {
            id,
            wal,
            file,
            path,
            size: used_bytes + free_bytes,
            directory,
            free_bytes,
            used_bytes,
            data_blocks,
            options_store,
            free_chunk_offsets,
        })
    }
}