use uuid::Uuid;
use super::errors::{err, Category, Result};
pub const HEAD_KEY: &str = "head.json";
pub(crate) fn uuid8() -> String {
Uuid::new_v4().simple().to_string()[..8].to_string()
}
pub(crate) fn checkpoint_key(generation: u64, seq: u64) -> String {
format!("checkpoints/{generation}-{seq}-{}.tar.gz", uuid8())
}
pub(crate) fn wal_key(generation: u64, seq: u64) -> String {
format!("wal/{generation}-{seq}-{}.jsonl", uuid8())
}
pub fn is_valid_object_key(key: &str) -> bool {
if key.is_empty() || key.starts_with('/') {
return false;
}
if key.contains('\\') || key.contains('\0') {
return false;
}
key.split('/')
.all(|segment| !matches!(segment, "" | "." | ".."))
}
pub(crate) fn validate_object_id(id: &str) -> Result<()> {
let bad = id.is_empty()
|| id.contains('/')
|| id.contains('\\')
|| id.contains('\0')
|| id == "."
|| id == "..";
if bad {
return Err(err(
Category::Backend,
format!("durable: object id must be a single non-empty path segment, got {id:?}"),
));
}
Ok(())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn a_minted_key_carries_its_generation_sequence_and_a_fresh_suffix() {
let first = wal_key(3, 9);
let second = wal_key(3, 9);
assert!(first.starts_with("wal/3-9-"), "{first}");
assert!(first.ends_with(".jsonl"), "{first}");
assert_ne!(first, second, "every attempt has to mint its own key");
assert!(checkpoint_key(3, 9).starts_with("checkpoints/3-9-"));
assert!(checkpoint_key(3, 9).ends_with(".tar.gz"));
assert!(is_valid_object_key(&first));
}
#[test]
fn a_key_that_could_leave_the_object_is_not_a_key() {
for key in [
"",
"/checkpoints/1.tar.gz",
"../other/head.json",
"wal/../../escape",
"wal//1.jsonl",
"wal/./1.jsonl",
"wal\\1.jsonl",
] {
assert!(!is_valid_object_key(key), "{key:?} should be refused");
}
assert!(is_valid_object_key("head.json"));
assert!(is_valid_object_key("wal/3-9-acde5678.jsonl"));
}
#[test]
fn an_object_id_is_one_segment() {
for id in ["", ".", "..", "a/b", "a\\b"] {
assert!(validate_object_id(id).is_err(), "{id:?} should be refused");
}
assert!(validate_object_id("tenant-123").is_ok());
}
}