jdb_idx 0.1.1

High-performance SSTable index engine / 高性能 SSTable 索引引擎
Documentation
//! SST file writer / SST 文件写入器

use std::path::Path;

use bytes::Bytes;
use jdb_alloc::AlignedBuf;
use jdb_fs::File;
use jdb_proto::ValPtr;

use crate::{
  BlockBuilder, Error, Footer, IndexBuilder, Result,
  layout::{BLOCK_SIZE, FOOTER_SIZE},
};

/// SST file writer / SST 文件写入器
pub struct SstWriter {
  file: File,
  block: BlockBuilder,
  index: IndexBuilder,
  offset: u64,
  num_entries: u64,
  first_key: Option<Bytes>,
}

impl SstWriter {
  pub async fn create(path: impl AsRef<Path>) -> Result<Self> {
    Ok(Self {
      file: File::create(path).await?,
      block: BlockBuilder::new(),
      index: IndexBuilder::new(),
      offset: 0,
      num_entries: 0,
      first_key: None,
    })
  }

  /// Add key-ptr pair (must be sorted) / 添加 key-ptr 对(必须有序)
  pub async fn add(&mut self, key: &[u8], ptr: &ValPtr) -> Result<()> {
    if self.first_key.is_none() {
      self.first_key = Some(Bytes::copy_from_slice(key));
    }

    // Try adding to current block
    if self.block.add(key, ptr)? {
      self.num_entries += 1;
      return Ok(());
    }

    // Block full, flush and start new block
    self.flush_block().await?;
    self.first_key = Some(Bytes::copy_from_slice(key));

    // Retry adding to the fresh block
    if !self.block.add(key, ptr)? {
      return Err(Error::KeyTooLarge(key.len()));
    }

    self.num_entries += 1;
    Ok(())
  }

  async fn flush_block(&mut self) -> Result<()> {
    if self.block.is_empty() {
      return Ok(());
    }

    if let Some(key) = self.first_key.take() {
      self.index.add(key)?;
    }

    // Finalize current block (pads with 0)
    let data = self.block.finalize();

    // Copy to AlignedBuf for Direct I/O
    let mut buf = AlignedBuf::page()?;
    buf.clear();
    buf.extend(data)?;

    // Reset block builder for next use (keeps capacity)
    self.block.reset();

    self.file.write_at(buf, self.offset).await?;
    self.offset += BLOCK_SIZE as u64;

    Ok(())
  }

  /// Finish writing SST / 完成 SST 写入
  pub async fn finish(mut self) -> Result<Footer> {
    self.flush_block().await?;

    if self.index.is_empty() {
      return Err(Error::EmptySst);
    }

    let num_blocks = self.index.len() as u64;
    let index_offset = self.offset;
    let index_data = self.index.finish()?;
    let index_len = index_data.len() as u64;

    // Write index pages / 写入索引页
    let mut pos = 0;
    while pos < index_data.len() {
      let n = (index_data.len() - pos).min(BLOCK_SIZE);

      // Performance: full page uses with_cap, partial page uses zeroed for padding
      let mut buf = if n == BLOCK_SIZE {
        AlignedBuf::with_cap(BLOCK_SIZE)?
      } else {
        AlignedBuf::zeroed(BLOCK_SIZE)?
      };

      buf[..n].copy_from_slice(&index_data[pos..pos + n]);

      self.file.write_at(buf, self.offset).await?;
      self.offset += BLOCK_SIZE as u64;
      pos += BLOCK_SIZE;
    }

    // Write footer / 写入 Footer
    let footer = Footer::new(index_offset, index_len, num_blocks, self.num_entries);

    // Use zeroed buffer to ensure clean padding
    let mut buf = AlignedBuf::zeroed(BLOCK_SIZE)?;
    footer.encode(&mut buf[BLOCK_SIZE - FOOTER_SIZE..]);

    self.file.write_at(buf, self.offset).await?;
    self.file.sync_all().await?;

    Ok(footer)
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn writer_basic() {
    compio::runtime::Runtime::new().unwrap().block_on(async {
      let path = "/tmp/test_sst_writer.sst";
      std::fs::remove_file(path).ok();

      let mut writer = SstWriter::create(path).await.unwrap();

      for i in 0u32..100 {
        let key = format!("key{i:05}");
        let ptr = ValPtr::new(1, i as u64 * 100, 50);
        writer.add(key.as_bytes(), &ptr).await.unwrap();
      }

      let footer = writer.finish().await.unwrap();

      assert_eq!(footer.num_entries, 100);
      assert!(footer.num_blocks > 0);

      std::fs::remove_file(path).ok();
    });
  }

  #[test]
  fn writer_key_too_large() {
    compio::runtime::Runtime::new().unwrap().block_on(async {
      let path = "/tmp/test_sst_writer_large_key.sst";
      std::fs::remove_file(path).ok();

      let mut writer = SstWriter::create(path).await.unwrap();
      let key = vec![0u8; 5000]; // > 4KB
      let ptr = ValPtr::new(1, 0, 100);

      let result = writer.add(&key, &ptr).await;
      assert!(matches!(result, Err(Error::KeyTooLarge(_))));

      std::fs::remove_file(path).ok();
    });
  }
}