use super::super::*;
use super::atomic_write;
const NAMESPACE_ALLOCATOR_FILE: &str = "namespace-allocator";
fn allocator_unavailable(detail: String) -> AuthFailure {
AuthFailure::new("namespace_allocator_unavailable", detail, false)
}
pub(crate) fn read_namespace_high_water(state_dir: &Path) -> Result<u64, AuthFailure> {
let path = state_dir.join(NAMESPACE_ALLOCATOR_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
Err(error) => {
return Err(allocator_unavailable(format!(
"failed to read `{}`: {error}",
path.display()
)));
}
};
match text.trim().parse::<u64>() {
Ok(high_water) if high_water <= MAX_ALLOCATED_NAMESPACE => Ok(high_water),
_ => Err(allocator_unavailable(format!(
"`{}` does not hold a namespace count",
path.display()
))),
}
}
pub(crate) fn restore_namespace_high_water(state_dir: &Path, persisted: u64) -> u64 {
match read_namespace_high_water(state_dir) {
Ok(high_water) if high_water >= persisted => high_water,
Ok(behind) => {
tracing::warn!(
event = "namespace_allocator_restored",
behind,
persisted,
"the namespace allocator file was lost or behind; restoring it from the encrypted state"
);
if let Err(error) = write_namespace_high_water(state_dir, persisted) {
tracing::error!(
event = "namespace_allocator_restore_failed",
reason = %error.code,
error = %error.message,
"could not restore the namespace allocator file; the next allocation will retry"
);
}
persisted
}
Err(error) => {
tracing::error!(
event = "namespace_allocator_damaged",
reason = %error.code,
error = %error.message,
"namespace operations are refused until the damaged allocator file is removed"
);
persisted
}
}
}
pub(crate) fn write_namespace_high_water(
state_dir: &Path,
namespace: u64,
) -> Result<(), AuthFailure> {
atomic_write(
&state_dir.join(NAMESPACE_ALLOCATOR_FILE),
namespace.to_string().as_bytes(),
0o600,
)
}