20261117 合入#188第二版仓库mmap索引
This commit is contained in:
@@ -8,6 +8,13 @@ default = ["full"]
|
|||||||
# Full build used by the main RP implementation (includes RocksDB-backed storage).
|
# Full build used by the main RP implementation (includes RocksDB-backed storage).
|
||||||
full = ["dep:rocksdb"]
|
full = ["dep:rocksdb"]
|
||||||
profile = ["dep:pprof", "dep:flate2"]
|
profile = ["dep:pprof", "dep:flate2"]
|
||||||
|
# Opt-in local index prototype; never selected by the RP CLI.
|
||||||
|
index-bench = []
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "current_repo_index_bench"
|
||||||
|
path = "src/bin/current_repo_index_bench.rs"
|
||||||
|
required-features = ["full", "index-bench"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
asn1-rs = "0.7.1"
|
asn1-rs = "0.7.1"
|
||||||
|
|||||||
7
src/bin/current_repo_index_bench.rs
Normal file
7
src/bin/current_repo_index_bench.rs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
//! Read-only historical input, isolated prototype output. Does not run an RP.
|
||||||
|
fn main() {
|
||||||
|
if let Err(error) = rpki::current_repo_index::run_local_benchmark(std::env::args().skip(1)) {
|
||||||
|
eprintln!("{error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/cli.rs
10
src/cli.rs
@@ -2771,6 +2771,16 @@ fn run_internal(
|
|||||||
)?
|
)?
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Required raw-index persistence is inside T1 validation/payload timing.
|
||||||
|
// T2 intentionally keeps the pre-existing RocksDB hydration path.
|
||||||
|
if benchmark.is_none() {
|
||||||
|
if let Err(error) = store.persist_current_repo_mmap() {
|
||||||
|
crate::progress_log::emit(
|
||||||
|
"current_repo_mmap_persist",
|
||||||
|
serde_json::json!({"state": "failed", "error": error}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
let early_benchmark_pp_refresh =
|
let early_benchmark_pp_refresh =
|
||||||
if benchmark.is_some() && args.enable_publication_point_validation_cache {
|
if benchmark.is_some() && args.enable_publication_point_validation_cache {
|
||||||
store
|
store
|
||||||
|
|||||||
@@ -3,6 +3,44 @@ use std::sync::{Arc, RwLock};
|
|||||||
|
|
||||||
use crate::storage::{RepositoryViewEntry, RepositoryViewState};
|
use crate::storage::{RepositoryViewEntry, RepositoryViewState};
|
||||||
|
|
||||||
|
pub(crate) mod mmap;
|
||||||
|
|
||||||
|
#[cfg(feature = "index-bench")]
|
||||||
|
pub use mmap::local_benchmark::run_local_benchmark;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct CurrentRepoEntryRef<'a> {
|
||||||
|
pub current_hash: [u8; 32],
|
||||||
|
pub current_hash_hex: &'a str,
|
||||||
|
pub repository_source: &'a str,
|
||||||
|
pub object_type: Option<&'a str>,
|
||||||
|
pub state: RepositoryViewState,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<&'a CurrentRepoEntry> for CurrentRepoEntryRef<'a> {
|
||||||
|
fn from(value: &'a CurrentRepoEntry) -> Self {
|
||||||
|
Self {
|
||||||
|
current_hash: value.current_hash,
|
||||||
|
current_hash_hex: &value.current_hash_hex,
|
||||||
|
repository_source: &value.repository_source,
|
||||||
|
object_type: value.object_type.as_deref(),
|
||||||
|
state: value.state,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CurrentRepoEntryRef<'_> {
|
||||||
|
fn to_owned(self) -> CurrentRepoEntry {
|
||||||
|
CurrentRepoEntry {
|
||||||
|
current_hash: self.current_hash,
|
||||||
|
current_hash_hex: self.current_hash_hex.into(),
|
||||||
|
repository_source: self.repository_source.into(),
|
||||||
|
object_type: self.object_type.map(str::to_owned),
|
||||||
|
state: self.state,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct CurrentRepoEntry {
|
pub struct CurrentRepoEntry {
|
||||||
pub current_hash: [u8; 32],
|
pub current_hash: [u8; 32],
|
||||||
@@ -22,7 +60,21 @@ pub struct CurrentRepoObject {
|
|||||||
|
|
||||||
#[derive(Default, Debug)]
|
#[derive(Default, Debug)]
|
||||||
pub struct CurrentRepoIndex {
|
pub struct CurrentRepoIndex {
|
||||||
by_uri: HashMap<String, CurrentRepoEntry>,
|
by_uri: HashMap<String, (u64, Option<CurrentRepoEntry>)>,
|
||||||
|
mapped: HashMap<String, (u64, mmap::RepoView)>,
|
||||||
|
routes: HashMap<String, Vec<String>>,
|
||||||
|
generation: u64,
|
||||||
|
directories: HashMap<String, DirectoryRoutes>,
|
||||||
|
route_bytes: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROUTE_BUDGET: usize = 32 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
struct DirectoryRoutes {
|
||||||
|
exact: HashMap<String, Vec<String>>,
|
||||||
|
fallback: Vec<String>,
|
||||||
|
bytes: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared handle to the run-wide current repository index. Readers (phase 2
|
/// Shared handle to the run-wide current repository index. Readers (phase 2
|
||||||
@@ -41,16 +93,157 @@ impl CurrentRepoIndex {
|
|||||||
Arc::new(RwLock::new(Self::new()))
|
Arc::new(RwLock::new(Self::new()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_by_uri(&self, rsync_uri: &str) -> Option<&CurrentRepoEntry> {
|
pub fn get_by_uri(&self, rsync_uri: &str) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
self.by_uri.get(rsync_uri)
|
let explicit = self.by_uri.get(rsync_uri);
|
||||||
|
if self.mapped.is_empty() {
|
||||||
|
return explicit.and_then(|(_, e)| e.as_ref().map(CurrentRepoEntryRef::from));
|
||||||
|
}
|
||||||
|
let hash = mmap::hash64(rsync_uri.as_bytes());
|
||||||
|
let module = mmap::module_prefix(rsync_uri);
|
||||||
|
let candidates = self.routes.get(module);
|
||||||
|
let lookup = |source: &str| {
|
||||||
|
let (generation, view) = &self.mapped[source];
|
||||||
|
if explicit.is_some_and(|(g, _)| generation <= g) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
view.get_hashed(rsync_uri, hash)
|
||||||
|
};
|
||||||
|
if let Some(sources) = candidates {
|
||||||
|
if sources.len() == 1 {
|
||||||
|
if let Some(entry) = lookup(&sources[0]) {
|
||||||
|
return Some(entry);
|
||||||
|
}
|
||||||
|
} else if let Some(routes) = self.directories.get(module) {
|
||||||
|
let mut exact = routes
|
||||||
|
.exact
|
||||||
|
.get(mmap::directory(rsync_uri))
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.peekable();
|
||||||
|
let mut fallback = routes.fallback.iter().peekable();
|
||||||
|
loop {
|
||||||
|
let source = match (exact.peek(), fallback.peek()) {
|
||||||
|
(Some(a), Some(b)) if a == b => {
|
||||||
|
fallback.next();
|
||||||
|
exact.next()
|
||||||
|
}
|
||||||
|
(Some(a), Some(b)) if self.mapped[*a].0 > self.mapped[*b].0 => exact.next(),
|
||||||
|
(Some(_), Some(_)) => fallback.next(),
|
||||||
|
(Some(_), None) => exact.next(),
|
||||||
|
(None, Some(_)) => fallback.next(),
|
||||||
|
(None, None) => break,
|
||||||
|
}
|
||||||
|
.unwrap();
|
||||||
|
if explicit.is_some_and(|(g, _)| self.mapped[source].0 <= *g) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(entry) = lookup(source) {
|
||||||
|
return Some(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
explicit.and_then(|(_, e)| e.as_ref().map(CurrentRepoEntryRef::from))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn install_mmap(&mut self, view: mmap::RepoView) {
|
||||||
|
self.install_mmap_with_budget(view, ROUTE_BUDGET);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install_mmap_with_budget(&mut self, view: mmap::RepoView, budget: usize) {
|
||||||
|
self.generation += 1;
|
||||||
|
// Only source-local old/new modules are changed. Immutable summaries
|
||||||
|
// supply directories without decoding every object into a heap map.
|
||||||
|
let mut affected = view.routes();
|
||||||
|
if let Some((_, old)) = self.mapped.get(&view.source) {
|
||||||
|
affected.extend(old.routes());
|
||||||
|
}
|
||||||
|
affected.sort_unstable();
|
||||||
|
affected.dedup();
|
||||||
|
for module in &affected {
|
||||||
|
if let Some(sources) = self.routes.get_mut(module) {
|
||||||
|
sources.retain(|s| s != &view.source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for module in view.routes() {
|
||||||
|
self.routes
|
||||||
|
.entry(module)
|
||||||
|
.or_default()
|
||||||
|
.push(view.source.clone());
|
||||||
|
}
|
||||||
|
self.mapped
|
||||||
|
.insert(view.source.clone(), (self.generation, view));
|
||||||
|
for module in affected {
|
||||||
|
if let Some(old) = self.directories.remove(&module) {
|
||||||
|
self.route_bytes -= old.bytes;
|
||||||
|
}
|
||||||
|
let sources = self
|
||||||
|
.routes
|
||||||
|
.get_mut(&module)
|
||||||
|
.expect("affected module registered");
|
||||||
|
sources.sort_unstable_by_key(|s| std::cmp::Reverse(self.mapped[s].0));
|
||||||
|
if sources.len() <= 1 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut routes = DirectoryRoutes::default();
|
||||||
|
for source in sources.iter() {
|
||||||
|
for dir in self.mapped[source]
|
||||||
|
.1
|
||||||
|
.directories()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|d| mmap::module_prefix(d) == module)
|
||||||
|
{
|
||||||
|
let cost = dir.len() + source.len() + 128;
|
||||||
|
if self
|
||||||
|
.route_bytes
|
||||||
|
.saturating_add(routes.bytes)
|
||||||
|
.saturating_add(cost)
|
||||||
|
<= budget
|
||||||
|
{
|
||||||
|
routes
|
||||||
|
.exact
|
||||||
|
.entry(dir.into())
|
||||||
|
.or_default()
|
||||||
|
.push(source.clone());
|
||||||
|
routes.bytes += cost;
|
||||||
|
} else {
|
||||||
|
// A source omitted from any exact directory remains a
|
||||||
|
// candidate even when another exact directory hits.
|
||||||
|
if routes.fallback.last() != Some(source) {
|
||||||
|
routes.fallback.push(source.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
routes
|
||||||
|
.fallback
|
||||||
|
.sort_unstable_by_key(|s| std::cmp::Reverse(self.mapped[s].0));
|
||||||
|
routes.fallback.dedup();
|
||||||
|
self.route_bytes += routes.bytes;
|
||||||
|
self.directories.insert(module, routes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uris(&self) -> Vec<&str> {
|
||||||
|
let mut uris: Vec<_> = self
|
||||||
|
.by_uri
|
||||||
|
.keys()
|
||||||
|
.map(String::as_str)
|
||||||
|
.chain(self.mapped.values().flat_map(|(_, v)| v.uris()))
|
||||||
|
.collect();
|
||||||
|
uris.sort_unstable();
|
||||||
|
uris.dedup();
|
||||||
|
uris.retain(|uri| self.get_by_uri(uri).is_some());
|
||||||
|
uris
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_scope_uris(&self, repository_source: &str) -> Vec<String> {
|
pub fn list_scope_uris(&self, repository_source: &str) -> Vec<String> {
|
||||||
let mut out = self
|
let mut out = self
|
||||||
.by_uri
|
.uris()
|
||||||
.iter()
|
.into_iter()
|
||||||
.filter_map(|(rsync_uri, entry)| {
|
.filter_map(|uri| {
|
||||||
(entry.repository_source == repository_source).then(|| rsync_uri.clone())
|
(self.get_by_uri(uri)?.repository_source == repository_source)
|
||||||
|
.then(|| uri.to_owned())
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
out.sort();
|
out.sort();
|
||||||
@@ -58,34 +251,85 @@ impl CurrentRepoIndex {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn active_uri_count(&self) -> usize {
|
pub fn active_uri_count(&self) -> usize {
|
||||||
self.by_uri.len()
|
if self.mapped.is_empty() {
|
||||||
|
return self.by_uri.values().filter(|(_, e)| e.is_some()).count();
|
||||||
|
}
|
||||||
|
self.uris().len()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scope_count(&self) -> usize {
|
pub fn scope_count(&self) -> usize {
|
||||||
self.by_uri
|
if self.mapped.is_empty() {
|
||||||
|
return self
|
||||||
|
.by_uri
|
||||||
.values()
|
.values()
|
||||||
.map(|entry| entry.repository_source.as_str())
|
.filter_map(|(_, e)| e.as_ref().map(|e| e.repository_source.as_str()))
|
||||||
|
.collect::<HashSet<_>>()
|
||||||
|
.len();
|
||||||
|
}
|
||||||
|
self.uris()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|uri| self.get_by_uri(uri).map(|e| e.repository_source))
|
||||||
.collect::<HashSet<_>>()
|
.collect::<HashSet<_>>()
|
||||||
.len()
|
.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn snapshot_objects(&self) -> Vec<CurrentRepoObject> {
|
pub fn snapshot_objects(&self) -> Vec<CurrentRepoObject> {
|
||||||
let mut out = self
|
if self.mapped.is_empty() {
|
||||||
|
let mut out: Vec<_> = self
|
||||||
.by_uri
|
.by_uri
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(rsync_uri, entry)| CurrentRepoObject {
|
.filter_map(|(uri, (_, entry))| {
|
||||||
rsync_uri: rsync_uri.clone(),
|
let entry = entry.as_ref()?;
|
||||||
|
Some(CurrentRepoObject {
|
||||||
|
rsync_uri: uri.clone(),
|
||||||
current_hash_hex: entry.current_hash_hex.clone(),
|
current_hash_hex: entry.current_hash_hex.clone(),
|
||||||
repository_source: entry.repository_source.clone(),
|
repository_source: entry.repository_source.clone(),
|
||||||
object_type: entry.object_type.clone(),
|
object_type: entry.object_type.clone(),
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
})
|
||||||
|
.collect();
|
||||||
out.sort();
|
out.sort();
|
||||||
out
|
return out;
|
||||||
|
}
|
||||||
|
let mut entries: Vec<_> = self
|
||||||
|
.mapped
|
||||||
|
.values()
|
||||||
|
.flat_map(|(generation, view)| {
|
||||||
|
view.entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(uri, value)| (uri, *generation, Some(value)))
|
||||||
|
})
|
||||||
|
.chain(self.by_uri.iter().map(|(uri, (generation, value))| {
|
||||||
|
(
|
||||||
|
uri.as_str(),
|
||||||
|
*generation,
|
||||||
|
value.as_ref().map(CurrentRepoEntryRef::from),
|
||||||
|
)
|
||||||
|
}))
|
||||||
|
.collect();
|
||||||
|
entries.sort_unstable_by(|a, b| a.0.cmp(b.0).then(b.1.cmp(&a.1)));
|
||||||
|
entries.dedup_by(|a, b| a.0 == b.0);
|
||||||
|
entries
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(uri, _, value)| {
|
||||||
|
let value = value?;
|
||||||
|
Some(CurrentRepoObject {
|
||||||
|
rsync_uri: uri.to_owned(),
|
||||||
|
current_hash_hex: value.current_hash_hex.to_owned(),
|
||||||
|
repository_source: value.repository_source.to_owned(),
|
||||||
|
object_type: value.object_type.map(str::to_owned),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
self.by_uri.clear();
|
self.by_uri.clear();
|
||||||
|
self.mapped.clear();
|
||||||
|
self.routes.clear();
|
||||||
|
self.directories.clear();
|
||||||
|
self.route_bytes = 0;
|
||||||
|
self.generation = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_repository_view_entries(
|
pub fn apply_repository_view_entries(
|
||||||
@@ -100,6 +344,7 @@ impl CurrentRepoIndex {
|
|||||||
|
|
||||||
fn apply_repository_view_entry(&mut self, entry: &RepositoryViewEntry) -> Result<(), String> {
|
fn apply_repository_view_entry(&mut self, entry: &RepositoryViewEntry) -> Result<(), String> {
|
||||||
entry.validate_internal().map_err(|e| e.to_string())?;
|
entry.validate_internal().map_err(|e| e.to_string())?;
|
||||||
|
self.generation += 1;
|
||||||
|
|
||||||
match entry.state {
|
match entry.state {
|
||||||
RepositoryViewState::Present | RepositoryViewState::Replaced => {
|
RepositoryViewState::Present | RepositoryViewState::Replaced => {
|
||||||
@@ -118,17 +363,21 @@ impl CurrentRepoIndex {
|
|||||||
let current_hash = decode_sha256_hex_32(¤t_hash_hex)?;
|
let current_hash = decode_sha256_hex_32(¤t_hash_hex)?;
|
||||||
self.by_uri.insert(
|
self.by_uri.insert(
|
||||||
entry.rsync_uri.clone(),
|
entry.rsync_uri.clone(),
|
||||||
CurrentRepoEntry {
|
(
|
||||||
|
self.generation,
|
||||||
|
Some(CurrentRepoEntry {
|
||||||
current_hash,
|
current_hash,
|
||||||
current_hash_hex: current_hash_hex.to_ascii_lowercase(),
|
current_hash_hex: current_hash_hex.to_ascii_lowercase(),
|
||||||
repository_source,
|
repository_source,
|
||||||
object_type: entry.object_type.clone(),
|
object_type: entry.object_type.clone(),
|
||||||
state: entry.state,
|
state: entry.state,
|
||||||
},
|
}),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
RepositoryViewState::Withdrawn => {
|
RepositoryViewState::Withdrawn => {
|
||||||
self.by_uri.remove(&entry.rsync_uri);
|
self.by_uri
|
||||||
|
.insert(entry.rsync_uri.clone(), (self.generation, None));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
287
src/current_repo_index/format_v2.rs
Normal file
287
src/current_repo_index/format_v2.rs
Normal file
@@ -0,0 +1,287 @@
|
|||||||
|
//! Shared v2 immutable format: production and isolated reference benchmark.
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const V2_MAGIC: &[u8; 8] = b"RPKICRI2";
|
||||||
|
const FOOTER: &[u8; 8] = b"CRIV2END";
|
||||||
|
pub(super) const FOOTER_SIZE: usize = 64;
|
||||||
|
const PROBE_LIMIT: usize = 64;
|
||||||
|
|
||||||
|
// XXH64, seed 0, frozen as v2 format algorithm 1.
|
||||||
|
// Only an accelerator: every candidate is checked against the full URI.
|
||||||
|
pub(crate) fn hash64(bytes: &[u8]) -> u64 {
|
||||||
|
const P1: u64 = 11400714785074694791;
|
||||||
|
const P2: u64 = 14029467366897019727;
|
||||||
|
const P3: u64 = 1609587929392839161;
|
||||||
|
const P4: u64 = 9650029242287828579;
|
||||||
|
const P5: u64 = 2870177450012600261;
|
||||||
|
fn lane(acc: u64, value: u64) -> u64 {
|
||||||
|
acc.wrapping_add(value.wrapping_mul(P2))
|
||||||
|
.rotate_left(31)
|
||||||
|
.wrapping_mul(P1)
|
||||||
|
}
|
||||||
|
let word = |at| u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap());
|
||||||
|
let mut at = 0;
|
||||||
|
let mut h;
|
||||||
|
if bytes.len() >= 32 {
|
||||||
|
let mut v = [P1.wrapping_add(P2), P2, 0, 0u64.wrapping_sub(P1)];
|
||||||
|
while at + 32 <= bytes.len() {
|
||||||
|
for (i, acc) in v.iter_mut().enumerate() {
|
||||||
|
*acc = lane(*acc, word(at + i * 8));
|
||||||
|
}
|
||||||
|
at += 32;
|
||||||
|
}
|
||||||
|
h = v[0]
|
||||||
|
.rotate_left(1)
|
||||||
|
.wrapping_add(v[1].rotate_left(7))
|
||||||
|
.wrapping_add(v[2].rotate_left(12))
|
||||||
|
.wrapping_add(v[3].rotate_left(18));
|
||||||
|
for acc in v {
|
||||||
|
h = (h ^ lane(0, acc)).wrapping_mul(P1).wrapping_add(P4);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
h = P5;
|
||||||
|
}
|
||||||
|
h = h.wrapping_add(bytes.len() as u64);
|
||||||
|
while at + 8 <= bytes.len() {
|
||||||
|
h = (h ^ lane(0, word(at)))
|
||||||
|
.rotate_left(27)
|
||||||
|
.wrapping_mul(P1)
|
||||||
|
.wrapping_add(P4);
|
||||||
|
at += 8;
|
||||||
|
}
|
||||||
|
if at + 4 <= bytes.len() {
|
||||||
|
h ^= (u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap()) as u64).wrapping_mul(P1);
|
||||||
|
h = h.rotate_left(23).wrapping_mul(P2).wrapping_add(P3);
|
||||||
|
at += 4;
|
||||||
|
}
|
||||||
|
for b in &bytes[at..] {
|
||||||
|
h ^= (*b as u64).wrapping_mul(P5);
|
||||||
|
h = h.rotate_left(11).wrapping_mul(P1);
|
||||||
|
}
|
||||||
|
h ^= h >> 33;
|
||||||
|
h = h.wrapping_mul(P2);
|
||||||
|
h ^= h >> 29;
|
||||||
|
h = h.wrapping_mul(P3);
|
||||||
|
h ^ (h >> 32)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn directory(uri: &str) -> &str {
|
||||||
|
&uri[..uri.rfind('/').map_or(uri.len(), |n| n + 1)]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn put64(bytes: &mut [u8], at: usize, n: u64) {
|
||||||
|
bytes[at..at + 8].copy_from_slice(&n.to_le_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn get64(bytes: &[u8], at: usize) -> u64 {
|
||||||
|
u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn prototype_bytes(v1: &Segment) -> Result<Vec<u8>, String> {
|
||||||
|
append_index(v1.bytes.to_vec(), (0..v1.count).map(|n| v1.uri_at(n)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn append_index<'a>(
|
||||||
|
mut bytes: Vec<u8>,
|
||||||
|
uris: impl Iterator<Item = &'a str> + Clone,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
|
let count = uris.clone().count();
|
||||||
|
bytes[..8].copy_from_slice(V2_MAGIC);
|
||||||
|
let slots = bytes.len();
|
||||||
|
let capacity = count
|
||||||
|
.checked_mul(2)
|
||||||
|
.and_then(|n| n.max(1).checked_next_power_of_two())
|
||||||
|
.ok_or("hash capacity overflow")?;
|
||||||
|
let end = capacity
|
||||||
|
.checked_mul(16)
|
||||||
|
.and_then(|n| slots.checked_add(n))
|
||||||
|
.ok_or("hash table overflow")?;
|
||||||
|
bytes.resize(end, 0);
|
||||||
|
for (n, uri) in uris.clone().enumerate() {
|
||||||
|
let h = hash64(uri.as_bytes());
|
||||||
|
let mut pos = h as usize & (capacity - 1);
|
||||||
|
while get64(&bytes, slots + pos * 16 + 8) != 0 {
|
||||||
|
pos = (pos + 1) & (capacity - 1);
|
||||||
|
}
|
||||||
|
put64(&mut bytes, slots + pos * 16, h);
|
||||||
|
put64(&mut bytes, slots + pos * 16 + 8, n as u64 + 1);
|
||||||
|
}
|
||||||
|
let dirs_start = bytes.len();
|
||||||
|
let dirs = uris
|
||||||
|
.map(directory)
|
||||||
|
.collect::<std::collections::BTreeSet<_>>();
|
||||||
|
for dir in &dirs {
|
||||||
|
let len = u32::try_from(dir.len()).map_err(|e| e.to_string())?;
|
||||||
|
bytes.extend_from_slice(&len.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(dir.as_bytes());
|
||||||
|
}
|
||||||
|
for n in [
|
||||||
|
slots as u64,
|
||||||
|
capacity as u64,
|
||||||
|
dirs_start as u64,
|
||||||
|
dirs.len() as u64,
|
||||||
|
1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
] {
|
||||||
|
bytes.extend_from_slice(&n.to_le_bytes());
|
||||||
|
}
|
||||||
|
bytes.extend_from_slice(FOOTER);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(super) struct V2Segment {
|
||||||
|
pub(super) core: Segment,
|
||||||
|
pub(super) slots: usize,
|
||||||
|
pub(super) capacity: usize,
|
||||||
|
pub(super) dirs: Vec<(usize, usize)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl V2Segment {
|
||||||
|
pub(super) fn open(path: &Path, digest: &str) -> Result<Self, String> {
|
||||||
|
let file = File::open(path).map_err(|e| e.to_string())?;
|
||||||
|
// SAFETY: segment files are immutable; publication is atomic and
|
||||||
|
// each complete byte range is validated before any unchecked access.
|
||||||
|
let bytes = unsafe { Mmap::map(&file) }.map_err(|e| e.to_string())?;
|
||||||
|
if bytes.len() < 24 + FOOTER_SIZE
|
||||||
|
|| &bytes[..8] != V2_MAGIC
|
||||||
|
|| &bytes[bytes.len() - 8..] != FOOTER
|
||||||
|
|| hex::encode(Sha256::digest(&bytes)) != digest
|
||||||
|
{
|
||||||
|
return Err("v2 header/checksum mismatch".into());
|
||||||
|
}
|
||||||
|
let footer = bytes.len() - FOOTER_SIZE;
|
||||||
|
let number = |at| usize::try_from(get64(&bytes, at)).map_err(|e| e.to_string());
|
||||||
|
let slots = number(footer)?;
|
||||||
|
let capacity = number(footer + 8)?;
|
||||||
|
let dirs_start = number(footer + 16)?;
|
||||||
|
let dir_count = number(footer + 24)?;
|
||||||
|
let count = number(8)?;
|
||||||
|
let expected = count
|
||||||
|
.checked_mul(2)
|
||||||
|
.and_then(|n| n.max(1).checked_next_power_of_two());
|
||||||
|
let table_end = count
|
||||||
|
.checked_add(1)
|
||||||
|
.and_then(|n| n.checked_mul(8))
|
||||||
|
.and_then(|n| n.checked_add(16));
|
||||||
|
if get64(&bytes, footer + 32) != 1
|
||||||
|
|| get64(&bytes, footer + 40) != 0
|
||||||
|
|| get64(&bytes, footer + 48) != 0
|
||||||
|
|| Some(capacity) != expected
|
||||||
|
|| table_end.is_none_or(|n| n > slots)
|
||||||
|
|| slots > dirs_start
|
||||||
|
|| capacity.checked_mul(16).and_then(|n| slots.checked_add(n)) != Some(dirs_start)
|
||||||
|
|| dirs_start > footer
|
||||||
|
|| dir_count > (footer - dirs_start) / 4
|
||||||
|
{
|
||||||
|
return Err("v2 layout invalid".into());
|
||||||
|
}
|
||||||
|
let core = Segment {
|
||||||
|
bytes,
|
||||||
|
count,
|
||||||
|
hash_layout: None,
|
||||||
|
};
|
||||||
|
if core.offset(0)? != table_end.unwrap() || core.offset(count)? != slots {
|
||||||
|
return Err("v2 record boundaries invalid".into());
|
||||||
|
}
|
||||||
|
let mut previous = None;
|
||||||
|
let mut expected_dirs = std::collections::BTreeSet::new();
|
||||||
|
for n in 0..count {
|
||||||
|
let (uri, _) = core.record(n)?;
|
||||||
|
if previous.is_some_and(|p| p >= uri) {
|
||||||
|
return Err("v2 URI order invalid".into());
|
||||||
|
}
|
||||||
|
let dir = directory(uri);
|
||||||
|
expected_dirs.insert(dir);
|
||||||
|
previous = Some(uri);
|
||||||
|
}
|
||||||
|
let mut dirs = Vec::new();
|
||||||
|
let expected_dirs = expected_dirs.into_iter().collect::<Vec<_>>();
|
||||||
|
let mut cursor = dirs_start;
|
||||||
|
for _ in 0..dir_count {
|
||||||
|
let len_bytes = core
|
||||||
|
.bytes
|
||||||
|
.get(cursor..cursor.saturating_add(4))
|
||||||
|
.ok_or("v2 directory truncated")?;
|
||||||
|
let len = u32::from_le_bytes(len_bytes.try_into().unwrap()) as usize;
|
||||||
|
cursor += 4;
|
||||||
|
let end = cursor
|
||||||
|
.checked_add(len)
|
||||||
|
.filter(|e| *e <= footer)
|
||||||
|
.ok_or("v2 directory out of bounds")?;
|
||||||
|
let dir = std::str::from_utf8(&core.bytes[cursor..end]).map_err(|e| e.to_string())?;
|
||||||
|
if expected_dirs.get(dirs.len()).copied() != Some(dir) {
|
||||||
|
return Err("v2 directory summary incomplete/unsorted".into());
|
||||||
|
}
|
||||||
|
dirs.push((cursor, end));
|
||||||
|
cursor = end;
|
||||||
|
}
|
||||||
|
if cursor != footer || dirs.len() != expected_dirs.len() {
|
||||||
|
return Err("v2 directory count invalid".into());
|
||||||
|
}
|
||||||
|
let this = Self {
|
||||||
|
core,
|
||||||
|
slots,
|
||||||
|
capacity,
|
||||||
|
dirs,
|
||||||
|
};
|
||||||
|
let mut seen = vec![false; count];
|
||||||
|
for pos in 0..capacity {
|
||||||
|
let (h, ordinal) = this.slot(pos);
|
||||||
|
if ordinal == 0 {
|
||||||
|
if h != 0 {
|
||||||
|
return Err("v2 noncanonical empty slot".into());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let n = usize::try_from(ordinal - 1).map_err(|e| e.to_string())?;
|
||||||
|
if n >= count || seen[n] || h != hash64(this.core.uri_at(n).as_bytes()) {
|
||||||
|
return Err("v2 ordinal/hash coverage invalid".into());
|
||||||
|
}
|
||||||
|
seen[n] = true;
|
||||||
|
// Verify reachability in bounded work. Beyond the query probe
|
||||||
|
// limit the lookup always falls back to validated binary search.
|
||||||
|
let home = h as usize & (capacity - 1);
|
||||||
|
let distance = pos.wrapping_sub(home) & (capacity - 1);
|
||||||
|
for offset in 0..distance.min(PROBE_LIMIT) {
|
||||||
|
if this.slot((home + offset) & (capacity - 1)).1 == 0 {
|
||||||
|
return Err("v2 unreachable slot".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if seen.iter().any(|present| !present) {
|
||||||
|
return Err("v2 missing record slot".into());
|
||||||
|
}
|
||||||
|
Ok(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn slot(&self, n: usize) -> (u64, u64) {
|
||||||
|
(
|
||||||
|
get64(&self.core.bytes, self.slots + n * 16),
|
||||||
|
get64(&self.core.bytes, self.slots + n * 16 + 8),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn lookup(&self, uri: &str, hash: u64) -> Option<Option<CurrentRepoEntryRef<'_>>> {
|
||||||
|
let mut pos = hash as usize & (self.capacity - 1);
|
||||||
|
for _ in 0..PROBE_LIMIT.min(self.capacity) {
|
||||||
|
let (h, ordinal) = self.slot(pos);
|
||||||
|
if ordinal == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if h == hash && self.core.uri_at(ordinal as usize - 1) == uri {
|
||||||
|
return Some(self.core.value_at(ordinal as usize - 1));
|
||||||
|
}
|
||||||
|
pos = (pos + 1) & (self.capacity - 1);
|
||||||
|
}
|
||||||
|
self.core.lookup(uri)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn directories(&self) -> impl Iterator<Item = &str> {
|
||||||
|
self.dirs.iter().map(|(start, end)| {
|
||||||
|
// SAFETY: open checked every directory range and UTF-8 string.
|
||||||
|
unsafe { std::str::from_utf8_unchecked(&self.core.bytes[*start..*end]) }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
984
src/current_repo_index/local_benchmark.rs
Normal file
984
src/current_repo_index/local_benchmark.rs
Normal file
@@ -0,0 +1,984 @@
|
|||||||
|
//! Isolated benchmark; v2 format routines are shared with the production RP.
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::hint::black_box;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
use super::format_v2::*;
|
||||||
|
const ROUTE_BUDGET: usize = 32 * 1024 * 1024;
|
||||||
|
|
||||||
|
// Keep the benchmark's historical reference independent from the now-v2
|
||||||
|
// production CurrentRepoIndex. Only immutable v1 segments enter this view.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct LegacyIndex {
|
||||||
|
mapped: HashMap<String, (usize, RepoView)>,
|
||||||
|
routes: HashMap<String, Vec<String>>,
|
||||||
|
generation: usize,
|
||||||
|
}
|
||||||
|
impl LegacyIndex {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
fn install_mmap(&mut self, view: RepoView) {
|
||||||
|
self.generation += 1;
|
||||||
|
for sources in self.routes.values_mut() {
|
||||||
|
sources.retain(|s| s != &view.source);
|
||||||
|
}
|
||||||
|
for route in view.routes() {
|
||||||
|
self.routes
|
||||||
|
.entry(route)
|
||||||
|
.or_default()
|
||||||
|
.push(view.source.clone());
|
||||||
|
}
|
||||||
|
self.mapped
|
||||||
|
.insert(view.source.clone(), (self.generation, view));
|
||||||
|
}
|
||||||
|
fn get_by_uri(&self, uri: &str) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
let mut newest = None;
|
||||||
|
if let Some(sources) = self.routes.get(module_prefix(uri)) {
|
||||||
|
for source in sources {
|
||||||
|
let (generation, view) = &self.mapped[source];
|
||||||
|
if newest.as_ref().is_none_or(|(g, _)| generation > g) {
|
||||||
|
let value = view
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|s| s.lookup(uri))
|
||||||
|
.flatten();
|
||||||
|
if let Some(mut value) = value {
|
||||||
|
value.repository_source = &view.source;
|
||||||
|
newest = Some((*generation, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newest.map(|(_, value)| value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct V2View {
|
||||||
|
source: String,
|
||||||
|
segments: Vec<Arc<V2Segment>>,
|
||||||
|
dirty: HashMap<String, Option<CurrentRepoEntry>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl V2View {
|
||||||
|
fn get(&self, uri: &str, hash: u64) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
let mut entry = if let Some(value) = self.dirty.get(uri) {
|
||||||
|
value.as_ref().map(CurrentRepoEntryRef::from)
|
||||||
|
} else {
|
||||||
|
self.segments
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|s| s.lookup(uri, hash))
|
||||||
|
.flatten()
|
||||||
|
}?;
|
||||||
|
entry.repository_source = &self.source;
|
||||||
|
Some(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct V2Index {
|
||||||
|
views: Vec<V2View>,
|
||||||
|
exact: HashMap<String, Vec<usize>>,
|
||||||
|
fallback: HashMap<String, Vec<usize>>,
|
||||||
|
explicit: HashMap<String, (usize, Option<CurrentRepoEntry>)>,
|
||||||
|
route_bytes_estimate: usize,
|
||||||
|
module: HashMap<String, Vec<usize>>,
|
||||||
|
adaptive: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl V2Index {
|
||||||
|
fn new(views: Vec<V2View>, budget: usize) -> Self {
|
||||||
|
Self::build(views, budget, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build(views: Vec<V2View>, budget: usize, adaptive: bool) -> Self {
|
||||||
|
let mut this = Self {
|
||||||
|
views,
|
||||||
|
exact: HashMap::new(),
|
||||||
|
fallback: HashMap::new(),
|
||||||
|
explicit: HashMap::new(),
|
||||||
|
route_bytes_estimate: 0,
|
||||||
|
module: HashMap::new(),
|
||||||
|
adaptive,
|
||||||
|
};
|
||||||
|
for (id, view) in this.views.iter().enumerate() {
|
||||||
|
let modules: HashSet<_> = view
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.flat_map(|s| s.directories())
|
||||||
|
.map(module_prefix)
|
||||||
|
.chain(view.dirty.keys().map(|uri| module_prefix(uri)))
|
||||||
|
.collect();
|
||||||
|
for module in modules {
|
||||||
|
this.module.entry(module.into()).or_default().push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (id, view) in this.views.iter().enumerate() {
|
||||||
|
let dirs: HashSet<_> = view
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.flat_map(|s| s.directories())
|
||||||
|
.chain(view.dirty.keys().map(|s| directory(s)))
|
||||||
|
.collect();
|
||||||
|
for dir in dirs {
|
||||||
|
if adaptive && this.module[module_prefix(dir)].len() == 1 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let cost = dir.len() + 128; // conservative per-entry allocation estimate
|
||||||
|
if this.route_bytes_estimate.saturating_add(cost) <= budget {
|
||||||
|
this.exact.entry(dir.into()).or_default().push(id);
|
||||||
|
this.route_bytes_estimate += cost;
|
||||||
|
} else {
|
||||||
|
this.fallback
|
||||||
|
.entry(module_prefix(dir).into())
|
||||||
|
.or_default()
|
||||||
|
.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for candidates in this.exact.values_mut().chain(this.fallback.values_mut()) {
|
||||||
|
candidates.sort_unstable_by(|a, b| b.cmp(a));
|
||||||
|
candidates.dedup();
|
||||||
|
}
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
fn candidates<'a>(&'a self, uri: &str) -> impl Iterator<Item = usize> + 'a {
|
||||||
|
let mut exact = self
|
||||||
|
.exact
|
||||||
|
.get(directory(uri))
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.copied()
|
||||||
|
.peekable();
|
||||||
|
let mut fallback = self
|
||||||
|
.fallback
|
||||||
|
.get(module_prefix(uri))
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.copied()
|
||||||
|
.peekable();
|
||||||
|
std::iter::from_fn(
|
||||||
|
move || match (exact.peek().copied(), fallback.peek().copied()) {
|
||||||
|
(Some(a), Some(b)) if a == b => {
|
||||||
|
exact.next();
|
||||||
|
fallback.next();
|
||||||
|
Some(a)
|
||||||
|
}
|
||||||
|
(Some(a), Some(b)) if a > b => exact.next(),
|
||||||
|
(Some(_), Some(_)) => fallback.next(),
|
||||||
|
(Some(_), None) => exact.next(),
|
||||||
|
(None, Some(_)) => fallback.next(),
|
||||||
|
(None, None) => None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get(&self, uri: &str) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
let hash = hash64(uri.as_bytes());
|
||||||
|
let explicit = self.explicit.get(uri);
|
||||||
|
if self.adaptive
|
||||||
|
&& let Some(ids) = self.module.get(module_prefix(uri))
|
||||||
|
&& ids.len() == 1
|
||||||
|
{
|
||||||
|
let id = ids[0];
|
||||||
|
let old =
|
||||||
|
|| explicit.and_then(|(_, entry)| entry.as_ref().map(CurrentRepoEntryRef::from));
|
||||||
|
return if explicit.is_some_and(|(generation, _)| id + 1 <= *generation) {
|
||||||
|
old()
|
||||||
|
} else {
|
||||||
|
self.views[id].get(uri, hash).or_else(old)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for id in self.candidates(uri) {
|
||||||
|
if explicit.is_some_and(|(generation, _)| id + 1 <= *generation) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Some(entry) = self.views[id].get(uri, hash) {
|
||||||
|
return Some(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
explicit.and_then(|(_, entry)| entry.as_ref().map(CurrentRepoEntryRef::from))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cpu_ns() -> u64 {
|
||||||
|
let mut ts = libc::timespec {
|
||||||
|
tv_sec: 0,
|
||||||
|
tv_nsec: 0,
|
||||||
|
};
|
||||||
|
// SAFETY: clock_gettime writes exactly one valid timespec.
|
||||||
|
let result = unsafe { libc::clock_gettime(libc::CLOCK_PROCESS_CPUTIME_ID, &mut ts) };
|
||||||
|
assert_eq!(result, 0, "process CPU clock unavailable");
|
||||||
|
ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timed<T>(f: impl FnOnce() -> T) -> (T, serde_json::Value) {
|
||||||
|
let wall = Instant::now();
|
||||||
|
let cpu = cpu_ns();
|
||||||
|
let value = f();
|
||||||
|
let cpu = cpu_ns() - cpu;
|
||||||
|
(
|
||||||
|
value,
|
||||||
|
serde_json::json!({"wall_ns": wall.elapsed().as_nanos() as u64, "cpu_ns": cpu}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Jobs = Vec<(String, Vec<String>)>;
|
||||||
|
|
||||||
|
fn load_jobs<T: Send>(
|
||||||
|
jobs: &Jobs,
|
||||||
|
workers: usize,
|
||||||
|
load: impl Fn(&str) -> Result<T, String> + Sync,
|
||||||
|
) -> Result<Vec<Vec<T>>, String> {
|
||||||
|
let cursor = AtomicUsize::new(0);
|
||||||
|
std::thread::scope(|scope| {
|
||||||
|
let mut handles = Vec::new();
|
||||||
|
for _ in 0..workers {
|
||||||
|
let cursor = &cursor;
|
||||||
|
let load = &load;
|
||||||
|
handles.push(scope.spawn(move || {
|
||||||
|
let mut results = Vec::new();
|
||||||
|
loop {
|
||||||
|
let id = cursor.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let Some((_, files)) = jobs.get(id) else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
results.push((
|
||||||
|
id,
|
||||||
|
files
|
||||||
|
.iter()
|
||||||
|
.map(|file| load(file))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok::<_, String>(results)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let mut all = Vec::new();
|
||||||
|
for handle in handles {
|
||||||
|
all.extend(handle.join().map_err(|_| "load thread panicked")??);
|
||||||
|
}
|
||||||
|
all.sort_unstable_by_key(|(id, _)| *id);
|
||||||
|
Ok(all.into_iter().map(|(_, segments)| segments).collect())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query<'a>(
|
||||||
|
variant: usize,
|
||||||
|
uri: &str,
|
||||||
|
v1: &'a LegacyIndex,
|
||||||
|
v2: &'a V2Index,
|
||||||
|
adaptive: &'a V2Index,
|
||||||
|
module: &HashMap<String, Vec<usize>>,
|
||||||
|
heap: &'a HashMap<String, CurrentRepoEntry>,
|
||||||
|
) -> Option<CurrentRepoEntryRef<'a>> {
|
||||||
|
match variant {
|
||||||
|
0 => v1.get_by_uri(uri),
|
||||||
|
1 => {
|
||||||
|
let hash = hash64(uri.as_bytes());
|
||||||
|
// Same coarse module candidates as v1; newest source wins.
|
||||||
|
module
|
||||||
|
.get(module_prefix(uri))
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.rev()
|
||||||
|
.find_map(|id| v2.views[*id].get(uri, hash))
|
||||||
|
}
|
||||||
|
2 => v2.get(uri),
|
||||||
|
3 => heap.get(uri).map(CurrentRepoEntryRef::from),
|
||||||
|
4 => adaptive.get(uri),
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shuffled(values: &mut [String], seed: u64) {
|
||||||
|
let mut state = seed;
|
||||||
|
for i in (1..values.len()).rev() {
|
||||||
|
state ^= state << 13;
|
||||||
|
state ^= state >> 7;
|
||||||
|
state ^= state << 17;
|
||||||
|
values.swap(i, state as usize % (i + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_hash(hash: &str) -> Result<(), String> {
|
||||||
|
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
return Err("non-content-addressed segment name".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Explicit local-test entry point, exported only with `index-bench`.
|
||||||
|
pub fn run_local_benchmark(args: impl Iterator<Item = String>) -> Result<(), String> {
|
||||||
|
let mut args = args;
|
||||||
|
let mut input = None;
|
||||||
|
let mut output = None;
|
||||||
|
let mut repeats = 7usize;
|
||||||
|
while let Some(arg) = args.next() {
|
||||||
|
match arg.as_str() {
|
||||||
|
"--input" => input = args.next().map(PathBuf::from),
|
||||||
|
"--output" => output = args.next().map(PathBuf::from),
|
||||||
|
"--repeats" => {
|
||||||
|
repeats = args
|
||||||
|
.next()
|
||||||
|
.ok_or("missing repeats")?
|
||||||
|
.parse::<usize>()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
}
|
||||||
|
_ => return Err(format!("unknown option {arg}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !(3..=21).contains(&repeats) {
|
||||||
|
return Err("repeats must be 3..21".into());
|
||||||
|
}
|
||||||
|
let input = fs::canonicalize(input.ok_or("--input INDEX_DIRECTORY required")?)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let output = output.ok_or("--output NEW_EMPTY_DIRECTORY required")?;
|
||||||
|
let parent = fs::canonicalize(output.parent().ok_or("output parent required")?)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let output = parent.join(output.file_name().ok_or("output basename required")?);
|
||||||
|
if output.starts_with(&input) || input.starts_with(&output) || output.exists() {
|
||||||
|
return Err("output must be a new directory outside historical input".into());
|
||||||
|
}
|
||||||
|
let original_manifest = fs::read(input.join("manifest.json")).map_err(|e| e.to_string())?;
|
||||||
|
let manifest: Manifest =
|
||||||
|
serde_json::from_slice(&original_manifest).map_err(|e| e.to_string())?;
|
||||||
|
if manifest.version != 1 || manifest.sources.is_empty() {
|
||||||
|
return Err("expected populated v1 manifest".into());
|
||||||
|
}
|
||||||
|
let jobs: Jobs = manifest.sources.into_iter().collect();
|
||||||
|
for (_, hashes) in &jobs {
|
||||||
|
for hash in hashes {
|
||||||
|
ensure_hash(hash)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs::create_dir(&output).map_err(|e| e.to_string())?;
|
||||||
|
let v2_dir = output.join("v2-segments");
|
||||||
|
fs::create_dir(&v2_dir).map_err(|e| e.to_string())?;
|
||||||
|
eprintln!("opening historical v1 segments read-only");
|
||||||
|
let (loaded, initial_load) = timed(|| {
|
||||||
|
load_jobs(&jobs, 1, |h| {
|
||||||
|
Segment::open(&input.join(format!("{h}.idx")), h).map(Arc::new)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let loaded = loaded?;
|
||||||
|
let mut converted = HashMap::new();
|
||||||
|
let mut input_bytes = 0u64;
|
||||||
|
let mut prototype_size = 0u64;
|
||||||
|
let (convert_result, convert_timing) = timed(|| -> Result<(), String> {
|
||||||
|
for ((_, hashes), segments) in jobs.iter().zip(&loaded) {
|
||||||
|
for (hash, segment) in hashes.iter().zip(segments) {
|
||||||
|
if converted.contains_key(hash) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
input_bytes += segment.bytes.len() as u64;
|
||||||
|
let bytes = prototype_bytes(segment)?;
|
||||||
|
let digest = hex::encode(Sha256::digest(&bytes));
|
||||||
|
atomic_write(&v2_dir.join(format!("{digest}.idx")), &bytes)?;
|
||||||
|
prototype_size += bytes.len() as u64;
|
||||||
|
converted.insert(hash.clone(), digest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
convert_result?;
|
||||||
|
for (_, hashes) in &jobs {
|
||||||
|
for hash in hashes {
|
||||||
|
if !converted.contains_key(hash) {
|
||||||
|
return Err("prototype conversion incomplete".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let v2_jobs: Jobs = jobs
|
||||||
|
.iter()
|
||||||
|
.map(|(source, files)| {
|
||||||
|
(
|
||||||
|
source.clone(),
|
||||||
|
files.iter().map(|h| converted[h].clone()).collect(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let (v2_loaded, v2_initial_load) = timed(|| {
|
||||||
|
load_jobs(&v2_jobs, 1, |h| {
|
||||||
|
V2Segment::open(&v2_dir.join(format!("{h}.idx")), h).map(Arc::new)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let v2_loaded = v2_loaded?;
|
||||||
|
let mut v1 = LegacyIndex::new();
|
||||||
|
let mut views = Vec::new();
|
||||||
|
let mut module: HashMap<String, Vec<usize>> = HashMap::new();
|
||||||
|
let mut heap = HashMap::new();
|
||||||
|
let (_, reference_setup) = timed(|| {
|
||||||
|
for (id, (((source, _), segments), new_segments)) in
|
||||||
|
jobs.iter().zip(&loaded).zip(&v2_loaded).enumerate()
|
||||||
|
{
|
||||||
|
let view = RepoView {
|
||||||
|
source: source.clone(),
|
||||||
|
segments: segments.clone(),
|
||||||
|
dirty: HashMap::new(),
|
||||||
|
};
|
||||||
|
for route in view.routes() {
|
||||||
|
module.entry(route).or_default().push(id);
|
||||||
|
}
|
||||||
|
for (uri, entry) in view.entries() {
|
||||||
|
heap.insert(uri.to_owned(), entry.to_owned());
|
||||||
|
}
|
||||||
|
v1.install_mmap(view);
|
||||||
|
views.push(V2View {
|
||||||
|
source: source.clone(),
|
||||||
|
segments: new_segments.clone(),
|
||||||
|
dirty: HashMap::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let (v2, route_setup) = timed(|| V2Index::new(views, ROUTE_BUDGET));
|
||||||
|
let (adaptive, adaptive_setup) = timed(|| V2Index::build(v2.views.clone(), ROUTE_BUDGET, true));
|
||||||
|
let mut ordered = heap.keys().cloned().collect::<Vec<_>>();
|
||||||
|
ordered.sort_unstable();
|
||||||
|
let mut random = ordered.clone();
|
||||||
|
shuffled(&mut random, 0x188_20261116);
|
||||||
|
let shared = random
|
||||||
|
.iter()
|
||||||
|
.filter(|uri| {
|
||||||
|
module
|
||||||
|
.get(module_prefix(uri))
|
||||||
|
.is_some_and(|ids| ids.len() > 1)
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let missing = random
|
||||||
|
.iter()
|
||||||
|
.step_by(10)
|
||||||
|
.map(|uri| format!("{uri}.index-bench-absent"))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let multi = random
|
||||||
|
.iter()
|
||||||
|
.filter(|uri| {
|
||||||
|
module
|
||||||
|
.get(module_prefix(uri))
|
||||||
|
.is_some_and(|ids| ids.iter().any(|id| v2.views[*id].segments.len() > 1))
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let withdrawn = loaded
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.flat_map(|s| (0..s.count).map(|n| s.uri_at(n)))
|
||||||
|
.filter(|uri| !heap.contains_key(*uri))
|
||||||
|
.collect::<std::collections::BTreeSet<_>>()
|
||||||
|
.into_iter()
|
||||||
|
.map(str::to_owned)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let worksets = [
|
||||||
|
("ordered_hits", ordered),
|
||||||
|
("shuffled_hits", random),
|
||||||
|
("shared_module_hits", shared),
|
||||||
|
("missing_same_directory", missing),
|
||||||
|
("multi_segment_hits", multi),
|
||||||
|
("withdrawn_real_uris", withdrawn),
|
||||||
|
];
|
||||||
|
let names = [
|
||||||
|
"v1_production",
|
||||||
|
"v2_hash_module",
|
||||||
|
"v2_hash_directory",
|
||||||
|
"heap_hashmap",
|
||||||
|
"v2_hash_adaptive",
|
||||||
|
];
|
||||||
|
eprintln!("validating full real-data query equality");
|
||||||
|
let mut checked = 0u64;
|
||||||
|
for (_, uris) in &worksets {
|
||||||
|
for uri in uris {
|
||||||
|
let expected = heap.get(uri);
|
||||||
|
for variant in [0, 1, 2, 4] {
|
||||||
|
if query(variant, uri, &v1, &v2, &adaptive, &module, &heap)
|
||||||
|
.map(CurrentRepoEntryRef::to_owned)
|
||||||
|
.as_ref()
|
||||||
|
!= expected
|
||||||
|
{
|
||||||
|
return Err(format!("query mismatch {} {uri}", names[variant]));
|
||||||
|
}
|
||||||
|
checked += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut original_affinity = std::mem::MaybeUninit::<libc::cpu_set_t>::uninit();
|
||||||
|
// SAFETY: valid output buffer of the declared size, current process.
|
||||||
|
let original_affinity = unsafe {
|
||||||
|
if libc::sched_getaffinity(
|
||||||
|
0,
|
||||||
|
std::mem::size_of::<libc::cpu_set_t>(),
|
||||||
|
original_affinity.as_mut_ptr(),
|
||||||
|
) != 0
|
||||||
|
{
|
||||||
|
return Err(std::io::Error::last_os_error().to_string());
|
||||||
|
}
|
||||||
|
original_affinity.assume_init()
|
||||||
|
};
|
||||||
|
let mut query_affinity = original_affinity;
|
||||||
|
// Prefer CPU 1 on 186; permit focused tests on constrained local cpusets.
|
||||||
|
let query_cpu = unsafe {
|
||||||
|
let cpu = if libc::CPU_ISSET(1, &original_affinity) {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
(0..libc::CPU_SETSIZE as usize)
|
||||||
|
.find(|n| libc::CPU_ISSET(*n, &original_affinity))
|
||||||
|
.ok_or("empty cpuset")?
|
||||||
|
};
|
||||||
|
libc::CPU_ZERO(&mut query_affinity);
|
||||||
|
libc::CPU_SET(cpu, &mut query_affinity);
|
||||||
|
if libc::sched_setaffinity(0, std::mem::size_of_val(&query_affinity), &query_affinity) != 0
|
||||||
|
{
|
||||||
|
return Err(std::io::Error::last_os_error().to_string());
|
||||||
|
}
|
||||||
|
cpu
|
||||||
|
};
|
||||||
|
let mut query_rows = Vec::new();
|
||||||
|
for (workload, uris) in &worksets {
|
||||||
|
if uris.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
"lookup workload {workload}: {} queries x {repeats} rotations",
|
||||||
|
uris.len()
|
||||||
|
);
|
||||||
|
// Equal warm-up for each variant, outside all timed measurements.
|
||||||
|
for variant in 0..5 {
|
||||||
|
for uri in uris {
|
||||||
|
black_box(query(
|
||||||
|
variant,
|
||||||
|
black_box(uri),
|
||||||
|
&v1,
|
||||||
|
&v2,
|
||||||
|
&adaptive,
|
||||||
|
&module,
|
||||||
|
&heap,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for repeat in 0..repeats {
|
||||||
|
for offset in 0..5 {
|
||||||
|
let variant = (repeat + offset) % 5;
|
||||||
|
let (_, mut timing) = timed(|| {
|
||||||
|
for uri in uris {
|
||||||
|
black_box(query(
|
||||||
|
variant,
|
||||||
|
black_box(uri),
|
||||||
|
&v1,
|
||||||
|
&v2,
|
||||||
|
&adaptive,
|
||||||
|
&module,
|
||||||
|
&heap,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
timing["workload"] = (*workload).into();
|
||||||
|
timing["variant"] = names[variant].into();
|
||||||
|
timing["repeat"] = repeat.into();
|
||||||
|
timing["queries"] = uris.len().into();
|
||||||
|
query_rows.push(timing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// SAFETY: restore the affinity obtained successfully above. New loading
|
||||||
|
// threads inherit this restored cpuset, rather than the lookup-only CPU.
|
||||||
|
if unsafe {
|
||||||
|
libc::sched_setaffinity(
|
||||||
|
0,
|
||||||
|
std::mem::size_of_val(&original_affinity),
|
||||||
|
&original_affinity,
|
||||||
|
)
|
||||||
|
} != 0
|
||||||
|
{
|
||||||
|
return Err(std::io::Error::last_os_error().to_string());
|
||||||
|
}
|
||||||
|
let mut loading_rows = Vec::new();
|
||||||
|
for repeat in 0..3 {
|
||||||
|
for offset in 0..4 {
|
||||||
|
let variant = (repeat + offset) % 4;
|
||||||
|
let workers = if variant % 2 == 0 { 1 } else { 3 };
|
||||||
|
let measurement = if variant < 2 {
|
||||||
|
let (value, timing) = timed(|| {
|
||||||
|
load_jobs(&jobs, workers, |h| {
|
||||||
|
Segment::open(&input.join(format!("{h}.idx")), h)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
drop(value?);
|
||||||
|
timing
|
||||||
|
} else {
|
||||||
|
let (value, timing) = timed(|| {
|
||||||
|
load_jobs(&v2_jobs, workers, |h| {
|
||||||
|
V2Segment::open(&v2_dir.join(format!("{h}.idx")), h)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
drop(value?);
|
||||||
|
timing
|
||||||
|
};
|
||||||
|
loading_rows.push(serde_json::json!({"format": if variant < 2 {"v1"} else {"v2"}, "workers": workers, "repeat": repeat, "timing": measurement}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut coarse_hist = BTreeMap::<usize, usize>::new();
|
||||||
|
let mut exact_hist = BTreeMap::<usize, usize>::new();
|
||||||
|
for uri in heap.keys() {
|
||||||
|
*coarse_hist
|
||||||
|
.entry(module.get(module_prefix(uri)).map_or(0, Vec::len))
|
||||||
|
.or_default() += 1;
|
||||||
|
*exact_hist.entry(v2.candidates(uri).count()).or_default() += 1;
|
||||||
|
}
|
||||||
|
if fs::read(input.join("manifest.json")).map_err(|e| e.to_string())? != original_manifest {
|
||||||
|
return Err("historical manifest changed during benchmark".into());
|
||||||
|
}
|
||||||
|
let mut usage = std::mem::MaybeUninit::<libc::rusage>::uninit();
|
||||||
|
// SAFETY: getrusage initializes the whole structure on success.
|
||||||
|
let max_rss_kib = unsafe {
|
||||||
|
if libc::getrusage(libc::RUSAGE_SELF, usage.as_mut_ptr()) == 0 {
|
||||||
|
usage.assume_init().ru_maxrss
|
||||||
|
} else {
|
||||||
|
-1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let report = serde_json::json!({
|
||||||
|
"schema": "feature188-local-index-v1", "production_path_changed": true, "v1_reference": "frozen module routing and binary segment lookup",
|
||||||
|
"input": input, "input_manifest_sha256": hex::encode(Sha256::digest(&original_manifest)),
|
||||||
|
"sources": jobs.len(), "segments": jobs.iter().map(|(_, s)| s.len()).sum::<usize>(),
|
||||||
|
"query_cpu": query_cpu,
|
||||||
|
"input_segments": jobs, "v2_segments": v2_jobs,
|
||||||
|
"input_bytes": input_bytes, "v2_bytes": prototype_size,
|
||||||
|
"live_uris": heap.len(), "equality_checks": checked, "max_rss_kib_with_all_references": max_rss_kib,
|
||||||
|
"route_budget_bytes": ROUTE_BUDGET, "route_bytes_estimate": v2.route_bytes_estimate,
|
||||||
|
"exact_route_count": v2.exact.len(), "fallback_module_count": v2.fallback.len(),
|
||||||
|
"adaptive_route_bytes_estimate": adaptive.route_bytes_estimate,
|
||||||
|
"adaptive_exact_route_count": adaptive.exact.len(),
|
||||||
|
"adaptive_fallback_module_count": adaptive.fallback.len(),
|
||||||
|
"coarse_module_route_bytes_estimate": adaptive.module.iter().map(|(k, v)| k.len() + 128 + v.len() * 8).sum::<usize>(),
|
||||||
|
"coarse_candidate_histogram": coarse_hist, "exact_candidate_histogram": exact_hist,
|
||||||
|
"setup": {"v1_initial_load": initial_load, "conversion": convert_timing, "v2_initial_load": v2_initial_load,
|
||||||
|
"reference_construction": reference_setup, "directory_route_construction": route_setup,
|
||||||
|
"adaptive_route_construction": adaptive_setup},
|
||||||
|
"lookup_measurements": query_rows, "loading_measurements": loading_rows,
|
||||||
|
"limitations": ["local prototype only; no RP/DB/server/replay", "warm lookup; filesystem cache uncontrolled",
|
||||||
|
"process peak RSS includes all implementations and owned reference/query datasets",
|
||||||
|
"source generations follow sorted manifest installation, not a reconstructed live sync schedule",
|
||||||
|
"source-parallel open benchmark does not modify production locking"]
|
||||||
|
});
|
||||||
|
atomic_write(
|
||||||
|
&output.join("report.json"),
|
||||||
|
&serde_json::to_vec_pretty(&report).map_err(|e| e.to_string())?,
|
||||||
|
)?;
|
||||||
|
println!("{}", output.join("report.json").display());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn entry(n: u8) -> CurrentRepoEntry {
|
||||||
|
CurrentRepoEntry {
|
||||||
|
current_hash: [n; 32],
|
||||||
|
current_hash_hex: hex::encode([n; 32]),
|
||||||
|
repository_source: "https://test/notification.xml".into(),
|
||||||
|
object_type: Some("roa".into()),
|
||||||
|
state: RepositoryViewState::Present,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn segment(dir: &Path, entries: BTreeMap<String, Option<CurrentRepoEntry>>) -> Arc<V2Segment> {
|
||||||
|
let (hash, _) = write_segment(dir, &entries).unwrap();
|
||||||
|
let v1 = Segment::open(&dir.join(format!("{hash}.idx")), &hash).unwrap();
|
||||||
|
let bytes = prototype_bytes(&v1).unwrap();
|
||||||
|
let digest = hex::encode(Sha256::digest(&bytes));
|
||||||
|
let path = dir.join(format!("v2-{digest}.idx"));
|
||||||
|
atomic_write(&path, &bytes).unwrap();
|
||||||
|
Arc::new(V2Segment::open(&path, &digest).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view(source: &str, segments: Vec<Arc<V2Segment>>) -> V2View {
|
||||||
|
V2View {
|
||||||
|
source: source.into(),
|
||||||
|
segments,
|
||||||
|
dirty: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stable_xxh64_vectors() {
|
||||||
|
assert_eq!(hash64(b""), 0xef46db3751d8e999);
|
||||||
|
assert_eq!(hash64(b"a"), 0xd24ec4f1a98c6e5b);
|
||||||
|
assert_eq!(hash64(b"abc"), 0x44bc2cf5ad770999);
|
||||||
|
assert_eq!(hash64(b"message digest"), 0x066ed728fceeb3be);
|
||||||
|
// Independently checked with the system libxxhash XXH64(seed=0).
|
||||||
|
for (len, expected) in [
|
||||||
|
(31, 0xc346d2b59b4d8ee1),
|
||||||
|
(32, 0xcbf59c5116ff32b4),
|
||||||
|
(33, 0x0c535d1acafb8ead),
|
||||||
|
(255, 0x0f7d97507caad693),
|
||||||
|
(1024, 0x6f3914f18fe4df57),
|
||||||
|
] {
|
||||||
|
let bytes = (0..len).map(|n| n as u8).collect::<Vec<_>>();
|
||||||
|
assert_eq!(hash64(&bytes), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn source_parallel_loader_preserves_order_and_allows_three_workers() {
|
||||||
|
let jobs = (0..6)
|
||||||
|
.map(|n| {
|
||||||
|
(
|
||||||
|
format!("source{n}"),
|
||||||
|
vec![format!("{n}-a"), format!("{n}-b")],
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let active = AtomicUsize::new(0);
|
||||||
|
let max = AtomicUsize::new(0);
|
||||||
|
let calls = AtomicUsize::new(0);
|
||||||
|
let barrier = std::sync::Barrier::new(3);
|
||||||
|
let parallel = load_jobs(&jobs, 3, |file| {
|
||||||
|
let now = active.fetch_add(1, Ordering::SeqCst) + 1;
|
||||||
|
max.fetch_max(now, Ordering::SeqCst);
|
||||||
|
if calls.fetch_add(1, Ordering::SeqCst) < 3 {
|
||||||
|
barrier.wait();
|
||||||
|
}
|
||||||
|
active.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
Ok(file.to_owned())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(max.load(Ordering::SeqCst), 3);
|
||||||
|
assert_eq!(
|
||||||
|
parallel,
|
||||||
|
jobs.iter()
|
||||||
|
.map(|(_, files)| files.clone())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_record_states_empty_and_unicode_directories() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
assert!(
|
||||||
|
segment(temp.path(), BTreeMap::new())
|
||||||
|
.lookup("absent", hash64(b"absent"))
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
let mut replaced = entry(2);
|
||||||
|
replaced.state = RepositoryViewState::Replaced;
|
||||||
|
replaced.object_type = None;
|
||||||
|
let rows = BTreeMap::from([
|
||||||
|
("rsync://test/repo/a.roa".into(), Some(entry(1))),
|
||||||
|
("rsync://test/repo/a/余.roa".into(), Some(replaced)),
|
||||||
|
("rsync://test/repo/z.roa".into(), None),
|
||||||
|
]);
|
||||||
|
let segment = segment(temp.path(), rows.clone());
|
||||||
|
for (uri, expected) in rows {
|
||||||
|
let actual = segment.lookup(&uri, hash64(uri.as_bytes())).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
actual.map(|e| (e.current_hash, e.object_type, e.state)),
|
||||||
|
expected
|
||||||
|
.as_ref()
|
||||||
|
.map(|e| (e.current_hash, e.object_type.as_deref(), e.state))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
segment.directories().collect::<Vec<_>>(),
|
||||||
|
["rsync://test/repo/", "rsync://test/repo/a/"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn collisions_full_uri_check_and_probe_limit_binary_fallback() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let uris = (0u32..)
|
||||||
|
.map(|n| format!("rsync://test/repo/{n}.roa"))
|
||||||
|
.filter(|uri| hash64(uri.as_bytes()) & 255 == 0)
|
||||||
|
.take(70)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let rows = uris
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(n, uri)| (uri.clone(), Some(entry(n as u8))))
|
||||||
|
.collect();
|
||||||
|
let segment = segment(temp.path(), rows);
|
||||||
|
assert_eq!(segment.capacity, 256);
|
||||||
|
for (n, uri) in uris.iter().enumerate() {
|
||||||
|
assert_eq!(
|
||||||
|
segment
|
||||||
|
.lookup(uri, hash64(uri.as_bytes()))
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.current_hash,
|
||||||
|
[n as u8; 32]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Force the same 64-bit digest as an existing URI: a digest hit is
|
||||||
|
// insufficient unless the full URI also matches.
|
||||||
|
assert!(
|
||||||
|
segment
|
||||||
|
.lookup("rsync://test/repo/never.roa", hash64(uris[0].as_bytes()))
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multi_segment_tombstone_and_dirty_overlay() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let a = "rsync://test/repo/a.roa";
|
||||||
|
let b = "rsync://test/repo/b.roa";
|
||||||
|
let base = segment(
|
||||||
|
temp.path(),
|
||||||
|
BTreeMap::from([(a.into(), Some(entry(1))), (b.into(), Some(entry(2)))]),
|
||||||
|
);
|
||||||
|
let delta = segment(
|
||||||
|
temp.path(),
|
||||||
|
BTreeMap::from([(a.into(), None), (b.into(), Some(entry(3)))]),
|
||||||
|
);
|
||||||
|
let mut v = view("a", vec![base, delta]);
|
||||||
|
assert!(v.get(a, hash64(a.as_bytes())).is_none());
|
||||||
|
assert_eq!(
|
||||||
|
v.get(b, hash64(b.as_bytes())).unwrap().current_hash,
|
||||||
|
[3; 32]
|
||||||
|
);
|
||||||
|
v.dirty.insert(a.into(), Some(entry(4)));
|
||||||
|
v.dirty.insert(b.into(), None);
|
||||||
|
assert_eq!(
|
||||||
|
v.get(a, hash64(a.as_bytes())).unwrap().current_hash,
|
||||||
|
[4; 32]
|
||||||
|
);
|
||||||
|
assert!(v.get(b, hash64(b.as_bytes())).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shared_directory_generations_and_explicit_global_tombstone() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let uri = "rsync://test/repo/a.roa";
|
||||||
|
let a = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(1)))]));
|
||||||
|
let b = segment(temp.path(), BTreeMap::from([(uri.into(), None)]));
|
||||||
|
let c = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(3)))]));
|
||||||
|
let mut index = V2Index::new(vec![view("a", vec![a]), view("b", vec![b])], ROUTE_BUDGET);
|
||||||
|
// A source-local withdrawal does not erase another source's object.
|
||||||
|
assert_eq!(index.get(uri).unwrap().current_hash, [1; 32]);
|
||||||
|
index.explicit.insert(uri.into(), (2, None));
|
||||||
|
assert!(index.get(uri).is_none());
|
||||||
|
index = V2Index::new(
|
||||||
|
vec![
|
||||||
|
view("a", index.views.remove(0).segments),
|
||||||
|
view("b", index.views.remove(0).segments),
|
||||||
|
view("c", vec![c]),
|
||||||
|
],
|
||||||
|
ROUTE_BUDGET,
|
||||||
|
);
|
||||||
|
index.explicit.insert(uri.into(), (2, None));
|
||||||
|
assert_eq!(index.get(uri).unwrap().current_hash, [3; 32]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_route_must_union_omitted_newer_module_candidate() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let uri = "rsync://test/repo/a.roa";
|
||||||
|
let a = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(1)))]));
|
||||||
|
let b = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(2)))]));
|
||||||
|
let index = V2Index::new(
|
||||||
|
vec![view("old", vec![a]), view("new", vec![b])],
|
||||||
|
directory(uri).len() + 128,
|
||||||
|
);
|
||||||
|
assert!(index.exact.contains_key(directory(uri)));
|
||||||
|
assert!(index.fallback.contains_key(module_prefix(uri)));
|
||||||
|
assert_eq!(index.candidates(uri).collect::<Vec<_>>(), [1, 0]);
|
||||||
|
assert_eq!(index.get(uri).unwrap().current_hash, [2; 32]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adaptive_single_source_skips_directory_map_but_honors_explicit_generation() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let uri = "rsync://test/repo/a.roa";
|
||||||
|
let a = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(1)))]));
|
||||||
|
let mut index = V2Index::build(vec![view("a", vec![a])], ROUTE_BUDGET, true);
|
||||||
|
assert!(index.exact.is_empty());
|
||||||
|
assert_eq!(index.get(uri).unwrap().current_hash, [1; 32]);
|
||||||
|
index.explicit.insert(uri.into(), (1, None));
|
||||||
|
assert!(index.get(uri).is_none());
|
||||||
|
assert!(index.get("rsync://other/repo/absent.roa").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn adaptive_shared_module_uses_exact_or_safe_budget_fallback() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let a_uri = "rsync://test/repo/a/a.roa";
|
||||||
|
let b_uri = "rsync://test/repo/b/b.roa";
|
||||||
|
let a = segment(
|
||||||
|
temp.path(),
|
||||||
|
BTreeMap::from([(a_uri.into(), Some(entry(1)))]),
|
||||||
|
);
|
||||||
|
let b = segment(
|
||||||
|
temp.path(),
|
||||||
|
BTreeMap::from([(b_uri.into(), Some(entry(2)))]),
|
||||||
|
);
|
||||||
|
let views = vec![view("a", vec![a]), view("b", vec![b])];
|
||||||
|
for budget in [0, ROUTE_BUDGET] {
|
||||||
|
let index = V2Index::build(views.clone(), budget, true);
|
||||||
|
assert_eq!(index.get(a_uri).unwrap().current_hash, [1; 32]);
|
||||||
|
assert_eq!(index.get(b_uri).unwrap().current_hash, [2; 32]);
|
||||||
|
if budget > 0 {
|
||||||
|
assert_eq!(index.candidates(a_uri).count(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corrupt_layout_coverage_reachability_and_summary_rejected() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let uri = "rsync://test/repo/a.roa";
|
||||||
|
let s = segment(temp.path(), BTreeMap::from([(uri.into(), Some(entry(1)))]));
|
||||||
|
let original = s.core.bytes.to_vec();
|
||||||
|
let check = |bytes: Vec<u8>| {
|
||||||
|
let path = temp.path().join("corrupt.idx");
|
||||||
|
let digest = hex::encode(Sha256::digest(&bytes));
|
||||||
|
atomic_write(&path, &bytes).unwrap();
|
||||||
|
assert!(V2Segment::open(&path, &digest).is_err());
|
||||||
|
};
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
let pos = hash64(uri.as_bytes()) as usize & (s.capacity - 1);
|
||||||
|
put64(&mut bytes, s.slots + pos * 16 + 8, 2); // out-of-range ordinal
|
||||||
|
check(bytes);
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
bytes[s.slots..s.slots + 16 * s.capacity].fill(0); // missing record
|
||||||
|
check(bytes);
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
let other = (pos + 1) & (s.capacity - 1);
|
||||||
|
bytes.copy_within(
|
||||||
|
s.slots + pos * 16..s.slots + pos * 16 + 16,
|
||||||
|
s.slots + other * 16,
|
||||||
|
);
|
||||||
|
bytes[s.slots + pos * 16..s.slots + pos * 16 + 16].fill(0); // gap before occupied
|
||||||
|
check(bytes);
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
bytes[s.dirs[0].0] = b'x'; // complete directory coverage required
|
||||||
|
check(bytes);
|
||||||
|
let mut bytes = original.clone();
|
||||||
|
let footer = bytes.len() - FOOTER_SIZE;
|
||||||
|
put64(&mut bytes, footer + 8, u64::MAX); // corrupt capacity
|
||||||
|
check(bytes);
|
||||||
|
let mut bytes = original;
|
||||||
|
bytes[0] = b'X';
|
||||||
|
check(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incompatible_versions_and_checksum_rejected() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (hash, _) = write_segment(temp.path(), &BTreeMap::new()).unwrap();
|
||||||
|
let path = temp.path().join(format!("{hash}.idx"));
|
||||||
|
assert!(V2Segment::open(&path, &hash).is_err());
|
||||||
|
let s = segment(temp.path(), BTreeMap::new());
|
||||||
|
let bytes = s.core.bytes.to_vec();
|
||||||
|
let digest = hex::encode(Sha256::digest(&bytes));
|
||||||
|
let path = temp.path().join("v2.idx");
|
||||||
|
atomic_write(&path, &bytes).unwrap();
|
||||||
|
assert!(Segment::open(&path, &digest).is_err());
|
||||||
|
assert!(V2Segment::open(&path, &"0".repeat(64)).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
982
src/current_repo_index/mmap.rs
Normal file
982
src/current_repo_index/mmap.rs
Normal file
@@ -0,0 +1,982 @@
|
|||||||
|
//! Disposable raw-repository indexes. RocksDB remains authoritative.
|
||||||
|
//!
|
||||||
|
//! Immutable, content-addressed segments contain sorted URI records. Queries
|
||||||
|
//! borrow directly from read-only mappings; opening a segment builds no object
|
||||||
|
//! HashMap. A completed-run manifest binds the files to DB IDENTITY + sequence.
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
use std::fs::{self, File, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use memmap2::Mmap;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use super::{CurrentRepoEntry, CurrentRepoEntryRef};
|
||||||
|
use crate::storage::{RepositoryViewState, RrdpSourceMemberRecord};
|
||||||
|
|
||||||
|
const MAGIC: &[u8; 8] = b"RPKICRI1";
|
||||||
|
const FIXED: usize = 105; // state, binary hash, hex hash, URI/type lengths
|
||||||
|
const MAX_SEGMENTS: usize = 8;
|
||||||
|
#[path = "format_v2.rs"]
|
||||||
|
mod format_v2;
|
||||||
|
pub(crate) use format_v2::{directory, hash64};
|
||||||
|
|
||||||
|
#[cfg(any(test, feature = "index-bench"))]
|
||||||
|
#[path = "local_benchmark.rs"]
|
||||||
|
pub(crate) mod local_benchmark;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct Segment {
|
||||||
|
bytes: Mmap,
|
||||||
|
count: usize,
|
||||||
|
hash_layout: Option<HashLayout>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct HashLayout {
|
||||||
|
slots: usize,
|
||||||
|
capacity: usize,
|
||||||
|
dirs: Vec<(usize, usize)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Segment {
|
||||||
|
fn open(path: &Path, digest: &str) -> Result<Self, String> {
|
||||||
|
let file = File::open(path).map_err(|e| e.to_string())?;
|
||||||
|
// SAFETY: writers publish new immutable files, never modify mapped files.
|
||||||
|
// Arc keeps each mapping alive; validate every offset and string below.
|
||||||
|
let bytes = unsafe { Mmap::map(&file) }.map_err(|e| e.to_string())?;
|
||||||
|
if bytes.len() < 24 || &bytes[..8] != MAGIC || hex::encode(Sha256::digest(&bytes)) != digest
|
||||||
|
{
|
||||||
|
return Err("current repository segment header/checksum mismatch".into());
|
||||||
|
}
|
||||||
|
let count = usize::try_from(u64::from_le_bytes(bytes[8..16].try_into().unwrap()))
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let table_end = count
|
||||||
|
.checked_add(1)
|
||||||
|
.and_then(|n| n.checked_mul(8))
|
||||||
|
.and_then(|n| n.checked_add(16))
|
||||||
|
.ok_or("segment table overflow")?;
|
||||||
|
if table_end > bytes.len() {
|
||||||
|
return Err("segment table truncated".into());
|
||||||
|
}
|
||||||
|
let segment = Self {
|
||||||
|
bytes,
|
||||||
|
count,
|
||||||
|
hash_layout: None,
|
||||||
|
};
|
||||||
|
if segment.offset(0)? != table_end || segment.offset(count)? != segment.bytes.len() {
|
||||||
|
return Err("segment table boundaries invalid".into());
|
||||||
|
}
|
||||||
|
let mut previous = None;
|
||||||
|
for n in 0..count {
|
||||||
|
let (uri, _) = segment.record(n)?;
|
||||||
|
if previous.is_some_and(|p| p >= uri) {
|
||||||
|
return Err("segment URIs unsorted/duplicate".into());
|
||||||
|
}
|
||||||
|
previous = Some(uri);
|
||||||
|
}
|
||||||
|
Ok(segment)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn open_current(path: &Path, digest: &str) -> Result<Self, String> {
|
||||||
|
let v2 = format_v2::V2Segment::open(path, digest)?;
|
||||||
|
let mut core = v2.core;
|
||||||
|
core.hash_layout = Some(HashLayout {
|
||||||
|
slots: v2.slots,
|
||||||
|
capacity: v2.capacity,
|
||||||
|
dirs: v2.dirs,
|
||||||
|
});
|
||||||
|
Ok(core)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookup_hashed(&self, uri: &str, hash: u64) -> Option<Option<CurrentRepoEntryRef<'_>>> {
|
||||||
|
let Some(layout) = &self.hash_layout else {
|
||||||
|
return self.lookup(uri);
|
||||||
|
};
|
||||||
|
let mut pos = hash as usize & (layout.capacity - 1);
|
||||||
|
for _ in 0..64.min(layout.capacity) {
|
||||||
|
let at = layout.slots + pos * 16;
|
||||||
|
let h = format_v2::get64(&self.bytes, at);
|
||||||
|
let ordinal = format_v2::get64(&self.bytes, at + 8);
|
||||||
|
if ordinal == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if h == hash && self.uri_at(ordinal as usize - 1) == uri {
|
||||||
|
return Some(self.value_at(ordinal as usize - 1));
|
||||||
|
}
|
||||||
|
pos = (pos + 1) & (layout.capacity - 1);
|
||||||
|
}
|
||||||
|
self.lookup(uri)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn directories(&self) -> Vec<&str> {
|
||||||
|
if let Some(layout) = &self.hash_layout {
|
||||||
|
return layout
|
||||||
|
.dirs
|
||||||
|
.iter()
|
||||||
|
.map(|(a, b)| {
|
||||||
|
// SAFETY: v2 open validated immutable ranges and UTF-8.
|
||||||
|
unsafe { std::str::from_utf8_unchecked(&self.bytes[*a..*b]) }
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
(0..self.count).map(|n| directory(self.uri_at(n))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn offset(&self, n: usize) -> Result<usize, String> {
|
||||||
|
usize::try_from(u64::from_le_bytes(
|
||||||
|
self.bytes[16 + n * 8..24 + n * 8].try_into().unwrap(),
|
||||||
|
))
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record(&self, n: usize) -> Result<(&str, Option<CurrentRepoEntryRef<'_>>), String> {
|
||||||
|
let start = self.offset(n)?;
|
||||||
|
let end = self.offset(n + 1)?;
|
||||||
|
let b = self
|
||||||
|
.bytes
|
||||||
|
.get(start..end)
|
||||||
|
.ok_or("segment record bounds invalid")?;
|
||||||
|
if b.len() < FIXED || b[0] > 2 {
|
||||||
|
return Err("segment record invalid".into());
|
||||||
|
}
|
||||||
|
let uri_len = u32::from_le_bytes(b[97..101].try_into().unwrap()) as usize;
|
||||||
|
let type_tag = u32::from_le_bytes(b[101..105].try_into().unwrap());
|
||||||
|
let type_len = if type_tag == u32::MAX {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
type_tag as usize
|
||||||
|
};
|
||||||
|
if FIXED
|
||||||
|
.checked_add(uri_len)
|
||||||
|
.and_then(|n| n.checked_add(type_len))
|
||||||
|
!= Some(b.len())
|
||||||
|
{
|
||||||
|
return Err("segment string bounds invalid".into());
|
||||||
|
}
|
||||||
|
let uri = std::str::from_utf8(&b[FIXED..FIXED + uri_len]).map_err(|e| e.to_string())?;
|
||||||
|
let kind = std::str::from_utf8(&b[FIXED + uri_len..]).map_err(|e| e.to_string())?;
|
||||||
|
let hash = std::str::from_utf8(&b[33..97]).map_err(|e| e.to_string())?;
|
||||||
|
if !hash.as_bytes().iter().all(u8::is_ascii_hexdigit) {
|
||||||
|
return Err("segment hash invalid".into());
|
||||||
|
}
|
||||||
|
let mut decoded = [0; 32];
|
||||||
|
hex::decode_to_slice(hash, &mut decoded).map_err(|e| e.to_string())?;
|
||||||
|
if decoded != b[1..33] {
|
||||||
|
return Err("segment binary/hex hashes disagree".into());
|
||||||
|
}
|
||||||
|
Ok((
|
||||||
|
uri,
|
||||||
|
(b[0] != 0).then(|| CurrentRepoEntryRef {
|
||||||
|
current_hash: b[1..33].try_into().unwrap(),
|
||||||
|
current_hash_hex: hash,
|
||||||
|
repository_source: "", // supplied by the source view
|
||||||
|
object_type: (type_tag != u32::MAX).then_some(kind),
|
||||||
|
state: if b[0] == 2 {
|
||||||
|
RepositoryViewState::Replaced
|
||||||
|
} else {
|
||||||
|
RepositoryViewState::Present
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookup(&self, uri: &str) -> Option<Option<CurrentRepoEntryRef<'_>>> {
|
||||||
|
let (mut lo, mut hi) = (0, self.count);
|
||||||
|
while lo < hi {
|
||||||
|
let mid = lo + (hi - lo) / 2;
|
||||||
|
match self.uri_at(mid).cmp(uri) {
|
||||||
|
std::cmp::Ordering::Less => lo = mid + 1,
|
||||||
|
std::cmp::Ordering::Greater => hi = mid,
|
||||||
|
std::cmp::Ordering::Equal => return Some(self.value_at(mid)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_bytes(&self, n: usize) -> &[u8] {
|
||||||
|
let start = self.offset(n).expect("validated offset");
|
||||||
|
let end = self.offset(n + 1).expect("validated offset");
|
||||||
|
&self.bytes[start..end]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn uri_at(&self, n: usize) -> &str {
|
||||||
|
let b = self.record_bytes(n);
|
||||||
|
let len = u32::from_le_bytes(b[97..101].try_into().unwrap()) as usize;
|
||||||
|
// SAFETY: open() checked the entire table and every UTF-8 string
|
||||||
|
// before publishing this immutable mapping.
|
||||||
|
unsafe { std::str::from_utf8_unchecked(&b[FIXED..FIXED + len]) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value_at(&self, n: usize) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
let b = self.record_bytes(n);
|
||||||
|
if b[0] == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let len = u32::from_le_bytes(b[97..101].try_into().unwrap()) as usize;
|
||||||
|
let type_tag = u32::from_le_bytes(b[101..105].try_into().unwrap());
|
||||||
|
// SAFETY: open() validated these exact slices and files are immutable.
|
||||||
|
let (hash, kind) = unsafe {
|
||||||
|
(
|
||||||
|
std::str::from_utf8_unchecked(&b[33..97]),
|
||||||
|
std::str::from_utf8_unchecked(&b[FIXED + len..]),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
Some(CurrentRepoEntryRef {
|
||||||
|
current_hash: b[1..33].try_into().unwrap(),
|
||||||
|
current_hash_hex: hash,
|
||||||
|
repository_source: "",
|
||||||
|
object_type: (type_tag != u32::MAX).then_some(kind),
|
||||||
|
state: if b[0] == 2 {
|
||||||
|
RepositoryViewState::Replaced
|
||||||
|
} else {
|
||||||
|
RepositoryViewState::Present
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) struct RepoView {
|
||||||
|
pub source: String,
|
||||||
|
segments: Vec<Arc<Segment>>,
|
||||||
|
dirty: HashMap<String, Option<CurrentRepoEntry>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RepoView {
|
||||||
|
pub fn get(&self, uri: &str) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
self.get_hashed(uri, hash64(uri.as_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_hashed(&self, uri: &str, hash: u64) -> Option<CurrentRepoEntryRef<'_>> {
|
||||||
|
let mut value = if let Some(value) = self.dirty.get(uri) {
|
||||||
|
value.as_ref().map(CurrentRepoEntryRef::from)
|
||||||
|
} else {
|
||||||
|
self.segments
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|s| s.lookup_hashed(uri, hash))
|
||||||
|
.flatten()
|
||||||
|
}?;
|
||||||
|
value.repository_source = &self.source;
|
||||||
|
Some(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uris(&self) -> Vec<&str> {
|
||||||
|
let mut uris: Vec<_> = self.entries().into_iter().map(|(uri, _)| uri).collect();
|
||||||
|
uris.sort_unstable();
|
||||||
|
uris
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn entries(&self) -> Vec<(&str, CurrentRepoEntryRef<'_>)> {
|
||||||
|
// Full output traversal remains necessary, but only incremental segments
|
||||||
|
// enter a temporary HashMap; the large base is scanned sequentially.
|
||||||
|
let mut changes: HashMap<&str, Option<CurrentRepoEntryRef<'_>>> = HashMap::new();
|
||||||
|
for segment in self.segments.iter().skip(1) {
|
||||||
|
for n in 0..segment.count {
|
||||||
|
changes.insert(segment.uri_at(n), segment.value_at(n));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (uri, value) in &self.dirty {
|
||||||
|
changes.insert(uri, value.as_ref().map(CurrentRepoEntryRef::from));
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if let Some(base) = self.segments.first() {
|
||||||
|
out.reserve(base.count + changes.len());
|
||||||
|
for n in 0..base.count {
|
||||||
|
let uri = base.uri_at(n);
|
||||||
|
if !changes.contains_key(uri)
|
||||||
|
&& let Some(value) = base.value_at(n)
|
||||||
|
{
|
||||||
|
out.push((uri, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.extend(
|
||||||
|
changes
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(uri, value)| value.map(|value| (uri, value))),
|
||||||
|
);
|
||||||
|
for (_, value) in &mut out {
|
||||||
|
value.repository_source = &self.source;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn directories(&self) -> Vec<&str> {
|
||||||
|
let mut dirs: Vec<_> = self
|
||||||
|
.segments
|
||||||
|
.iter()
|
||||||
|
.flat_map(|s| s.directories())
|
||||||
|
.chain(self.dirty.keys().map(|uri| directory(uri)))
|
||||||
|
.collect();
|
||||||
|
dirs.sort_unstable();
|
||||||
|
dirs.dedup();
|
||||||
|
dirs
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn routes(&self) -> Vec<String> {
|
||||||
|
let mut routes: Vec<_> = self
|
||||||
|
.directories()
|
||||||
|
.into_iter()
|
||||||
|
.map(|dir| module_prefix(dir).to_owned())
|
||||||
|
.collect();
|
||||||
|
routes.sort_unstable();
|
||||||
|
routes.dedup();
|
||||||
|
routes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn module_prefix(uri: &str) -> &str {
|
||||||
|
let start = uri.find("://").map_or(0, |n| n + 3);
|
||||||
|
let end = uri[start..]
|
||||||
|
.match_indices('/')
|
||||||
|
.nth(1)
|
||||||
|
.map_or(uri.len(), |(n, _)| start + n + 1);
|
||||||
|
&uri[..end]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Serialize, Deserialize)]
|
||||||
|
struct Manifest {
|
||||||
|
version: u32,
|
||||||
|
identity: String,
|
||||||
|
sequence: u64,
|
||||||
|
sources: BTreeMap<String, Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Serialize)]
|
||||||
|
pub(crate) struct Stats {
|
||||||
|
pub mmap_views: u64,
|
||||||
|
pub db_rebuilds: u64,
|
||||||
|
pub loaded_files: u64,
|
||||||
|
pub mapped_bytes: u64,
|
||||||
|
pub written_bytes: u64,
|
||||||
|
pub dirty_records: u64,
|
||||||
|
pub persist_ms: u64,
|
||||||
|
pub invalidations: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Source {
|
||||||
|
view: Option<RepoView>,
|
||||||
|
files: Vec<String>,
|
||||||
|
touched: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Manager {
|
||||||
|
dir: PathBuf,
|
||||||
|
identity: String,
|
||||||
|
manifest: Manifest,
|
||||||
|
sources: HashMap<String, Source>,
|
||||||
|
pub stats: Stats,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Manager {
|
||||||
|
pub fn new(db: &Path, sequence: u64) -> Self {
|
||||||
|
let dir = db.with_file_name(format!(
|
||||||
|
"{}.current-repo-index",
|
||||||
|
db.file_name().unwrap_or_default().to_string_lossy()
|
||||||
|
));
|
||||||
|
let identity = fs::read_to_string(db.join("IDENTITY")).unwrap_or_default();
|
||||||
|
let manifest = fs::read(dir.join("manifest.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|b| serde_json::from_slice::<Manifest>(&b).ok())
|
||||||
|
.filter(|m| {
|
||||||
|
m.version == 2
|
||||||
|
&& !identity.is_empty()
|
||||||
|
&& m.identity == identity
|
||||||
|
&& m.sequence == sequence
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Self {
|
||||||
|
dir,
|
||||||
|
identity,
|
||||||
|
manifest,
|
||||||
|
sources: HashMap::new(),
|
||||||
|
stats: Stats::default(),
|
||||||
|
enabled: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn source(&mut self, uri: &str) -> &mut Source {
|
||||||
|
if !self.sources.contains_key(uri) {
|
||||||
|
let files = self.manifest.sources.get(uri).cloned().unwrap_or_default();
|
||||||
|
let loaded: Result<Vec<_>, _> = files
|
||||||
|
.iter()
|
||||||
|
.map(|hash| {
|
||||||
|
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
return Err("invalid segment filename".into());
|
||||||
|
}
|
||||||
|
Segment::open_current(&self.dir.join(format!("{hash}.idx")), hash).map(Arc::new)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let view = match loaded {
|
||||||
|
Ok(segments) if !files.is_empty() => {
|
||||||
|
self.stats.loaded_files += segments.len() as u64;
|
||||||
|
self.stats.mapped_bytes +=
|
||||||
|
segments.iter().map(|s| s.bytes.len() as u64).sum::<u64>();
|
||||||
|
Some(RepoView {
|
||||||
|
source: uri.into(),
|
||||||
|
segments,
|
||||||
|
dirty: HashMap::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if !files.is_empty() {
|
||||||
|
self.stats.invalidations += 1;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.sources.insert(
|
||||||
|
uri.into(),
|
||||||
|
Source {
|
||||||
|
view,
|
||||||
|
files,
|
||||||
|
touched: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.sources.get_mut(uri).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn view(&mut self, uri: &str) -> Option<RepoView> {
|
||||||
|
if !self.enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let source = self.source(uri);
|
||||||
|
source.touched = true;
|
||||||
|
let view = source.view.clone();
|
||||||
|
if view.is_some() {
|
||||||
|
self.stats.mmap_views += 1;
|
||||||
|
}
|
||||||
|
view
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn touch(&mut self, uri: &str) {
|
||||||
|
if self.enabled {
|
||||||
|
self.source(uri).touched = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record(&mut self, records: &[RrdpSourceMemberRecord]) {
|
||||||
|
if !self.enabled {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for record in records {
|
||||||
|
let source = self.source(&record.notify_uri);
|
||||||
|
source.touched = true;
|
||||||
|
if let Some(view) = source.view.as_mut() {
|
||||||
|
view.dirty
|
||||||
|
.insert(record.rsync_uri.clone(), member_entry(record));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn persist(
|
||||||
|
&mut self,
|
||||||
|
sequence: u64,
|
||||||
|
mut rebuild: impl FnMut(&str) -> Result<Vec<RrdpSourceMemberRecord>, String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if !self.enabled {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let started = Instant::now();
|
||||||
|
fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?;
|
||||||
|
let mut manifest = Manifest {
|
||||||
|
version: 2,
|
||||||
|
identity: self.identity.clone(),
|
||||||
|
sequence,
|
||||||
|
sources: self.manifest.sources.clone(),
|
||||||
|
};
|
||||||
|
for (uri, source) in &mut self.sources {
|
||||||
|
if !source.touched {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if source.view.is_none() {
|
||||||
|
let rows = rebuild(uri)?;
|
||||||
|
let entries = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| (r.rsync_uri.clone(), member_entry(&r)))
|
||||||
|
.collect();
|
||||||
|
let (hash, bytes) = write_current_segment(&self.dir, &entries)?;
|
||||||
|
source.files = vec![hash];
|
||||||
|
self.stats.db_rebuilds += 1;
|
||||||
|
self.stats.written_bytes += bytes;
|
||||||
|
} else if let Some(view) = source.view.as_ref().filter(|v| !v.dirty.is_empty()) {
|
||||||
|
self.stats.dirty_records += view.dirty.len() as u64;
|
||||||
|
let compact = source.files.len() >= MAX_SEGMENTS;
|
||||||
|
let entries = if compact {
|
||||||
|
view.entries()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(uri, value)| (uri.into(), Some(value.to_owned())))
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
view.dirty
|
||||||
|
.iter()
|
||||||
|
.map(|(uri, value)| (uri.clone(), value.clone()))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let (hash, bytes) = write_current_segment(&self.dir, &entries)?;
|
||||||
|
if compact {
|
||||||
|
source.files.clear();
|
||||||
|
}
|
||||||
|
source.files.push(hash);
|
||||||
|
self.stats.written_bytes += bytes;
|
||||||
|
}
|
||||||
|
manifest.sources.insert(uri.clone(), source.files.clone());
|
||||||
|
}
|
||||||
|
atomic_write(
|
||||||
|
&self.dir.join("manifest.json"),
|
||||||
|
&serde_json::to_vec(&manifest).map_err(|e| e.to_string())?,
|
||||||
|
)?;
|
||||||
|
// Unlink obsolete immutable segments only after the new manifest is durable.
|
||||||
|
// Existing Arc mappings retain their old inodes until the last reader exits.
|
||||||
|
let live: std::collections::HashSet<_> = manifest
|
||||||
|
.sources
|
||||||
|
.values()
|
||||||
|
.flatten()
|
||||||
|
.map(|hash| format!("{hash}.idx"))
|
||||||
|
.collect();
|
||||||
|
for entry in fs::read_dir(&self.dir).map_err(|e| e.to_string())? {
|
||||||
|
let entry = entry.map_err(|e| e.to_string())?;
|
||||||
|
let name = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
if name.ends_with(".idx") && !live.contains(&name) {
|
||||||
|
let _ = fs::remove_file(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.manifest = manifest;
|
||||||
|
self.stats.persist_ms = started.elapsed().as_millis() as u64;
|
||||||
|
atomic_write(
|
||||||
|
&self.dir.join("stats.json"),
|
||||||
|
&serde_json::to_vec_pretty(&self.stats).map_err(|e| e.to_string())?,
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn member_entry(record: &RrdpSourceMemberRecord) -> Option<CurrentRepoEntry> {
|
||||||
|
if !record.present {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let hash = record
|
||||||
|
.current_hash
|
||||||
|
.as_ref()
|
||||||
|
.expect("validated present member hash")
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
Some(CurrentRepoEntry {
|
||||||
|
current_hash: super::decode_sha256_hex_32(&hash).expect("validated hash"),
|
||||||
|
current_hash_hex: hash,
|
||||||
|
repository_source: record.notify_uri.clone(),
|
||||||
|
object_type: record.object_type.clone(),
|
||||||
|
state: RepositoryViewState::Present,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_segment(
|
||||||
|
dir: &Path,
|
||||||
|
entries: &BTreeMap<String, Option<CurrentRepoEntry>>,
|
||||||
|
) -> Result<(String, u64), String> {
|
||||||
|
publish_segment(dir, &segment_bytes(entries)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn segment_bytes(entries: &BTreeMap<String, Option<CurrentRepoEntry>>) -> Result<Vec<u8>, String> {
|
||||||
|
let table_end = 16 + (entries.len() + 1) * 8;
|
||||||
|
let mut bytes = vec![0; table_end];
|
||||||
|
bytes[..8].copy_from_slice(MAGIC);
|
||||||
|
bytes[8..16].copy_from_slice(&(entries.len() as u64).to_le_bytes());
|
||||||
|
for (n, (uri, entry)) in entries.iter().enumerate() {
|
||||||
|
let offset = bytes.len() as u64;
|
||||||
|
bytes[16 + n * 8..24 + n * 8].copy_from_slice(&offset.to_le_bytes());
|
||||||
|
let kind = entry
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|e| e.object_type.as_deref())
|
||||||
|
.unwrap_or("");
|
||||||
|
bytes.push(entry.as_ref().map_or(0, |e| {
|
||||||
|
if e.state == RepositoryViewState::Replaced {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
bytes.extend_from_slice(&entry.as_ref().map_or([0; 32], |e| e.current_hash));
|
||||||
|
bytes.extend_from_slice(
|
||||||
|
entry
|
||||||
|
.as_ref()
|
||||||
|
.map_or(
|
||||||
|
"0000000000000000000000000000000000000000000000000000000000000000",
|
||||||
|
|e| e.current_hash_hex.as_str(),
|
||||||
|
)
|
||||||
|
.as_bytes(),
|
||||||
|
);
|
||||||
|
bytes.extend_from_slice(
|
||||||
|
&u32::try_from(uri.len())
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.to_le_bytes(),
|
||||||
|
);
|
||||||
|
let type_tag = if entry
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|e| e.object_type.as_ref())
|
||||||
|
.is_none()
|
||||||
|
{
|
||||||
|
u32::MAX
|
||||||
|
} else {
|
||||||
|
u32::try_from(kind.len()).map_err(|e| e.to_string())?
|
||||||
|
};
|
||||||
|
bytes.extend_from_slice(&type_tag.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(uri.as_bytes());
|
||||||
|
bytes.extend_from_slice(kind.as_bytes());
|
||||||
|
}
|
||||||
|
let n = entries.len();
|
||||||
|
let len = bytes.len() as u64;
|
||||||
|
bytes[16 + n * 8..24 + n * 8].copy_from_slice(&len.to_le_bytes());
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_current_segment(
|
||||||
|
dir: &Path,
|
||||||
|
entries: &BTreeMap<String, Option<CurrentRepoEntry>>,
|
||||||
|
) -> Result<(String, u64), String> {
|
||||||
|
let bytes = segment_bytes(entries)?;
|
||||||
|
let bytes = format_v2::append_index(bytes, entries.keys().map(String::as_str))?;
|
||||||
|
publish_segment(dir, &bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_segment(dir: &Path, bytes: &[u8]) -> Result<(String, u64), String> {
|
||||||
|
let len = bytes.len() as u64;
|
||||||
|
let digest = hex::encode(Sha256::digest(&bytes));
|
||||||
|
let path = dir.join(format!("{digest}.idx"));
|
||||||
|
if fs::read(&path)
|
||||||
|
.ok()
|
||||||
|
.is_none_or(|existing| existing.as_slice() != bytes)
|
||||||
|
{
|
||||||
|
atomic_write(&path, &bytes)?;
|
||||||
|
}
|
||||||
|
Ok((digest, len))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||||
|
let nonce = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.as_nanos();
|
||||||
|
let temp = path.with_extension(format!("tmp-{}-{nonce}", std::process::id()));
|
||||||
|
let result = (|| {
|
||||||
|
let mut file = OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&temp)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
file.write_all(bytes)
|
||||||
|
.and_then(|_| file.sync_all())
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
fs::rename(&temp, path).map_err(|e| e.to_string())?;
|
||||||
|
File::open(path.parent().ok_or("index path missing parent")?)
|
||||||
|
.and_then(|d| d.sync_all())
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
})();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = fs::remove_file(temp);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::current_repo_index::CurrentRepoIndex;
|
||||||
|
use crate::storage::{RepositoryViewEntry, RocksStore};
|
||||||
|
|
||||||
|
fn member(uri: &str, value: Option<u8>) -> RrdpSourceMemberRecord {
|
||||||
|
RrdpSourceMemberRecord {
|
||||||
|
notify_uri: "https://test/notification.xml".into(),
|
||||||
|
rsync_uri: format!("rsync://test/repo/{uri}"),
|
||||||
|
current_hash: value.map(|n| hex::encode([n; 32])),
|
||||||
|
object_type: Some("roa".into()),
|
||||||
|
present: value.is_some(),
|
||||||
|
last_confirmed_session_id: "session".into(),
|
||||||
|
last_confirmed_serial: 1,
|
||||||
|
last_changed_at: crate::storage::PackTime {
|
||||||
|
rfc3339_utc: "2026-11-13T00:00:00Z".into(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn database() -> (tempfile::TempDir, PathBuf) {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let db = temp.path().join("db");
|
||||||
|
fs::create_dir(&db).unwrap();
|
||||||
|
fs::write(db.join("IDENTITY"), "test-db").unwrap();
|
||||||
|
(temp, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seed(db: &Path, records: &[RrdpSourceMemberRecord], sequence: u64) {
|
||||||
|
let mut manager = Manager::new(db, 0);
|
||||||
|
manager.record(records);
|
||||||
|
manager.persist(sequence, |_| Ok(records.to_vec())).unwrap();
|
||||||
|
assert_eq!(manager.stats.db_rebuilds, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_roundtrip_borrowed_lookup_overlay_and_compaction() {
|
||||||
|
let (_temp, db) = database();
|
||||||
|
let a = member("a.roa", Some(1));
|
||||||
|
let b = member("b.roa", Some(2));
|
||||||
|
let source = a.notify_uri.clone();
|
||||||
|
seed(&db, &[a.clone(), b.clone()], 1);
|
||||||
|
for seq in 1..=10 {
|
||||||
|
let mut manager = Manager::new(&db, seq);
|
||||||
|
let before = manager.view(&source).unwrap();
|
||||||
|
let previous_hash = before.get(&a.rsync_uri).unwrap().current_hash;
|
||||||
|
if seq == 1 {
|
||||||
|
assert_eq!(before.get(&a.rsync_uri).unwrap().current_hash, [1; 32]);
|
||||||
|
}
|
||||||
|
manager.record(&[
|
||||||
|
member("a.roa", Some((seq + 2) as u8)),
|
||||||
|
member("b.roa", None),
|
||||||
|
member("c.roa", Some(3)),
|
||||||
|
]);
|
||||||
|
let view = manager.view(&source).unwrap();
|
||||||
|
assert!(view.get(&b.rsync_uri).is_none());
|
||||||
|
assert_eq!(view.uris().len(), 2);
|
||||||
|
assert_eq!(view.routes(), vec!["rsync://test/repo/"]);
|
||||||
|
manager
|
||||||
|
.persist(seq + 1, |_| panic!("warm path scanned DB"))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
before.get(&a.rsync_uri).unwrap().current_hash,
|
||||||
|
previous_hash,
|
||||||
|
"old Arc mapping survives compaction/unlink"
|
||||||
|
);
|
||||||
|
assert_eq!(manager.stats.db_rebuilds, 0);
|
||||||
|
}
|
||||||
|
let mut final_manager = Manager::new(&db, 11);
|
||||||
|
let view = final_manager.view(&source).unwrap();
|
||||||
|
assert_eq!(view.get(&a.rsync_uri).unwrap().current_hash, [12; 32]);
|
||||||
|
assert!(view.get(&b.rsync_uri).is_none());
|
||||||
|
assert!(view.get("rsync://unknown/repo/a.roa").is_none());
|
||||||
|
assert!(final_manager.manifest.sources[&source].len() <= MAX_SEGMENTS);
|
||||||
|
let file_count = fs::read_dir(&final_manager.dir)
|
||||||
|
.unwrap()
|
||||||
|
.filter(|p| {
|
||||||
|
p.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.path()
|
||||||
|
.extension()
|
||||||
|
.is_some_and(|e| e == "idx")
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
assert_eq!(file_count, final_manager.manifest.sources[&source].len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_rejects_stale_identity_sequence_and_uncommitted_changes() {
|
||||||
|
let (_temp, db) = database();
|
||||||
|
let a = member("a.roa", Some(1));
|
||||||
|
seed(&db, std::slice::from_ref(&a), 10);
|
||||||
|
assert!(Manager::new(&db, 9).view(&a.notify_uri).is_none());
|
||||||
|
assert!(Manager::new(&db, 11).view(&a.notify_uri).is_none());
|
||||||
|
let mut interrupted = Manager::new(&db, 10);
|
||||||
|
interrupted.record(&[member("a.roa", None)]);
|
||||||
|
drop(interrupted);
|
||||||
|
assert!(Manager::new(&db, 11).view(&a.notify_uri).is_none());
|
||||||
|
fs::write(db.join("IDENTITY"), "different-db").unwrap();
|
||||||
|
assert!(Manager::new(&db, 10).view(&a.notify_uri).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_corruption_missing_segment_and_truncated_table_fall_back_and_repair() {
|
||||||
|
let (_temp, db) = database();
|
||||||
|
let a = member("a.roa", Some(1));
|
||||||
|
seed(&db, std::slice::from_ref(&a), 1);
|
||||||
|
let mut manager = Manager::new(&db, 1);
|
||||||
|
let hash = &manager.manifest.sources[&a.notify_uri][0];
|
||||||
|
let path = manager.dir.join(format!("{hash}.idx"));
|
||||||
|
// Corrupt before any process maps the file.
|
||||||
|
fs::write(&path, "broken").unwrap();
|
||||||
|
assert!(manager.view(&a.notify_uri).is_none());
|
||||||
|
manager.persist(2, |_| Ok(vec![a.clone()])).unwrap();
|
||||||
|
assert!(Manager::new(&db, 2).view(&a.notify_uri).is_some());
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
assert!(Manager::new(&db, 2).view(&a.notify_uri).is_none());
|
||||||
|
let invalid = manager.dir.join("invalid");
|
||||||
|
let mut bytes = MAGIC.to_vec();
|
||||||
|
bytes.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||||
|
bytes.extend_from_slice(&0u64.to_le_bytes());
|
||||||
|
fs::write(&invalid, &bytes).unwrap();
|
||||||
|
assert!(Segment::open(&invalid, &hex::encode(Sha256::digest(&bytes))).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_install_preserves_last_writer_ownership_and_withdrawals() {
|
||||||
|
let (_temp, db) = database();
|
||||||
|
let a = member("a.roa", Some(1));
|
||||||
|
seed(&db, std::slice::from_ref(&a), 1);
|
||||||
|
let view = Manager::new(&db, 1).view(&a.notify_uri).unwrap();
|
||||||
|
let mut index = CurrentRepoIndex::new();
|
||||||
|
index.install_mmap(view.clone());
|
||||||
|
assert_eq!(index.snapshot_objects().len(), 1);
|
||||||
|
let mut change = RepositoryViewEntry {
|
||||||
|
rsync_uri: a.rsync_uri.clone(),
|
||||||
|
current_hash: Some(hex::encode([2; 32])),
|
||||||
|
repository_source: Some("rsync://test/repo/".into()),
|
||||||
|
object_type: None,
|
||||||
|
state: RepositoryViewState::Present,
|
||||||
|
};
|
||||||
|
index
|
||||||
|
.apply_repository_view_entries(&[change.clone()])
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
index.get_by_uri(&a.rsync_uri).unwrap().current_hash,
|
||||||
|
[2; 32]
|
||||||
|
);
|
||||||
|
index.install_mmap(view); // A later successful repo hydration owns this URI.
|
||||||
|
assert_eq!(
|
||||||
|
index.get_by_uri(&a.rsync_uri).unwrap().current_hash,
|
||||||
|
[1; 32]
|
||||||
|
);
|
||||||
|
change.state = RepositoryViewState::Withdrawn;
|
||||||
|
index.apply_repository_view_entries(&[change]).unwrap();
|
||||||
|
assert!(index.get_by_uri(&a.rsync_uri).is_none());
|
||||||
|
assert_eq!(index.active_uri_count(), 0);
|
||||||
|
assert_eq!(index.scope_count(), 0);
|
||||||
|
index.clear();
|
||||||
|
assert!(index.snapshot_objects().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_real_store_member_writes_and_external_writes_invalidate() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let db = temp.path().join("db");
|
||||||
|
let a = member("a.roa", Some(1));
|
||||||
|
{
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
store.put_rrdp_source_member_record(&a).unwrap();
|
||||||
|
store.persist_current_repo_mmap().unwrap();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
assert!(store.current_repo_mmap_view(&a.notify_uri).is_some());
|
||||||
|
store
|
||||||
|
.put_projection_batch(&[], &[member("a.roa", Some(2))], &[])
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
store
|
||||||
|
.current_repo_mmap_view(&a.notify_uri)
|
||||||
|
.unwrap()
|
||||||
|
.get(&a.rsync_uri)
|
||||||
|
.unwrap()
|
||||||
|
.current_hash,
|
||||||
|
[2; 32]
|
||||||
|
);
|
||||||
|
store.persist_current_repo_mmap().unwrap();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
assert!(store.current_repo_mmap_view(&a.notify_uri).is_some());
|
||||||
|
store
|
||||||
|
.put_rrdp_source_member_record(&member("a.roa", Some(3)))
|
||||||
|
.unwrap(); /* crash before persist */
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
assert!(store.current_repo_mmap_view(&a.notify_uri).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn v2_view(source: &str, rows: &[(&str, Option<u8>)]) -> RepoView {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let entries = rows
|
||||||
|
.iter()
|
||||||
|
.map(|(uri, n)| {
|
||||||
|
let mut record = member("unused", *n);
|
||||||
|
record.rsync_uri = (*uri).into();
|
||||||
|
record.notify_uri = source.into();
|
||||||
|
((*uri).to_owned(), member_entry(&record))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let (hash, _) = write_current_segment(dir.path(), &entries).unwrap();
|
||||||
|
RepoView {
|
||||||
|
source: source.into(),
|
||||||
|
segments: vec![Arc::new(
|
||||||
|
Segment::open_current(&dir.path().join(format!("{hash}.idx")), &hash).unwrap(),
|
||||||
|
)],
|
||||||
|
dirty: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn production_v2_routes_shared_directory_budget_and_source_replacement() {
|
||||||
|
let uri = "rsync://host/module/ca/a.roa";
|
||||||
|
let other = "rsync://host/module/other/b.roa";
|
||||||
|
for budget in [0, uri.len() + "old".len() + 128, super::super::ROUTE_BUDGET] {
|
||||||
|
let mut index = CurrentRepoIndex::new();
|
||||||
|
index.install_mmap_with_budget(
|
||||||
|
v2_view("old", &[(uri, Some(1)), (other, Some(3))]),
|
||||||
|
budget,
|
||||||
|
);
|
||||||
|
index.install_mmap_with_budget(v2_view("new", &[(uri, Some(2))]), budget);
|
||||||
|
assert_eq!(index.get_by_uri(uri).unwrap().current_hash, [2; 32]);
|
||||||
|
assert_eq!(index.get_by_uri(other).unwrap().current_hash, [3; 32]);
|
||||||
|
assert!(
|
||||||
|
index
|
||||||
|
.get_by_uri("rsync://host/module/missing.roa")
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
// A source-local tombstone cannot erase another source's entry.
|
||||||
|
index.install_mmap_with_budget(v2_view("new", &[(uri, None)]), budget);
|
||||||
|
assert_eq!(index.get_by_uri(uri).unwrap().current_hash, [1; 32]);
|
||||||
|
index.install_mmap_with_budget(
|
||||||
|
v2_view("new", &[("rsync://different/new/c.roa", Some(4))]),
|
||||||
|
budget,
|
||||||
|
);
|
||||||
|
assert_eq!(index.routes["rsync://host/module/"], vec!["old"]);
|
||||||
|
assert!(!index.directories.contains_key("rsync://host/module/"));
|
||||||
|
assert_eq!(index.get_by_uri(uri).unwrap().repository_source, "old");
|
||||||
|
index.clear();
|
||||||
|
assert_eq!(index.route_bytes, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn production_v2_explicit_tombstone_and_later_source_generation() {
|
||||||
|
let uri = "rsync://host/module/ca/a.roa";
|
||||||
|
let mut index = CurrentRepoIndex::new();
|
||||||
|
index.install_mmap(v2_view("a", &[(uri, Some(1))]));
|
||||||
|
index.install_mmap(v2_view("b", &[(uri, Some(2))]));
|
||||||
|
index
|
||||||
|
.apply_repository_view_entries(&[RepositoryViewEntry {
|
||||||
|
rsync_uri: uri.into(),
|
||||||
|
current_hash: None,
|
||||||
|
repository_source: Some("a".into()),
|
||||||
|
object_type: None,
|
||||||
|
state: RepositoryViewState::Withdrawn,
|
||||||
|
}])
|
||||||
|
.unwrap();
|
||||||
|
assert!(index.get_by_uri(uri).is_none());
|
||||||
|
index.install_mmap(v2_view("a", &[(uri, Some(4))]));
|
||||||
|
assert_eq!(index.get_by_uri(uri).unwrap().current_hash, [4; 32]);
|
||||||
|
assert_eq!(index.snapshot_objects()[0].repository_source, "a");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn production_v2_rejects_v1_manifest_and_v1_segment() {
|
||||||
|
let (_temp, db) = database();
|
||||||
|
let record = member("a.roa", Some(1));
|
||||||
|
seed(&db, std::slice::from_ref(&record), 1);
|
||||||
|
let manager = Manager::new(&db, 1);
|
||||||
|
let path = manager.dir.join("manifest.json");
|
||||||
|
let mut manifest: serde_json::Value =
|
||||||
|
serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||||
|
manifest["version"] = 1.into();
|
||||||
|
atomic_write(&path, &serde_json::to_vec(&manifest).unwrap()).unwrap();
|
||||||
|
assert!(Manager::new(&db, 1).view(&record.notify_uri).is_none());
|
||||||
|
let entries = [(record.rsync_uri.clone(), member_entry(&record))]
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
let (hash, _) = write_segment(&manager.dir, &entries).unwrap();
|
||||||
|
assert!(Segment::open_current(&manager.dir.join(format!("{hash}.idx")), &hash).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -381,6 +381,7 @@ pub fn run(argv: &[String]) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let store = Arc::new(RocksStore::open(&scratch).map_err(|e| e.to_string())?);
|
let store = Arc::new(RocksStore::open(&scratch).map_err(|e| e.to_string())?);
|
||||||
|
store.disable_current_repo_mmap();
|
||||||
let overlay = store
|
let overlay = store
|
||||||
.import_frozen_repository_for_benchmark(&source_state)
|
.import_frozen_repository_for_benchmark(&source_state)
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ pub struct ChildCertificateCacheMmapLookup {
|
|||||||
|
|
||||||
pub struct RocksStore {
|
pub struct RocksStore {
|
||||||
db: DB,
|
db: DB,
|
||||||
|
current_repo_mmap: Mutex<crate::current_repo_index::mmap::Manager>,
|
||||||
external_raw_store: Option<ExternalRawStoreDb>,
|
external_raw_store: Option<ExternalRawStoreDb>,
|
||||||
external_repo_bytes: Option<ExternalRepoBytesDb>,
|
external_repo_bytes: Option<ExternalRepoBytesDb>,
|
||||||
publication_point_cache_index_dir: PathBuf,
|
publication_point_cache_index_dir: PathBuf,
|
||||||
@@ -2966,8 +2967,13 @@ impl RocksStore {
|
|||||||
)
|
)
|
||||||
.map_err(|e| StorageError::RocksDb(e.to_string()))?;
|
.map_err(|e| StorageError::RocksDb(e.to_string()))?;
|
||||||
|
|
||||||
|
let current_repo_mmap = Mutex::new(crate::current_repo_index::mmap::Manager::new(
|
||||||
|
path,
|
||||||
|
db.latest_sequence_number(),
|
||||||
|
));
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
db,
|
db,
|
||||||
|
current_repo_mmap,
|
||||||
external_raw_store: None,
|
external_raw_store: None,
|
||||||
external_repo_bytes: None,
|
external_repo_bytes: None,
|
||||||
publication_point_cache_index_dir: default_pp_cache_index_dir(path),
|
publication_point_cache_index_dir: default_pp_cache_index_dir(path),
|
||||||
@@ -3189,7 +3195,12 @@ impl RocksStore {
|
|||||||
batch.put_cf(owner_cf, key.as_bytes(), value);
|
batch.put_cf(owner_cf, key.as_bytes(), value);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.write_batch(batch)
|
self.write_batch(batch)?;
|
||||||
|
self.current_repo_mmap
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| StorageError::RocksDb(e.to_string()))?
|
||||||
|
.record(member_records);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_repository_view_entries_with_prefix(
|
pub fn list_repository_view_entries_with_prefix(
|
||||||
@@ -4674,9 +4685,43 @@ impl RocksStore {
|
|||||||
self.db
|
self.db
|
||||||
.put_cf(cf, key.as_bytes(), value)
|
.put_cf(cf, key.as_bytes(), value)
|
||||||
.map_err(|e| StorageError::RocksDb(e.to_string()))?;
|
.map_err(|e| StorageError::RocksDb(e.to_string()))?;
|
||||||
|
self.current_repo_mmap
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| StorageError::RocksDb(e.to_string()))?
|
||||||
|
.record(std::slice::from_ref(record));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn current_repo_mmap_view(
|
||||||
|
&self,
|
||||||
|
source: &str,
|
||||||
|
) -> Option<crate::current_repo_index::mmap::RepoView> {
|
||||||
|
self.current_repo_mmap.lock().ok()?.view(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn touch_current_repo_mmap_source(&self, source: &str) {
|
||||||
|
if let Ok(mut manager) = self.current_repo_mmap.lock() {
|
||||||
|
manager.touch(source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frozen T2 retains its original input-hydration path and timing boundary.
|
||||||
|
pub(crate) fn disable_current_repo_mmap(&self) {
|
||||||
|
if let Ok(mut manager) = self.current_repo_mmap.lock() {
|
||||||
|
manager.enabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn persist_current_repo_mmap(&self) -> Result<(), String> {
|
||||||
|
self.current_repo_mmap
|
||||||
|
.lock()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.persist(self.db.latest_sequence_number(), |uri| {
|
||||||
|
self.list_current_rrdp_source_members(uri)
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_rrdp_source_member_record(
|
pub fn get_rrdp_source_member_record(
|
||||||
&self,
|
&self,
|
||||||
notify_uri: &str,
|
notify_uri: &str,
|
||||||
|
|||||||
@@ -857,6 +857,8 @@ fn sync_from_notification_snapshot_inner(
|
|||||||
drop(_write_state_step);
|
drop(_write_state_step);
|
||||||
drop(_write_state_total);
|
drop(_write_state_total);
|
||||||
|
|
||||||
|
// Also cache an empty initial snapshot, which writes no member records.
|
||||||
|
store.touch_current_repo_mmap_source(notification_uri);
|
||||||
Ok(published)
|
Ok(published)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1234,6 +1236,7 @@ fn sync_from_notification_inner(
|
|||||||
drop(_write_state_step);
|
drop(_write_state_step);
|
||||||
drop(_write_state_total);
|
drop(_write_state_total);
|
||||||
|
|
||||||
|
store.touch_current_repo_mmap_source(notification_uri);
|
||||||
Ok(published)
|
Ok(published)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1246,6 +1249,14 @@ pub(crate) fn hydrate_current_repo_index_from_rrdp_members(
|
|||||||
return Ok(0);
|
return Ok(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(view) = store.current_repo_mmap_view(notification_uri) {
|
||||||
|
index
|
||||||
|
.write()
|
||||||
|
.map_err(|_| RrdpSyncError::Storage("current repo index lock poisoned".into()))?
|
||||||
|
.install_mmap(view);
|
||||||
|
return Ok(0); // mmap views install without hydrating individual objects
|
||||||
|
}
|
||||||
|
|
||||||
let members = store
|
let members = store
|
||||||
.list_current_rrdp_source_members(notification_uri)
|
.list_current_rrdp_source_members(notification_uri)
|
||||||
.map_err(|e| RrdpSyncError::Storage(e.to_string()))?;
|
.map_err(|e| RrdpSyncError::Storage(e.to_string()))?;
|
||||||
|
|||||||
@@ -1182,6 +1182,122 @@ fn sync_from_notification_delta_hydrates_unchanged_current_repo_entries() {
|
|||||||
assert!(index.get_by_uri(uri_c).is_some(), "delta publish visible");
|
assert!(index.get_by_uri(uri_c).is_some(), "delta publish visible");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mmap_current_index_survives_restart_and_rrdp_replace_withdraw() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let db = tmp.path().join("db");
|
||||||
|
let sid = "550e8400-e29b-41d4-a716-446655440000";
|
||||||
|
let notify = "https://example.net/notification.xml";
|
||||||
|
let a = "rsync://example.net/repo/a.roa";
|
||||||
|
let b = "rsync://example.net/repo/b.roa";
|
||||||
|
let c = "rsync://example.net/repo/c.roa";
|
||||||
|
let d = "rsync://example.net/repo/d.roa";
|
||||||
|
let snapshot_uri = "https://example.net/snapshot.xml";
|
||||||
|
let snapshot = snapshot_xml(sid, 1, &[(a, b"a1"), (b, b"b1"), (c, b"c1")]);
|
||||||
|
let notification1 = notification_xml(
|
||||||
|
sid,
|
||||||
|
1,
|
||||||
|
snapshot_uri,
|
||||||
|
&hex::encode(sha2::Sha256::digest(&snapshot)),
|
||||||
|
);
|
||||||
|
{
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
sync_from_notification_snapshot(
|
||||||
|
&store,
|
||||||
|
notify,
|
||||||
|
¬ification1,
|
||||||
|
&MapFetcher {
|
||||||
|
map: HashMap::from([(snapshot_uri.into(), snapshot)]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
store.persist_current_repo_mmap().unwrap();
|
||||||
|
}
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
assert!(store.current_repo_mmap_view(notify).is_some());
|
||||||
|
let index = CurrentRepoIndex::shared();
|
||||||
|
let empty = MapFetcher {
|
||||||
|
map: HashMap::new(),
|
||||||
|
};
|
||||||
|
sync_from_notification_with_timing_and_download_log(
|
||||||
|
&store,
|
||||||
|
notify,
|
||||||
|
Some(&index),
|
||||||
|
¬ification1,
|
||||||
|
&empty,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(index.read().unwrap().active_uri_count(), 3);
|
||||||
|
let delta = delta_xml(
|
||||||
|
sid,
|
||||||
|
2,
|
||||||
|
&[
|
||||||
|
&format!(
|
||||||
|
r#"<publish uri="{a}" hash="{}">{}</publish>"#,
|
||||||
|
hex::encode(sha2::Sha256::digest(b"a1")),
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(b"a2")
|
||||||
|
),
|
||||||
|
&format!(
|
||||||
|
r#"<withdraw uri="{b}" hash="{}"/>"#,
|
||||||
|
hex::encode(sha2::Sha256::digest(b"b1"))
|
||||||
|
),
|
||||||
|
&format!(
|
||||||
|
r#"<publish uri="{d}">{}</publish>"#,
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(b"d2")
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let delta_hash = hex::encode(sha2::Sha256::digest(&delta));
|
||||||
|
let notification2 = notification_xml_with_deltas(
|
||||||
|
sid,
|
||||||
|
2,
|
||||||
|
snapshot_uri,
|
||||||
|
&"00".repeat(32),
|
||||||
|
&[("d2", 2, "https://example.net/delta.xml", &delta_hash)],
|
||||||
|
);
|
||||||
|
sync_from_notification_with_timing_and_download_log(
|
||||||
|
&store,
|
||||||
|
notify,
|
||||||
|
Some(&index),
|
||||||
|
¬ification2,
|
||||||
|
&MapFetcher {
|
||||||
|
map: HashMap::from([("https://example.net/delta.xml".into(), delta)]),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let expected = index.read().unwrap().snapshot_objects();
|
||||||
|
assert_eq!(expected.len(), 3);
|
||||||
|
assert!(index.read().unwrap().get_by_uri(b).is_none());
|
||||||
|
assert_eq!(
|
||||||
|
index
|
||||||
|
.read()
|
||||||
|
.unwrap()
|
||||||
|
.get_by_uri(a)
|
||||||
|
.unwrap()
|
||||||
|
.current_hash_hex,
|
||||||
|
hex::encode(sha2::Sha256::digest(b"a2"))
|
||||||
|
);
|
||||||
|
store.persist_current_repo_mmap().unwrap();
|
||||||
|
drop(store);
|
||||||
|
let store = RocksStore::open(&db).unwrap();
|
||||||
|
let restarted = CurrentRepoIndex::shared();
|
||||||
|
sync_from_notification_with_timing_and_download_log(
|
||||||
|
&store,
|
||||||
|
notify,
|
||||||
|
Some(&restarted),
|
||||||
|
¬ification2,
|
||||||
|
&empty,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(restarted.read().unwrap().snapshot_objects(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn load_rrdp_local_state_uses_source_record_only() {
|
fn load_rrdp_local_state_uses_source_record_only() {
|
||||||
let tmp = tempfile::tempdir().expect("tempdir");
|
let tmp = tempfile::tempdir().expect("tempdir");
|
||||||
|
|||||||
@@ -798,7 +798,7 @@ pub(crate) fn try_build_fresh_publication_point_with_timing(
|
|||||||
})?;
|
})?;
|
||||||
pack_files_index_lookup_duration += index_lookup_started.elapsed();
|
pack_files_index_lookup_duration += index_lookup_started.elapsed();
|
||||||
crate::storage::CurrentObjectWithHash {
|
crate::storage::CurrentObjectWithHash {
|
||||||
current_hash_hex: current.current_hash_hex.clone(),
|
current_hash_hex: current.current_hash_hex.to_owned(),
|
||||||
current_hash: current.current_hash,
|
current_hash: current.current_hash,
|
||||||
bytes: Vec::new(),
|
bytes: Vec::new(),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -764,7 +764,7 @@ impl<'a> Rpkiv1PublicationPointRunner<'a> {
|
|||||||
&& let Ok(index) = index_handle.read()
|
&& let Ok(index) = index_handle.read()
|
||||||
&& let Some(entry) = index.get_by_uri(&ca.manifest_rsync_uri)
|
&& let Some(entry) = index.get_by_uri(&ca.manifest_rsync_uri)
|
||||||
{
|
{
|
||||||
return Some(entry.current_hash_hex.clone());
|
return Some(entry.current_hash_hex.to_owned());
|
||||||
}
|
}
|
||||||
|
|
||||||
self.store
|
self.store
|
||||||
|
|||||||
Reference in New Issue
Block a user