From 9da170a1b25fa1614cafe5c5bcb47e4c89cc9abf Mon Sep 17 00:00:00 2001 From: dusk Date: Fri, 8 Aug 2025 22:59:09 +0300 Subject: [PATCH] feat(server): use snapshots for reading from handles to not block writes, updating every sync --- server/Cargo.lock | 7 +++++ server/Cargo.toml | 1 + server/src/db/handle.rs | 53 ++++++++++++++++++++++----------- server/src/db/mod.rs | 57 ++++++++++++++++++++++------------- server/src/utils.rs | 66 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 37 deletions(-) diff --git a/server/Cargo.lock b/server/Cargo.lock index 4999da2..4cbc541 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -47,6 +47,12 @@ version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" +[[package]] +name = "arc-swap" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" + [[package]] name = "async-compression" version = "0.4.25" @@ -1553,6 +1559,7 @@ name = "server" version = "0.1.0" dependencies = [ "anyhow", + "arc-swap", "async-trait", "axum", "axum-tws", diff --git a/server/Cargo.toml b/server/Cargo.toml index 5923d23..c563cb3 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -31,3 +31,4 @@ rayon = "1.10.0" parking_lot = { version = "0.12", features = ["send_guard", "hardware-lock-elision"] } rclite = "0.2.7" snmalloc-rs = "0.3.8" +arc-swap = "1.7.1" diff --git a/server/src/db/handle.rs b/server/src/db/handle.rs index f4ede64..b9496dc 100644 --- a/server/src/db/handle.rs +++ b/server/src/db/handle.rs @@ -1,13 +1,13 @@ use std::{ fmt::Debug, io::Cursor, - ops::{Bound, Deref, RangeBounds}, + ops::{Bound, RangeBounds}, sync::atomic::{AtomicU64, Ordering as AtomicOrdering}, time::Duration, }; use byteview::ByteView; -use fjall::{Keyspace, Partition, PartitionCreateOptions, Slice}; +use fjall::{Keyspace, Partition, PartitionCreateOptions, Slice, Snapshot}; use itertools::Itertools; use parking_lot::Mutex; use rayon::iter::{IntoParallelIterator, ParallelIterator}; @@ -16,8 +16,11 @@ use smol_str::SmolStr; use crate::{ db::{EventRecord, NsidHit, block}, - error::AppResult, - utils::{CLOCK, DefaultRateTracker, RateTracker, ReadVariableExt, varints_unsigned_encoded}, + error::{AppError, AppResult}, + utils::{ + ArcRefCnt, ArcliteSwap, CLOCK, DefaultRateTracker, RateTracker, ReadVariableExt, + varints_unsigned_encoded, + }, }; pub type ItemDecoder = block::ItemDecoder, NsidHit>; @@ -31,7 +34,8 @@ pub struct Block { } pub struct LexiconHandle { - tree: Partition, + write_tree: Partition, + read_tree: ArcliteSwap, nsid: SmolStr, buf: Arc>>, last_insert: AtomicU64, // relaxed @@ -46,21 +50,16 @@ impl Debug for LexiconHandle { } } -impl Deref for LexiconHandle { - type Target = Partition; - - fn deref(&self) -> &Self::Target { - &self.tree - } -} - impl LexiconHandle { pub fn new(keyspace: &Keyspace, nsid: &str) -> Self { let opts = PartitionCreateOptions::default() .block_size(1024 * 48) .compression(fjall::CompressionType::Miniz(9)); + let write_tree = keyspace.open_partition(nsid, opts).unwrap(); + let read_tree = ArcliteSwap::new(ArcRefCnt::new(write_tree.snapshot())); Self { - tree: keyspace.open_partition(nsid, opts).unwrap(), + write_tree, + read_tree, nsid: nsid.into(), buf: Default::default(), last_insert: AtomicU64::new(0), @@ -68,14 +67,28 @@ impl LexiconHandle { } } + #[inline(always)] + pub fn read(&self) -> arc_swap::Guard> { + self.read_tree.load() + } + + #[inline(always)] + pub fn update_tree(&self) { + self.read_tree + .store(ArcRefCnt::new(self.write_tree.snapshot())); + } + + #[inline(always)] pub fn span(&self) -> tracing::Span { tracing::info_span!("handle", nsid = %self.nsid) } + #[inline(always)] pub fn nsid(&self) -> &SmolStr { &self.nsid } + #[inline(always)] pub fn item_count(&self) -> usize { self.buf.lock().len() } @@ -122,7 +135,7 @@ impl LexiconHandle { let end_key = varints_unsigned_encoded([end_limit]); let blocks_to_compact = self - .tree + .read() .range(start_key..end_key) .collect::, _>>()?; if blocks_to_compact.len() < 2 { @@ -162,10 +175,10 @@ impl LexiconHandle { let end_blocks_size = new_blocks.len(); for key in keys_to_delete { - self.tree.remove(key.clone())?; + self.write_tree.remove(key.clone())?; } for block in new_blocks { - self.tree.insert(block.key, block.data)?; + self.write_tree.insert(block.key, block.data)?; } let reduction = @@ -181,6 +194,12 @@ impl LexiconHandle { Ok(()) } + pub fn insert_block(&self, block: Block) -> AppResult<()> { + self.write_tree + .insert(block.key, block.data) + .map_err(AppError::from) + } + pub fn encode_block_from_items( items: impl IntoIterator, count: usize, diff --git a/server/src/db/mod.rs b/server/src/db/mod.rs index 4977aac..b96a284 100644 --- a/server/src/db/mod.rs +++ b/server/src/db/mod.rs @@ -1,5 +1,5 @@ use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, fmt::Debug, io::Cursor, ops::{Bound, Deref, RangeBounds}, @@ -165,9 +165,11 @@ impl Db { pub fn sync(&self, all: bool) -> AppResult<()> { let start = CLOCK.now(); // prepare all the data - let mut data = Vec::with_capacity(self.hits.len()); + let nsids_len = self.hits.len(); + let mut data = Vec::with_capacity(nsids_len); + let mut nsids = HashSet::with_capacity(nsids_len); let _guard = scc::ebr::Guard::new(); - for (_, handle) in self.hits.iter(&_guard) { + for (nsid, handle) in self.hits.iter(&_guard) { let mut nsid_data = Vec::with_capacity(2); let mut total_count = 0; let is_too_old = handle.since_last_activity() > self.cfg.max_last_activity; @@ -201,6 +203,7 @@ impl Db { {blocks = %nsid_data.len(), count = %total_count}, "will encode & sync", ); + nsids.insert(nsid.clone()); data.push(nsid_data); } } @@ -228,9 +231,10 @@ impl Db { for (block, handle) in chunk { self.sync_pool.execute(move || { let _span = handle.span().entered(); - match handle.insert(block.key, block.data) { + let written = block.written; + match handle.insert_block(block) { Ok(_) => { - tracing::info!({count = %block.written}, "synced") + tracing::info!({count = %written}, "synced") } Err(err) => tracing::error!({ err = %err }, "failed to sync block"), } @@ -239,6 +243,12 @@ impl Db { AppResult::Ok(()) })?; self.sync_pool.join(); + + // update snapshots for all (changed) handles + for nsid in nsids { + self.hits.peek_with(&nsid, |_, handle| handle.update_tree()); + } + tracing::info!(time = %start.elapsed().as_secs_f64(), "synced all blocks"); Ok(()) @@ -254,7 +264,9 @@ impl Db { let Some(handle) = self.get_handle(nsid) else { return Ok(()); }; - handle.compact(max_count, range, sort) + handle.compact(max_count, range, sort)?; + handle.update_tree(); + Ok(()) } pub fn compact_all( @@ -363,14 +375,18 @@ impl Db { let Some(handle) = self.get_handle(&nsid) else { continue; }; - let block_lens = handle.iter().rev().try_fold(Vec::new(), |mut acc, item| { - let (key, value) = item?; - let mut timestamps = Cursor::new(key); - let start_timestamp = timestamps.read_varint()?; - let decoder = ItemDecoder::new(Cursor::new(value), start_timestamp)?; - acc.push(decoder.item_count()); - AppResult::Ok(acc) - })?; + let block_lens = handle + .read() + .iter() + .rev() + .try_fold(Vec::new(), |mut acc, item| { + let (key, value) = item?; + let mut timestamps = Cursor::new(key); + let start_timestamp = timestamps.read_varint()?; + let decoder = ItemDecoder::new(Cursor::new(value), start_timestamp)?; + acc.push(decoder.item_count()); + AppResult::Ok(acc) + })?; nsids.insert(nsid.to_smolstr(), block_lens); } Ok(DbInfo { @@ -438,7 +454,8 @@ impl Db { )) }; - let (blocks, counted) = handle + let (blocks, _counted) = handle + .read() .range(..end_key) .map(|res| res.map_err(AppError::from)) .rev() @@ -462,10 +479,10 @@ impl Db { ) .into_inner(); - tracing::info!( - "got blocks with size {}, item count {counted}", - blocks.len() - ); + // tracing::info!( + // "got blocks with size {}, item count {counted}", + // blocks.len() + // ); Either::Left(blocks.into_iter().rev().flatten().flatten()) } @@ -476,7 +493,7 @@ impl Db { let Some(handle) = self.get_handle("app.bsky.feed.like") else { return Ok(0); }; - let Some((timestamps_raw, _)) = handle.first_key_value()? else { + let Some((timestamps_raw, _)) = handle.read().first_key_value()? else { return Ok(0); }; let mut timestamp_reader = Cursor::new(timestamps_raw); diff --git a/server/src/utils.rs b/server/src/utils.rs index 0273d87..628408d 100644 --- a/server/src/utils.rs +++ b/server/src/utils.rs @@ -1,9 +1,12 @@ use std::io::{self, Read, Write}; +use std::ops::Deref; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; +use arc_swap::RefCnt; use byteview::ByteView; use ordered_varint::Variable; +use rclite::Arc; pub fn get_time() -> Duration { std::time::SystemTime::now() @@ -320,3 +323,66 @@ impl std::fmt::Display for RelativeDateTime { } } } + +pub type ArcliteSwap = arc_swap::ArcSwapAny>; + +pub struct ArcRefCnt(Arc); + +impl ArcRefCnt { + pub fn new(value: T) -> Self { + Self(Arc::new(value)) + } +} + +impl Deref for ArcRefCnt { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Clone for ArcRefCnt { + fn clone(&self) -> Self { + Self(self.0.clone()) + } +} + +// SAFETY: uhhhhhhhh copied the Arc impl from arc_swap xd +unsafe impl RefCnt for ArcRefCnt { + type Base = T; + + fn into_ptr(me: Self) -> *mut Self::Base { + Arc::into_raw(me.0) as *mut T + } + + fn as_ptr(me: &Self) -> *mut Self::Base { + // Slightly convoluted way to do this, but this avoids stacked borrows violations. The same + // intention as + // + // me as &T as *const T as *mut T + // + // We first create a "shallow copy" of me - one that doesn't really own its ref count + // (that's OK, me _does_ own it, so it can't be destroyed in the meantime). + // Then we can use into_raw (which preserves not having the ref count). + // + // We need to "revert" the changes we did. In current std implementation, the combination + // of from_raw and forget is no-op. But formally, into_raw shall be paired with from_raw + // and that read shall be paired with forget to properly "close the brackets". In future + // versions of STD, these may become something else that's not really no-op (unlikely, but + // possible), so we future-proof it a bit. + + // SAFETY: &T cast to *const T will always be aligned, initialised and valid for reads + let ptr = Arc::into_raw(unsafe { std::ptr::read(&me.0) }); + let ptr = ptr as *mut T; + + // SAFETY: We got the pointer from into_raw just above + std::mem::forget(unsafe { Arc::from_raw(ptr) }); + + ptr + } + + unsafe fn from_ptr(ptr: *const Self::Base) -> Self { + Self(unsafe { Arc::from_raw(ptr) }) + } +} -- knotmirror 0.0.1