use std::collections::HashMap;
use std::fs;
use std::io::{ErrorKind, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use super::CURRENT;
use super::error::{CONFLICT_IDS, ErrorType, ServiceError};
use super::limits::Limits;
use super::log::{
self, AppendError, ChangeName, Disk, Entry, FsDisk, LogError, LogFile, Outcome, Parsed, Tally, TaskRecord,
};
use super::memory::available_memory;
use super::request::{ChangeRecords, ChangeRequest, is_valid_name, unknown};
use super::set::{Overlay, SearchSet, Sets, collapse};
use crate::error::Error;
use crate::neighbours::NeighbourTable;
use crate::planned::Planned;
use crate::snapshot::{self, Fault, Manifest};
use crate::value::Value;
const CURRENT_MAX_BYTES: u64 = 256;
const SNAPSHOT_NAME_MAX: usize = 128;
const TABLE_MARGIN_MIN: u64 = 512 << 20;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SetSpec {
index: String,
subset: Option<String>,
dir: PathBuf,
}
impl SetSpec {
#[must_use]
pub fn index(name: &str, dir: impl Into<PathBuf>) -> Self {
Self {
index: name.to_owned(),
subset: None,
dir: dir.into(),
}
}
#[must_use]
pub fn subset(index: &str, name: &str, dir: impl Into<PathBuf>) -> Self {
Self {
index: index.to_owned(),
subset: Some(name.to_owned()),
dir: dir.into(),
}
}
pub fn parse_index(argument: &str) -> Result<Self, String> {
let (name, dir) = argument
.split_once('=')
.ok_or_else(|| "`--index` takes `name=dir`".to_owned())?;
check_name(name)?;
Ok(Self::index(name, dir))
}
pub fn parse_subset(argument: &str) -> Result<Self, String> {
let (names, dir) = argument
.split_once('=')
.ok_or_else(|| "`--subset` takes `index.name=dir`".to_owned())?;
let (index, name) = names
.split_once('.')
.ok_or_else(|| "`--subset` takes `index.name=dir`".to_owned())?;
check_name(index)?;
check_name(name)?;
Ok(Self::subset(index, name, dir))
}
#[must_use]
pub fn label(&self) -> String {
label(&self.index, self.subset.as_deref())
}
}
fn check_name(name: &str) -> Result<(), String> {
if is_valid_name(name) {
Ok(())
} else {
Err("a name is 1 to 32 of `a-z`, `0-9`, `_` and `-`".to_owned())
}
}
fn label(index: &str, subset: Option<&str>) -> String {
subset.map_or_else(|| index.to_owned(), |subset| format!("{index}.{subset}"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TableMemory {
Auto,
Bytes(u64),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LoadConfig {
pub table_memory: TableMemory,
pub threads: usize,
pub neighbours: bool,
pub sample: usize,
pub max_distance_64: u32,
pub max_distance_256: u32,
pub seed: u64,
pub retry_failed: Duration,
pub state_dir: Option<PathBuf>,
pub write_changes: bool,
pub repeat_window: Duration,
pub max_log_read_bytes: u64,
}
impl Default for LoadConfig {
fn default() -> Self {
Self {
table_memory: TableMemory::Auto,
threads: std::thread::available_parallelism().map_or(1, usize::from),
neighbours: true,
sample: 2_000,
max_distance_64: 16,
max_distance_256: 96,
seed: 0,
retry_failed: Duration::from_secs(300),
state_dir: None,
write_changes: false,
repeat_window: Duration::from_secs(3600),
max_log_read_bytes: Limits::new().log_read_bound(),
}
}
}
impl LoadConfig {
#[must_use]
pub fn max_distance(&self, width: u32) -> u32 {
if width == 64 {
self.max_distance_64.min(64)
} else {
self.max_distance_256.min(256)
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Event {
Refused {
set: String,
reason: String,
},
Loading {
set: String,
snapshot: String,
bytes: u64,
},
Loaded {
set: String,
snapshot: String,
records: usize,
width: u32,
tables: bool,
load_ms: u64,
build_ms: u64,
replaced: Option<String>,
replayed: usize,
replay_ms: u64,
seq: u64,
},
LogOpened {
set: String,
tasks: usize,
entries: usize,
seq: u64,
cut_bytes: u64,
cut_entries: usize,
},
LogRefused {
set: String,
reason: String,
},
LogShortened {
set: String,
covers_seq: u64,
entries: usize,
bytes_before: u64,
bytes_after: u64,
},
LogFailed {
set: String,
reason: String,
},
Failed {
set: String,
snapshot: String,
code: &'static str,
reason: String,
},
Measured {
set: String,
snapshot: String,
sample: usize,
ms: u64,
},
}
#[derive(Debug)]
pub(crate) struct Generation {
pub(crate) snapshot: String,
pub(crate) set: Sets,
pub(crate) loaded_at: SystemTime,
pub(crate) covers_seq: Option<u64>,
pub(crate) load_ms: u64,
pub(crate) build_ms: u64,
pub(crate) table_bytes: u64,
pub(crate) table_budget: Option<u64>,
pub(crate) replayed: usize,
pub(crate) replay_ms: u64,
pub(crate) neighbours: Arc<OnceLock<Neighbours>>,
}
impl Generation {
fn with_set(&self, set: Sets) -> Self {
Self {
snapshot: self.snapshot.clone(),
set,
loaded_at: self.loaded_at,
covers_seq: self.covers_seq,
load_ms: self.load_ms,
build_ms: self.build_ms,
table_bytes: self.table_bytes,
table_budget: self.table_budget,
replayed: self.replayed,
replay_ms: self.replay_ms,
neighbours: Arc::clone(&self.neighbours),
}
}
}
#[derive(Debug)]
pub(crate) struct Neighbours {
pub(crate) table: NeighbourTable,
pub(crate) max_distance: u32,
pub(crate) ms: u64,
}
#[derive(Debug, Clone)]
pub(crate) struct Loading {
pub(crate) snapshot: String,
pub(crate) read: Arc<AtomicU64>,
pub(crate) total: u64,
}
impl Loading {
pub(crate) fn fraction(&self) -> Option<f64> {
(self.total > 0).then(|| {
#[expect(clippy::cast_precision_loss, reason = "a fraction for a person to read")]
let fraction = self.read.load(Ordering::Relaxed) as f64 / self.total as f64;
(fraction * 1000.0).floor() / 1000.0
})
}
}
#[derive(Debug, Clone)]
pub(crate) struct Failed {
pub(crate) snapshot: String,
pub(crate) code: &'static str,
pub(crate) reason: Option<String>,
pub(crate) at: SystemTime,
retry_at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct LogSummary {
pub(crate) tasks: usize,
pub(crate) entries: usize,
pub(crate) bytes: u64,
pub(crate) first_seq: Option<u64>,
pub(crate) last_seq: u64,
pub(crate) base_seq: u64,
}
impl LogSummary {
fn of(parsed: &Parsed) -> Self {
Self {
tasks: parsed.tasks.len(),
entries: parsed.entries.len(),
bytes: parsed.end,
first_seq: parsed.entries.first().map(|entry| entry.seq),
last_seq: parsed.last_seq(),
base_seq: parsed.base_seq(),
}
}
}
#[derive(Debug)]
pub(crate) struct Changes {
dir: PathBuf,
file: Option<LogFile>,
tasks: HashMap<String, TaskRecord>,
summary: LogSummary,
width: Option<u32>,
broken: Option<Broken>,
events: Vec<Event>,
}
impl Changes {
fn adopt(&mut self, parsed: &Parsed) {
self.tasks = log::remembered(parsed);
self.summary = LogSummary::of(parsed);
self.width = parsed.header.as_ref().map(|header| header.width);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Writer {
Ok,
Broken(&'static str),
}
struct Unwinding<'a>(&'a Slot);
impl Drop for Unwinding<'_> {
fn drop(&mut self) {
if std::thread::panicking() {
self.0.state().writer = Some(Writer::Broken("panicked"));
}
}
}
#[derive(Debug, Default)]
struct State {
current: Option<Arc<Generation>>,
loading: Option<Loading>,
failed: Option<Failed>,
refused: Option<String>,
log_refused: Option<LogError>,
log: Option<LogSummary>,
writer: Option<Writer>,
remembered: usize,
}
#[derive(Debug)]
pub(crate) struct Slot {
pub(crate) index: String,
pub(crate) subset: Option<String>,
dir: PathBuf,
parent: Option<usize>,
state: Mutex<State>,
changes: Option<Mutex<Changes>>,
}
#[derive(Debug, Clone)]
pub(crate) struct View {
pub(crate) current: Option<Arc<Generation>>,
pub(crate) loading: Option<Loading>,
pub(crate) failed: Option<Failed>,
pub(crate) log_refused: Option<LogError>,
pub(crate) log: Option<LogSummary>,
pub(crate) writer: Option<Writer>,
pub(crate) remembered: usize,
}
impl Slot {
fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
fn changes(&self) -> Option<MutexGuard<'_, Changes>> {
self.changes
.as_ref()
.map(|changes| changes.lock().unwrap_or_else(PoisonError::into_inner))
}
pub(crate) fn label(&self) -> String {
label(&self.index, self.subset.as_deref())
}
pub(crate) fn ready(&self) -> Result<Arc<Generation>, ServiceError> {
let state = self.state();
if let Some(current) = &state.current {
return Ok(Arc::clone(current));
}
let what = if self.subset.is_some() { "subset" } else { "index" };
if let Some(reason) = &state.log_refused {
let mut error = ServiceError::new(
ErrorType::NotReady,
format!("the index `{}` is refused: {}", self.label(), reason.message),
);
error.state = Some("refused");
return Err(error);
}
let mut error = match &state.loading {
Some(loading) => {
let mut error = ServiceError::new(
ErrorType::NotReady,
format!("the {what} `{}` is loading its first snapshot", self.label()),
);
error.state = Some("loading");
error.fraction = loading.fraction();
error
}
None => ServiceError::new(
ErrorType::NotReady,
format!("the {what} `{}` has no snapshot loaded yet", self.label()),
),
};
error.state.get_or_insert("empty");
Err(error)
}
pub(crate) fn view(&self) -> View {
let state = self.state();
View {
current: state.current.clone(),
loading: state.loading.clone(),
failed: state.failed.clone(),
log_refused: state.log_refused.clone(),
log: state.log,
writer: state.writer,
remembered: state.remembered,
}
}
fn width(&self) -> Option<u32> {
self.state().current.as_ref().map(|current| current.set.width())
}
fn mirror(&self, changes: &Changes) {
let mut state = self.state();
state.log = Some(changes.summary);
state.remembered = changes.tasks.len();
}
fn break_writer(&self, changes: &mut Changes, code: &'static str, reason: String) -> Event {
let message = format!("changes are refused until the program restarts ({code}): {reason}");
changes.broken = Some((code, reason));
self.state().writer = Some(Writer::Broken(code));
Event::LogFailed {
set: self.label(),
reason: message,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Totals {
pub sets: u64,
pub records: u64,
pub changes_held: u64,
pub ready: u64,
pub not_ready: u64,
}
#[derive(Debug)]
pub struct Catalog {
slots: Vec<Slot>,
config: LoadConfig,
#[cfg(test)]
pub(crate) faults: Mutex<Vec<&'static str>>,
}
type Failure = (&'static str, String);
type Broken = (&'static str, String);
impl Catalog {
pub fn new(specs: Vec<SetSpec>, config: LoadConfig) -> Result<Self, String> {
Self::with_disk(specs, config, &|dir| Box::new(FsDisk::new(dir)))
}
pub(crate) fn with_disk(
specs: Vec<SetSpec>,
config: LoadConfig,
disk: &dyn Fn(&Path) -> Box<dyn Disk>,
) -> Result<Self, String> {
let mut ordered: Vec<SetSpec> = specs.iter().filter(|spec| spec.subset.is_none()).cloned().collect();
ordered.extend(specs.into_iter().filter(|spec| spec.subset.is_some()));
let mut slots: Vec<Slot> = Vec::with_capacity(ordered.len());
for spec in ordered {
check_name(&spec.index)?;
if let Some(subset) = &spec.subset {
check_name(subset)?;
}
if slots
.iter()
.any(|slot| slot.index == spec.index && slot.subset == spec.subset)
{
return Err(format!("`{}` is given twice", spec.label()));
}
let parent = match &spec.subset {
None => None,
Some(_) => Some(
slots
.iter()
.position(|slot| slot.subset.is_none() && slot.index == spec.index)
.ok_or_else(|| format!("the subset `{}` belongs to no `--index`", spec.label()))?,
),
};
if !spec.dir.is_dir() {
return Err(format!(
"`{}` isn't a directory, for `{}`",
spec.dir.display(),
spec.label()
));
}
slots.push(Slot {
index: spec.index,
subset: spec.subset,
dir: spec.dir,
parent,
state: Mutex::new(State::default()),
changes: None,
});
}
if slots.is_empty() {
return Err("give at least one `--index name=dir`".to_owned());
}
if let Some(state_dir) = &config.state_dir {
for slot in slots.iter_mut().filter(|slot| slot.subset.is_none()) {
let dir = state_dir.join(&slot.index);
let (file, parsed) = if config.write_changes {
let (file, parsed) = LogFile::open(disk(&dir), &slot.index, config.max_log_read_bytes)?;
(Some(file), parsed)
} else {
(None, log::read(&dir, &slot.index, config.max_log_read_bytes))
};
let mut changes = Changes {
dir,
file,
tasks: HashMap::new(),
summary: LogSummary::default(),
width: None,
broken: None,
events: Vec::new(),
};
let state = slot.state.get_mut().unwrap_or_else(PoisonError::into_inner);
match parsed {
Ok(parsed) => {
changes.adopt(&parsed);
state.log = Some(changes.summary);
state.remembered = changes.tasks.len();
state.writer = config.write_changes.then_some(Writer::Ok);
if config.write_changes {
let (cut_bytes, cut_entries) = parsed.cut.unwrap_or((0, 0));
changes.events.push(Event::LogOpened {
set: slot.index.clone(),
tasks: parsed.tasks.len(),
entries: parsed.entries.len(),
seq: parsed.last_seq(),
cut_bytes,
cut_entries,
});
}
}
Err(error) => {
changes.events.push(Event::LogRefused {
set: slot.index.clone(),
reason: format!("{} ({})", error.message, error.code),
});
state.log_refused = Some(error);
}
}
slot.changes = Some(Mutex::new(changes));
}
}
Ok(Self {
slots,
config,
#[cfg(test)]
faults: Mutex::new(Vec::new()),
})
}
#[cfg_attr(not(test), expect(clippy::unused_self, reason = "a test's hook"))]
#[cfg_attr(not(test), inline(always))]
pub(crate) fn fault(&self, point: &'static str) {
#[cfg(test)]
assert!(
!self
.faults
.lock()
.unwrap_or_else(PoisonError::into_inner)
.contains(&point),
"a fault injected at `{point}`"
);
#[cfg(not(test))]
let _ = point;
}
#[must_use]
pub const fn config(&self) -> &LoadConfig {
&self.config
}
#[must_use]
pub fn sets(&self) -> Vec<(String, PathBuf)> {
self.slots.iter().map(|slot| (slot.label(), slot.dir.clone())).collect()
}
#[must_use]
pub fn unready(&self) -> Vec<(String, String)> {
self.slots
.iter()
.filter_map(|slot| slot.ready().err().map(|error| (slot.label(), error.message)))
.collect()
}
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals::default();
for slot in &self.slots {
totals.sets += 1;
let current = slot.state().current.clone();
match current {
Some(generation) => {
totals.ready += 1;
totals.records += generation.set.len() as u64;
let (values, removals, _) = generation.set.changes();
totals.changes_held += (values + removals) as u64;
}
None => totals.not_ready += 1,
}
}
totals
}
pub(crate) fn find(&self, index: &str, subset: Option<&str>) -> Result<&Slot, ServiceError> {
let mut of_index = self.slots.iter().filter(|slot| slot.index == index).peekable();
if of_index.peek().is_none() {
return Err(unknown(ErrorType::UnknownIndex, "index", index));
}
of_index
.find(|slot| slot.subset.as_deref() == subset)
.ok_or_else(|| unknown(ErrorType::UnknownSubset, "subset", subset.unwrap_or_default()))
}
pub(crate) fn slots(&self) -> &[Slot] {
&self.slots
}
pub fn refresh(&self, observe: &mut dyn FnMut(&Event)) {
self.fault("refresh");
self.load_changed(observe);
self.measure_neighbours(observe);
}
pub fn load_changed(&self, observe: &mut dyn FnMut(&Event)) {
for slot in &self.slots {
self.refresh_slot(slot, observe);
}
}
pub fn measure_neighbours(&self, observe: &mut dyn FnMut(&Event)) {
if !self.config.neighbours {
return;
}
for slot in &self.slots {
let current = slot.state().current.clone();
if let Some(generation) = current.filter(|generation| generation.neighbours.get().is_none()) {
self.measure(slot, &generation, observe);
}
}
}
fn refresh_slot(&self, slot: &Slot, observe: &mut dyn FnMut(&Event)) {
let events = slot.changes().map(|mut changes| std::mem::take(&mut changes.events));
for event in events.iter().flatten() {
observe(event);
}
if slot.state().log_refused.is_some() {
return;
}
let name = match read_current(&slot.dir) {
Ok(None) => {
slot.state().refused = None;
return;
}
Ok(Some(name)) => name,
Err(reason) => {
let mut state = slot.state();
if state.refused.as_deref() != Some(reason.as_str()) {
state.refused = Some(reason.clone());
drop(state);
observe(&Event::Refused {
set: slot.label(),
reason,
});
}
return;
}
};
{
let mut state = slot.state();
state.refused = None;
if state.current.as_ref().is_some_and(|current| current.snapshot == name) {
return;
}
if state
.failed
.as_ref()
.is_some_and(|failed| failed.snapshot == name && Instant::now() < failed.retry_at)
{
return;
}
}
let parent_width = match slot.parent {
None => None,
Some(parent) => match self.slots[parent].width() {
None => return,
width => width,
},
};
self.load(slot, &name, parent_width, observe);
}
fn load(&self, slot: &Slot, name: &str, parent_width: Option<u32>, observe: &mut dyn FnMut(&Event)) {
let dir = slot.dir.join(name);
let loaded = open_manifest(&dir).and_then(|(path, manifest)| {
let (width, bytes) = (manifest.width, manifest.part_bytes());
let held = slot.width();
if let Some(served) = parent_width.filter(|&served| served != width) {
return Err((
"width",
format!("holds {width}-bit values; its index holds {served}-bit values"),
));
}
if let Some(served) = held.filter(|&served| served != width) {
return Err((
"width",
format!("holds {width}-bit values; the snapshot served holds {served}-bit values"),
));
}
let checked = if width == 64 {
manifest.check::<u64>(&path)
} else {
manifest.check::<[u64; 4]>(&path)
};
checked
.and_then(|()| snapshot::check_parts(&dir, &manifest))
.map_err(|error| failure(&error, &dir))?;
if let Some(available) = available_memory()
&& bytes > available
{
return Err((
"memory",
format!("needs {bytes} bytes for its records; {available} bytes are available"),
));
}
let loading = Loading {
snapshot: name.to_owned(),
read: Arc::new(AtomicU64::new(0)),
total: bytes,
};
slot.state().loading = Some(loading.clone());
observe(&Event::Loading {
set: slot.label(),
snapshot: name.to_owned(),
bytes,
});
if width == 64 {
self.build::<u64>(&dir, name, &manifest, &loading.read, Sets::W64)
} else {
self.build::<[u64; 4]>(&dir, name, &manifest, &loading.read, Sets::W256)
}
});
let mut changes = slot.changes();
let mut broke = None;
let loaded = loaded.and_then(|generation| match changes.as_deref_mut() {
Some(changes) => {
let parsed = self.read_log(changes, &slot.index).map_err(|(failure, broken)| {
broke = broken;
failure
})?;
replay(changes, &generation, parsed)
}
None => Ok((generation, None)),
});
if let (Some(changes), Some((code, reason))) = (changes.as_deref_mut(), broke) {
let event = slot.break_writer(changes, code, reason);
observe(&event);
}
let mut state = slot.state();
state.loading = None;
match loaded {
Ok((generation, parsed)) => {
let generation = Arc::new(generation);
let replaced = state.current.replace(Arc::clone(&generation));
state.failed = None;
drop(state);
observe(&Event::Loaded {
set: slot.label(),
snapshot: name.to_owned(),
records: generation.set.len(),
width: generation.set.width(),
tables: generation.set.has_tables(),
load_ms: generation.load_ms,
build_ms: generation.build_ms,
replaced: replaced.as_ref().map(|old| old.snapshot.clone()),
replayed: generation.replayed,
replay_ms: generation.replay_ms,
seq: generation.set.seq(),
});
drop(replaced);
if let (Some(changes), Some(parsed), Some(covers)) =
(changes.as_deref_mut(), parsed, generation.covers_seq)
{
self.shorten(slot, changes, &parsed, covers, observe);
}
}
Err((code, reason)) => {
state.failed = Some(Failed {
snapshot: name.to_owned(),
code,
reason: matches!(code, "covers_seq" | "log").then(|| reason.clone()),
at: SystemTime::now(),
retry_at: Instant::now() + self.config.retry_failed,
});
drop(state);
observe(&Event::Failed {
set: slot.label(),
snapshot: name.to_owned(),
code,
reason,
});
}
}
}
fn shorten(
&self,
slot: &Slot,
changes: &mut Changes,
parsed: &Parsed,
covers: u64,
observe: &mut dyn FnMut(&Event),
) {
let Some(file) = changes.file.as_mut() else {
return;
};
if changes.broken.is_some() {
return;
}
let keep_since = unix_millis().saturating_sub(millis(self.config.repeat_window));
let needless = parsed.tasks.iter().any(|(record, _)| {
record.last_seq().is_none_or(|last| last <= covers)
&& (record.entries > 0 || record.applied_at < keep_since)
});
if !needless && covers <= parsed.base_seq() {
return;
}
match file.shorten(parsed, covers, keep_since) {
Ok(shortened) => {
changes.adopt(&shortened);
slot.mirror(changes);
observe(&Event::LogShortened {
set: slot.label(),
covers_seq: covers,
entries: parsed.entries.len() - shortened.entries.len(),
bytes_before: parsed.end,
bytes_after: shortened.end,
});
}
Err(error) => {
let event = slot.break_writer(
changes,
"shorten_failed",
format!("the log couldn't be shortened: {error}"),
);
observe(&event);
}
}
}
pub(crate) fn change(
&self,
task_id: &str,
request: ChangeRequest,
limits: &Limits,
) -> Result<String, ServiceError> {
if !log::is_valid_task_id(task_id) {
return Err(invalid_task_id());
}
let slot = self.find(&request.index, None)?;
let Some(mut changes) = slot.changes() else {
return Err(ServiceError::new(
ErrorType::InvalidTask,
"this service keeps no change log: start it with `--state-dir` to take changes",
));
};
if changes.file.is_none() {
return Err(ServiceError::new(
ErrorType::InvalidTask,
"this program only reads the change log; `serve` takes changes",
));
}
let generation = slot.ready()?;
if let Some((code, broken)) = &changes.broken {
return Err(ServiceError::new(
ErrorType::Internal,
format!(
"writing the change log failed ({code}: {broken}); changes are refused until the program restarts"
),
));
}
let width = generation.set.width();
if width != request.width {
return Err(ServiceError::new(
ErrorType::WidthMismatch,
format!(
"`{}` holds {width}-bit values; the task gives `width` {}",
slot.label(),
request.width
),
));
}
if let Some(record) = changes.tasks.get(task_id) {
return answer(&slot.index, record);
}
let room = Room {
file: changes.file.as_ref().expect("checked above"),
position: changes.summary.last_seq,
bound: limits.max_log_bytes,
held: changes.summary.bytes,
label: slot.label(),
};
let (set, record, entries) = match (&generation.set, request.records) {
(Sets::W64(set), ChangeRecords::W64(records)) => {
let records: Vec<_> = records.into_iter().map(|(id, value)| (id, Some(value))).collect();
plan(set, task_id, request.name, &records, &room, Sets::W64)
}
(Sets::W256(set), ChangeRecords::W256(records)) => {
let records: Vec<_> = records.into_iter().map(|(id, value)| (id, Some(value))).collect();
plan(set, task_id, request.name, &records, &room, Sets::W256)
}
(Sets::W64(set), ChangeRecords::Remove(ids)) => {
let records: Vec<_> = ids.into_iter().map(|id| (id, None)).collect();
plan(set, task_id, request.name, &records, &room, Sets::W64)
}
(Sets::W256(set), ChangeRecords::Remove(ids)) => {
let records: Vec<_> = ids.into_iter().map(|id| (id, None)).collect();
plan(set, task_id, request.name, &records, &room, Sets::W256)
}
_ => return Err(ServiceError::new(ErrorType::Internal, "the widths disagree")),
}?;
let unwinding = Unwinding(slot);
changes.broken = Some(("panicked", "a change unwound between the log and memory".to_owned()));
let file = changes.file.as_mut().expect("checked above");
match file.append(width, &record, &entries, limits.max_log_bytes) {
Ok(Some(bytes)) => {
self.fault("commit");
let summary = &mut changes.summary;
summary.tasks += 1;
summary.entries += entries.len();
summary.bytes += bytes;
if let Some(last) = entries.last() {
summary.first_seq.get_or_insert(entries[0].seq);
summary.last_seq = last.seq;
}
changes.width = Some(width);
}
Ok(None) => {
changes.broken = None;
return Err(log_full(&slot.label(), changes.summary.bytes, limits.max_log_bytes));
}
Err(AppendError::Unrepresentable(field)) => {
changes.broken = None;
return Err(ServiceError::new(
ErrorType::InvalidTask,
format!("the task's {field} can't be recorded in the change log; nothing was written"),
));
}
Err(AppendError::Failed(code, error)) => {
let event = slot.break_writer(&mut changes, code, format!("a change couldn't be written: {error}"));
changes.events.push(event);
return Err(ServiceError::new(
ErrorType::Internal,
format!(
"the change couldn't be written to the log ({code}: {error}); whether it was is unknown, \
and changes are refused until the program restarts: send it again with the same \
`task_id` then"
),
));
}
}
self.fault("publish");
if let Some(set) = set {
let mut state = slot.state();
if let Some(current) = &state.current {
state.current = Some(Arc::new(current.with_set(set)));
}
}
self.fault("remember");
let answered = answer(&slot.index, &record);
changes.tasks.insert(task_id.to_owned(), record);
slot.mirror(&changes);
changes.broken = None;
drop(unwinding);
answered
}
fn read_log(&self, changes: &mut Changes, index: &str) -> Result<Parsed, (Failure, Option<Broken>)> {
let max = self.config.max_log_read_bytes;
match changes.file.as_mut() {
None => log::read(&changes.dir, index, max).map_err(|error| (("log", error.message), None)),
Some(_) if changes.broken.is_some() => {
let code = changes.broken.as_ref().map_or("", |(code, _)| code);
Err((
(
"log",
format!(
"this process stopped writing the change log ({code}), so what it holds isn't known; a \
restart reads it again"
),
),
None,
))
}
Some(file) => file.reread(max).map_err(|error| {
let code = match error.code {
"missing" => "log_missing",
"replaced" => "log_replaced",
"appeared" => "log_appeared",
"changed" => "log_changed",
"cut" => "log_cut",
"too_large" => "log_too_large",
_ => "log_unreadable",
};
let reason = format!("{} ({code}); the snapshot served stays", error.message);
(("log", reason), Some((code, error.message)))
}),
}
}
fn build<V: Value>(
&self,
dir: &Path,
name: &str,
manifest: &Manifest,
read: &AtomicU64,
wrap: fn(SearchSet<V>) -> Sets,
) -> Result<Generation, Failure> {
let started = Instant::now();
let records = snapshot::load_listed::<V>(dir, manifest, read).map_err(|error| failure(&error, dir))?;
let load_ms = millis(started.elapsed());
let records = Arc::new(records);
let table_bytes = Planned::<V>::table_bytes(records.len()) as u64;
let table_budget = match self.config.table_memory {
TableMemory::Bytes(bytes) => Some(bytes),
TableMemory::Auto => {
available_memory().map(|available| available.saturating_sub((available / 4).max(TABLE_MARGIN_MIN)))
}
};
let started = Instant::now();
let planned = match table_budget {
Some(budget) if table_bytes > budget => Planned::scan_only(records),
_ => Planned::try_new(records, usize::MAX, self.config.threads).map_err(|error| failure(&error, dir))?,
};
Ok(Generation {
snapshot: name.to_owned(),
set: wrap(SearchSet::new(planned)),
loaded_at: SystemTime::now(),
covers_seq: manifest.covers_seq,
load_ms,
build_ms: millis(started.elapsed()),
table_bytes,
table_budget,
replayed: 0,
replay_ms: 0,
neighbours: Arc::new(OnceLock::new()),
})
}
fn measure(&self, slot: &Slot, generation: &Generation, observe: &mut dyn FnMut(&Event)) {
let started = Instant::now();
let max_distance = self.config.max_distance(generation.set.width());
let table = generation
.set
.neighbours(self.config.sample, self.config.seed, max_distance, self.config.threads);
let sample = table.sample;
let ms = millis(started.elapsed());
let _ = generation.neighbours.set(Neighbours {
table,
max_distance,
ms,
});
observe(&Event::Measured {
set: slot.label(),
snapshot: generation.snapshot.clone(),
sample,
ms,
});
}
}
pub(crate) fn millis(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
fn unix_millis() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, millis)
}
fn replay(
changes: &mut Changes,
generation: &Generation,
parsed: Parsed,
) -> Result<(Generation, Option<Parsed>), Failure> {
if !generation.set.has_ids() {
return Err((
"ids",
"has no record ids; an index that takes changes needs them".to_owned(),
));
}
let width = generation.set.width();
for logged in [changes.width, parsed.header.as_ref().map(|header| header.width)] {
if let Some(logged) = logged.filter(|&logged| logged != width) {
return Err((
"width",
format!("holds {width}-bit values; the index's change log holds {logged}-bit values"),
));
}
}
let position = parsed.last_seq();
let base = parsed.base_seq();
match generation.covers_seq {
Some(covers) if covers > position => {
return Err((
"covers_seq",
format!(
"its covers_seq is {covers}, past {position}, the last change this service logged: it claims \
changes this service never saw"
),
));
}
Some(covers) if covers < base => {
return Err((
"covers_seq",
format!(
"its covers_seq is {covers}, but the log has dropped every change to {base}, so the changes it \
misses can't be replayed"
),
));
}
None if base > 0 => {
return Err((
"covers_seq",
format!(
"it has no covers_seq, but the log has dropped every change to {base}, so the changes it may \
miss can't be replayed"
),
));
}
_ => {}
}
let from = generation.covers_seq.unwrap_or(0);
let entries = &parsed.entries[parsed.entries.partition_point(|entry| entry.seq <= from)..];
let started = Instant::now();
let set = match &generation.set {
Sets::W64(set) => Sets::W64(set.with_changes(Overlay::over(set.records(), collapse(entries)), position)),
Sets::W256(set) => Sets::W256(set.with_changes(Overlay::over(set.records(), collapse(entries)), position)),
};
let generation = Generation {
replayed: entries.len(),
replay_ms: millis(started.elapsed()),
..generation.with_set(set)
};
changes.adopt(&parsed);
Ok((generation, Some(parsed)))
}
pub(crate) fn invalid_task_id() -> ServiceError {
ServiceError::new(
ErrorType::InvalidTask,
format!(
"a change task's `task_id` is 1 to {} of `A-Z`, `a-z`, `0-9`, `_` and `-`",
log::TASK_ID_MAX
),
)
}
fn log_full(label: &str, held: u64, bound: u64) -> ServiceError {
ServiceError::new(
ErrorType::LogFull,
format!(
"the change log of `{label}` holds {held} bytes, and this task would take it past its bound of {bound}: \
export a snapshot that covers its changes so it can be shortened"
),
)
}
struct Room<'a> {
file: &'a LogFile,
position: u64,
bound: u64,
held: u64,
label: String,
}
fn plan<V: Value>(
set: &SearchSet<V>,
task_id: &str,
name: ChangeName,
records: &[(u64, Option<V>)],
room: &Room<'_>,
wrap: fn(SearchSet<V>) -> Sets,
) -> Result<(Option<Sets>, TaskRecord, Vec<Entry>), ServiceError> {
let mut tally = Tally::default();
let mut conflicts = Vec::new();
for &(id, value) in records {
match (set.get(id), value) {
(Some(held), Some(value)) if held == value => tally.unchanged += 1,
(Some(_), Some(_)) if name == ChangeName::Append => conflicts.push(id),
(Some(_), Some(_)) => tally.changed += 1,
(None, Some(_)) => tally.added += 1,
(Some(_), None) => tally.removed += 1,
(None, None) => tally.unchanged += 1,
}
}
let position = room.position;
let width = V::BITS;
let (sets, removes) = if conflicts.is_empty() {
let sets = records.iter().filter(|(_, value)| value.is_some()).count();
(sets, records.len() - sets)
} else {
(0, 0)
};
let bytes = log::framed_bytes(width, sets, removes, conflicts.len(), task_id.len());
if bytes.is_none_or(|bytes| !room.file.fits(width, bytes, room.bound)) {
return Err(log_full(&room.label, room.held, room.bound));
}
let last = if conflicts.is_empty() {
position.checked_add(records.len() as u64)
} else {
Some(position)
};
let Some(seq) = last else {
return Err(ServiceError::new(
ErrorType::LogFull,
format!(
"the change log of `{}` is at seq {position}, and this task's {} changes would take it past the last \
seq there is: the sequence is exhausted",
room.label,
records.len()
),
));
};
let record = |outcome, entries| TaskRecord {
task_id: task_id.to_owned(),
name,
outcome,
applied_at: unix_millis(),
first_seq: position.saturating_add(1),
entries,
};
if !conflicts.is_empty() {
let count = u32::try_from(conflicts.len()).unwrap_or(u32::MAX);
conflicts.truncate(CONFLICT_IDS);
let record = TaskRecord {
first_seq: position,
..record(Outcome::Conflict { ids: conflicts, count }, 0)
};
return Ok((None, record, Vec::new()));
}
let entries: Vec<Entry> = records
.iter()
.zip(position + 1..=seq)
.map(|(&(id, value), seq)| Entry::new(seq, id, value))
.collect();
let count = u32::try_from(entries.len()).unwrap_or(u32::MAX);
let next = set.with_changes(set.overlay().with(records), seq);
Ok((
Some(wrap(next)),
record(Outcome::Applied { seq, tally }, count),
entries,
))
}
#[derive(serde::Serialize)]
struct ChangeObject<'a> {
format: u32,
index: &'a str,
seq: u64,
added: u32,
changed: u32,
removed: u32,
unchanged: u32,
}
fn answer(index: &str, record: &TaskRecord) -> Result<String, ServiceError> {
match &record.outcome {
Outcome::Applied { seq, tally } => serde_json::to_string(&ChangeObject {
format: super::FORMAT,
index,
seq: *seq,
added: tally.added,
changed: tally.changed,
removed: tally.removed,
unchanged: tally.unchanged,
})
.map_err(|error| ServiceError::new(ErrorType::Internal, error.to_string())),
Outcome::Conflict { ids, count } => {
let mut error = ServiceError::new(
ErrorType::Conflict,
format!(
"{count} of the task's records give an id the index holds with another value; nothing was applied"
),
);
error.ids = Some(ids.clone());
error.count = Some(u64::from(*count));
Err(error)
}
}
}
const LABEL_BYTES: usize = 64;
fn log_label(text: &str) -> String {
text.bytes()
.take(LABEL_BYTES)
.map(|byte| {
if (byte.is_ascii_graphic() && byte != b'`') || byte == b' ' {
char::from(byte)
} else {
'?'
}
})
.collect()
}
fn shown(dir: &Path, path: &Path) -> String {
let name = path.file_name().map(|name| name.to_string_lossy()).unwrap_or_default();
format!("{}/{}", dir.display(), log_label(&name))
}
fn failure(error: &Error, dir: &Path) -> Failure {
match error {
Error::Checksum { path, .. } => (
"checksum",
format!(
"snapshot part `{}`: its SHA-256 isn't the one the manifest records",
shown(dir, path)
),
),
Error::Io { path, source } => ("io", format!("couldn't read `{}`: {source}", shown(dir, path))),
Error::IdOrder { .. } => (
"ids",
format!(
"snapshot `{}`: a record id isn't above the id before it; records go in rising id order",
dir.display()
),
),
Error::OutOfMemory { .. } => ("memory", format!("snapshot `{}`: {error}", dir.display())),
Error::Snapshot { path, reason } => {
let fault = Fault::of(reason);
let words = fault.map_or("doesn't agree with the snapshot format", Fault::words);
let location = if fault == Some(Fault::Parse) {
reason
.rfind(" at line ")
.map(|at| &reason[at..])
.filter(|location| {
location
.bytes()
.all(|byte| byte.is_ascii_digit() || b" atlinecolum".contains(&byte))
})
.unwrap_or_default()
} else {
""
};
(
"manifest",
format!("snapshot file `{}`: {words}{location}", shown(dir, path)),
)
}
_ => ("manifest", format!("snapshot `{}`: {error}", dir.display())),
}
}
fn read_current(dir: &Path) -> Result<Option<String>, String> {
let path = dir.join(CURRENT);
let (file, metadata) = match snapshot::open_file(&path) {
Ok(opened) => opened,
Err(Error::Io { source, .. }) if source.kind() == ErrorKind::NotFound => return Ok(None),
Err(Error::Io { source, .. }) => return Err(format!("`CURRENT` can't be read: {source}")),
Err(Error::Snapshot { reason, .. }) => {
return Err(match Fault::of(&reason) {
Some(Fault::Link) => "`CURRENT` is a symbolic link; it must be a file".to_owned(),
Some(Fault::NotFile) => "`CURRENT` isn't a file".to_owned(),
_ => "`CURRENT` changed while it was opened".to_owned(),
});
}
Err(error) => return Err(format!("`CURRENT` can't be read: {error}")),
};
let too_long = || format!("`CURRENT` is more than {CURRENT_MAX_BYTES} bytes; it names one directory");
if metadata.len() > CURRENT_MAX_BYTES {
return Err(too_long());
}
let mut bytes = Vec::new();
file.take(CURRENT_MAX_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|error| format!("`CURRENT` can't be read: {error}"))?;
if bytes.len() as u64 > CURRENT_MAX_BYTES {
return Err(format!(
"`CURRENT` is more than {CURRENT_MAX_BYTES} bytes; it names one directory"
));
}
let text = String::from_utf8(bytes).map_err(|_| "`CURRENT` isn't UTF-8".to_owned())?;
let name = text
.strip_suffix('\n')
.map_or(text.as_str(), |line| line.strip_suffix('\r').unwrap_or(line));
if !is_snapshot_name(name) {
return Err(format!(
"`CURRENT` must be one line naming a snapshot directory inside `{}`: 1 to {SNAPSHOT_NAME_MAX} of \
`A-Z`, `a-z`, `0-9`, `.`, `_`, `:` and `-`, not starting with `.`",
dir.display()
));
}
let snapshot = dir.join(name);
let shown = log_label(name);
let metadata = match fs::symlink_metadata(&snapshot) {
Ok(metadata) => metadata,
Err(error) if error.kind() == ErrorKind::NotFound => {
return Err(format!("`CURRENT` names `{shown}`, which doesn't exist"));
}
Err(error) => return Err(format!("`CURRENT` names `{shown}`, which can't be read: {error}")),
};
if metadata.file_type().is_symlink() {
return Err(format!(
"`CURRENT` names `{shown}`, a symbolic link; it must be a directory"
));
}
if !metadata.is_dir() {
return Err(format!("`CURRENT` names `{shown}`, which isn't a directory"));
}
let inside = fs::canonicalize(&snapshot)
.ok()
.zip(fs::canonicalize(dir).ok())
.is_some_and(|(snapshot, dir)| snapshot.parent() == Some(dir.as_path()));
if !inside {
return Err(format!(
"`CURRENT` names `{shown}`, which isn't inside `{}`",
dir.display()
));
}
Ok(Some(name.to_owned()))
}
fn is_snapshot_name(name: &str) -> bool {
(1..=SNAPSHOT_NAME_MAX).contains(&name.len())
&& !name.starts_with('.')
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
}
fn open_manifest(dir: &Path) -> Result<(PathBuf, Manifest), Failure> {
let (path, manifest) = snapshot::read_manifest(dir).map_err(|error| failure(&error, dir))?;
if !matches!(manifest.width, 64 | 256) {
return Err((
"manifest",
format!("snapshot file `{}`: gives no width of 64 or 256", shown(dir, &path)),
));
}
Ok((path, manifest))
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[non_exhaustive]
pub struct Verified {
pub width: u32,
pub ids: bool,
pub records: u64,
pub first_id: Option<u64>,
pub last_id: Option<u64>,
pub parts: usize,
pub bytes: u64,
pub covers_seq: Option<u64>,
}
pub fn verify_snapshot(dir: &Path) -> Result<Verified, String> {
let (path, manifest) = snapshot::read_manifest(dir).map_err(|error| error.to_string())?;
let manifest = match manifest.width {
64 => snapshot::verify_listed::<u64>(dir, &path, manifest),
256 => snapshot::verify_listed::<[u64; 4]>(dir, &path, manifest),
width => {
return Err(format!(
"snapshot file `{}`: gives width {width}, not 64 or 256",
path.display()
));
}
}
.map_err(|error| error.to_string())?;
Ok(Verified {
width: manifest.width,
ids: manifest.ids,
records: manifest.records,
first_id: manifest.first_id,
last_id: manifest.last_id,
parts: manifest.parts.len(),
bytes: manifest.part_bytes(),
covers_seq: manifest.covers_seq,
})
}
#[cfg(test)]
mod tests {
use std::panic::{AssertUnwindSafe, catch_unwind};
use serde_json::Value as Json;
use super::super::log::double::MemDisk;
use super::super::set::LEVELS_BUILT;
use super::*;
use crate::Records;
use crate::service::{Lane, Service};
struct SetDir(PathBuf);
impl SetDir {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("legit-hamming-catalog-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let records = Records::from_records([(1u64, 0xffu64), (2, 0xf0)]).expect("ids rise");
snapshot::write(&dir.join("s0"), &records, 10).expect("written");
fs::write(dir.join(CURRENT), "s0\n").expect("written");
Self(dir)
}
}
impl Drop for SetDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn open(dir: &SetDir, disk: &MemDisk, limits: Limits) -> Service {
let config = LoadConfig {
neighbours: false,
threads: 1,
state_dir: Some(PathBuf::from("state")),
write_changes: true,
..LoadConfig::default()
};
let disk = disk.clone();
let catalog = Catalog::with_disk(vec![SetSpec::index("m", &dir.0)], config, &move |_| {
Box::new(disk.clone()) as Box<dyn Disk>
})
.expect("opens");
catalog.refresh(&mut |_| {});
Service::new(Arc::new(catalog), limits, 1)
}
fn replace(service: &Service, task_id: &str, id: u64, value: u64) -> Result<Json, ServiceError> {
let options = format!(r#"{{"format":1,"index":"m","width":64,"records":[[{id},"{value:016x}"]]}}"#);
service
.change(task_id, "replace", &options)
.map(|json| serde_json::from_str(&json).expect("JSON"))
}
fn stats(service: &Service) -> Json {
serde_json::from_str(&service.stats(r#"{"format":1,"index":"m"}"#).expect("stats")).expect("JSON")
}
fn found(service: &Service, value: u64) -> Json {
let options = format!(r#"{{"format":1,"index":"m","width":64,"radius":0,"values":["{value:016x}"]}}"#);
let json = service.search(&options, Lane::Bulk).expect("searched").json;
serde_json::from_str::<Json>(&json).expect("JSON")["queries"][0]["matches"].clone()
}
fn durable_tasks(disk: &MemDisk) -> Vec<String> {
disk.state().durable.as_ref().map_or_else(Vec::new, |bytes| {
log::parse(bytes, "m")
.expect("reads")
.tasks
.iter()
.map(|(record, _)| record.task_id.clone())
.collect()
})
}
#[test]
fn a_task_written_before_a_crash_is_durable_before_its_repeat_is_answered() {
let dir = SetDir::new("recovered");
let disk = MemDisk::default();
let service = open(&dir, &disk, Limits::default());
{
let mut state = disk.state();
state.fail_sync_data = true;
state.fail_truncate = true;
}
assert_eq!(
replace(&service, "t1", 7, 0x0f).expect_err("unknown").error_type,
ErrorType::Internal
);
drop(service);
disk.state().fail_truncate = false;
assert!(durable_tasks(&disk).is_empty());
let service = open(&dir, &disk, Limits::default());
let again = replace(&service, "t1", 7, 0x0f).expect("answered");
assert_eq!(again["seq"], 1);
assert_eq!(durable_tasks(&disk), ["t1"]);
disk.crash();
let service = open(&dir, &disk, Limits::default());
assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), again);
assert_eq!(stats(&service)["seq"], 1);
}
#[test]
fn the_state_directory_is_durable_from_the_first_change() {
let dir = SetDir::new("first");
let disk = MemDisk::default();
let service = open(&dir, &disk, Limits::default());
let first = replace(&service, "t1", 7, 0x0f).expect("applied");
drop(service);
disk.crash();
let service = open(&dir, &disk, Limits::default());
assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), first);
assert_eq!(found(&service, 0x0f)[0]["id"], 7);
let calls = disk.state().calls.clone();
let made = calls.iter().position(|call| *call == "make_dir").expect("made");
assert_eq!(calls[made + 1], "sync_parent", "{calls:?}");
}
#[test]
fn a_failed_sync_breaks_the_writer_and_stats_says_how() {
for (fail_truncate, code, survives) in [(false, "sync_failed", false), (true, "rollback_failed", true)] {
let dir = SetDir::new(code);
let disk = MemDisk::default();
let service = open(&dir, &disk, Limits::default());
replace(&service, "t0", 9, 0x01).expect("applied");
{
let mut state = disk.state();
state.fail_sync_data = true;
state.fail_truncate = fail_truncate;
}
let error = replace(&service, "t1", 7, 0x0f).expect_err("unknown");
assert_eq!(error.error_type, ErrorType::Internal);
assert!(error.message.contains("same `task_id`"), "{}", error.message);
let changes = &stats(&service)["changes"];
assert_eq!(
(&changes["writer"], &changes["writer_reason"]),
(&json("broken"), &json(code))
);
assert_eq!(
replace(&service, "t2", 8, 0x02).expect_err("refused").error_type,
ErrorType::Internal
);
assert_eq!(stats(&service)["seq"], 1);
drop(service);
disk.state().fail_truncate = false;
let service = open(&dir, &disk, Limits::default());
assert_eq!(stats(&service)["changes"]["writer"], "ok");
assert_eq!(stats(&service)["seq"], if survives { 2 } else { 1 });
let again = replace(&service, "t1", 7, 0x0f).expect("answered");
assert_eq!(again["seq"], 2);
assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered"), again);
assert_eq!(durable_tasks(&disk), ["t0", "t1"]);
}
}
fn json(text: &str) -> Json {
Json::String(text.to_owned())
}
#[test]
fn log_full_is_decided_before_any_level_is_built() {
let dir = SetDir::new("full");
let disk = MemDisk::default();
let service = open(&dir, &disk, Limits::default());
LEVELS_BUILT.with(|built| built.set(0));
replace(&service, "t1", 7, 0x0f).expect("applied");
assert!(LEVELS_BUILT.with(std::cell::Cell::get) > 0, "a change builds a level");
let held = stats(&service)["changes"]["log"]["bytes"].as_u64().expect("bytes");
drop(service);
let limits = Limits {
max_log_bytes: held + 50,
..Limits::default()
};
let service = open(&dir, &disk, limits);
LEVELS_BUILT.with(|built| built.set(0));
let full = replace(&service, "t2", 8, 0x0f).expect_err("full");
assert_eq!(full.error_type, ErrorType::LogFull);
assert_eq!(
LEVELS_BUILT.with(std::cell::Cell::get),
0,
"a refused task builds no level"
);
assert_eq!(disk.state().visible.as_ref().map(Vec::len), Some(held as usize));
}
#[test]
fn a_change_that_unwinds_between_the_log_and_memory_breaks_the_writer() {
for point in ["commit", "publish", "remember"] {
let dir = SetDir::new(point);
let disk = MemDisk::default();
let service = open(&dir, &disk, Limits::default());
service.catalog().faults.lock().expect("faults").push(point);
let unwound = catch_unwind(AssertUnwindSafe(|| replace(&service, "t1", 7, 0x0f)));
assert!(unwound.is_err(), "{point}");
service.catalog().faults.lock().expect("faults").clear();
let changes = &stats(&service)["changes"];
assert_eq!(
(&changes["writer"], &changes["writer_reason"]),
(&json("broken"), &json("panicked")),
"{point}"
);
assert_eq!(
replace(&service, "t2", 8, 0x02).expect_err("refused").error_type,
ErrorType::Internal,
"{point}"
);
drop(service);
let service = open(&dir, &disk, Limits::default());
assert_eq!(replace(&service, "t1", 7, 0x0f).expect("answered")["seq"], 1, "{point}");
assert_eq!(replace(&service, "t2", 8, 0x02).expect("applied")["seq"], 2, "{point}");
}
}
}