pub use kcode_k1_ese_format::{Authority, Event, ExternalSubsystem, TxId, UserId};
use sha2::{Digest, Sha256};
use std::{
collections::HashMap,
fs::{self, File, FileType, OpenOptions},
io::{self, Read, Seek, SeekFrom, Write},
path::{Path, PathBuf},
sync::{
Arc, Mutex, RwLock,
atomic::{AtomicBool, Ordering},
},
};
const MAGIC: &[u8; 8] = b"K1ESE01\0";
const FIXED: usize = 64;
type Ref = Arc<Mutex<Stream>>;
type Map = HashMap<ExternalSubsystem, Ref>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExternalUpdate {
progress: TxId,
operation_id: [u8; 32],
payload: Vec<u8>,
}
impl ExternalUpdate {
pub const fn progress(&self) -> TxId {
self.progress
}
pub const fn operation_id(&self) -> &[u8; 32] {
&self.operation_id
}
pub fn payload(&self) -> &[u8] {
&self.payload
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ApplyOutcome {
Registered,
Submitted { progress: TxId, duplicate: bool },
}
#[derive(Clone, Copy)]
struct Record {
progress: TxId,
actor: UserId,
operation: [u8; 32],
at: u64,
len: usize,
}
struct Stream {
path: PathBuf,
records: Vec<Record>,
operations: HashMap<[u8; 32], usize>,
progress: HashMap<TxId, usize>,
}
pub struct EseStore {
root: PathBuf,
streams: RwLock<Map>,
checkpoint: Mutex<Option<TxId>>,
poisoned: AtomicBool,
}
impl EseStore {
pub fn open(root: &Path) -> Result<Self, String> {
let (streams, checkpoint) = match load(root) {
Ok(value) => value,
Err(Failure::Bad) => {
remove(root).map_err(ioe)?;
load(root).map_err(failure)?
}
Err(error) => return Err(failure(error)),
};
Ok(Self {
root: root.into(),
streams: RwLock::new(streams),
checkpoint: Mutex::new(checkpoint),
poisoned: AtomicBool::new(false),
})
}
pub fn apply(&self, id: TxId, event: &Event) -> Result<ApplyOutcome, String> {
self.ready()?;
let result = match event {
Event::Register { stream, .. } => self.register(id, stream),
Event::Submit {
actor,
stream,
operation_id,
payload,
} => self.submit(id, *actor, stream, *operation_id, payload),
};
if result.is_err() {
self.poisoned.store(true, Ordering::Release);
}
result
}
pub fn registered(&self, stream: &ExternalSubsystem) -> Result<bool, String> {
self.ready()?;
Ok(self.map()?.contains_key(stream))
}
pub fn operation(
&self,
stream: &ExternalSubsystem,
operation: [u8; 32],
) -> Result<Option<ExternalUpdate>, String> {
self.ready()?;
let Some(stream) = self.stream(stream)? else {
return Ok(None);
};
let stream = lock(&stream)?;
stream
.operations
.get(&operation)
.map(|&i| read(&stream, i))
.transpose()
}
pub fn history(
&self,
key: &ExternalSubsystem,
after: Option<TxId>,
) -> Result<Option<Vec<ExternalUpdate>>, String> {
self.ready()?;
let Some(stream) = self.stream(key)? else {
return Ok(None);
};
let stream = lock(&stream)?;
let start =
match after {
None => 0,
Some(id) => {
stream.progress.get(&id).copied().ok_or_else(|| {
"external subsystem progress is not in this stream".to_owned()
})? + 1
}
};
(start..stream.records.len())
.map(|i| read(&stream, i))
.collect::<Result<_, _>>()
.map(Some)
}
pub fn checkpoint(&self) -> Result<Option<TxId>, String> {
self.ready()?;
self.checkpoint
.lock()
.map(|value| *value)
.map_err(|_| "ESE checkpoint lock poisoned".into())
}
pub fn discard(&self) -> Result<(), String> {
self.ready()?;
let result = remove(&self.root).map_err(ioe);
self.poisoned.store(true, Ordering::Release);
result
}
fn register(&self, id: TxId, key: &ExternalSubsystem) -> Result<ApplyOutcome, String> {
let mut map = self
.streams
.write()
.map_err(|_| "ESE stream map lock poisoned".to_owned())?;
if !map.contains_key(key) {
map.insert(
key.clone(),
Arc::new(Mutex::new(create(&self.root.join("streams"), key)?)),
);
}
drop(map);
self.advance(id)?;
Ok(ApplyOutcome::Registered)
}
fn submit(
&self,
id: TxId,
actor: UserId,
key: &ExternalSubsystem,
operation: [u8; 32],
payload: &[u8],
) -> Result<ApplyOutcome, String> {
let stream = self
.stream(key)?
.ok_or_else(|| "external subsystem is not registered".to_owned())?;
let (progress, duplicate) = {
let mut stream = lock(&stream)?;
if let Some(&i) = stream.progress.get(&id) {
let record = stream.records[i];
let update = read(&stream, i)?;
if record.actor != actor
|| record.operation != operation
|| update.payload() != payload
{
return Err("external subsystem transaction replay mismatch".into());
}
(id, true)
} else if let Some(&i) = stream.operations.get(&operation) {
let update = read(&stream, i)?;
if update.payload() != payload {
return Err(
"external subsystem operation conflicts with its existing payload".into(),
);
}
(update.progress(), true)
} else {
append(&mut stream, id, actor, operation, payload)?;
(id, false)
}
};
self.advance(id)?;
Ok(ApplyOutcome::Submitted {
progress,
duplicate,
})
}
fn stream(&self, key: &ExternalSubsystem) -> Result<Option<Ref>, String> {
Ok(self.map()?.get(key).cloned())
}
fn map(&self) -> Result<std::sync::RwLockReadGuard<'_, Map>, String> {
self.streams
.read()
.map_err(|_| "ESE stream map lock poisoned".into())
}
fn advance(&self, id: TxId) -> Result<(), String> {
let mut current = self
.checkpoint
.lock()
.map_err(|_| "ESE checkpoint lock poisoned".to_owned())?;
if *current != Some(id) {
let mut file = append_file(&self.root.join("checkpoint"))?;
file.write_all(&check_record(id))
.and_then(|_| file.sync_data())
.map_err(ioe)?;
*current = Some(id);
}
Ok(())
}
fn ready(&self) -> Result<(), String> {
if self.poisoned.load(Ordering::Acquire) {
Err("ESE store is unavailable".into())
} else {
Ok(())
}
}
}
#[rustfmt::skip]
fn lock(stream: &Ref) -> Result<std::sync::MutexGuard<'_, Stream>, String> { stream.lock().map_err(|_| "ESE stream lock poisoned".into()) }
#[rustfmt::skip]
fn empty(path: PathBuf) -> Stream { Stream { path, records: vec![], operations: HashMap::new(), progress: HashMap::new() } }
#[rustfmt::skip]
fn create(dir: &Path, key: &ExternalSubsystem) -> Result<Stream, String> {
let path = dir.join(format!("{}.ese", hex(&hash(key))));
match kind(&path).map_err(ioe)? {
None => { let mut file = OpenOptions::new().write(true).create_new(true).open(&path).map_err(ioe)?; file.write_all(&header(key)?).and_then(|_| file.sync_data()).map_err(ioe)?; sync(dir).map_err(ioe)?; Ok(empty(path)) }
Some(kind) if kind.is_file() => { let bytes = fs::read(&path).map_err(ioe)?; if parse_header(&bytes).map_err(failure)?.0 != *key { return Err("ESE stream file identity mismatch".into()) } parse_stream(&path).map_err(failure) }
Some(_) => Err(ioe(invalid(&path, "regular file"))),
}
}
#[rustfmt::skip]
fn append(stream: &mut Stream, progress: TxId, actor: UserId, operation: [u8; 32], payload: &[u8]) -> Result<(), String> {
let len = FIXED.checked_add(payload.len()).ok_or_else(|| "ESE update length exceeds usize".to_owned())?;
let mut body = Vec::with_capacity(len); body.extend_from_slice(progress.as_bytes()); body.extend_from_slice(actor.as_tx_id().as_bytes()); body.extend_from_slice(&operation); body.extend_from_slice(&u64::try_from(payload.len()).map_err(|_| "ESE payload length exceeds u64")?.to_le_bytes()); body.extend_from_slice(payload);
let mut file = OpenOptions::new().append(true).open(&stream.path).map_err(ioe)?; let start = file.metadata().map_err(ioe)?.len();
file.write_all(&u64::try_from(len).map_err(|_| "ESE update length exceeds u64")?.to_le_bytes()).and_then(|_| file.write_all(&body)).and_then(|_| file.write_all(&Sha256::digest(&body))).and_then(|_| file.sync_data()).map_err(ioe)?;
let i = stream.records.len(); stream.records.push(Record { progress, actor, operation, at: start + 8 + FIXED as u64, len: payload.len() }); stream.operations.insert(operation, i); stream.progress.insert(progress, i); Ok(())
}
#[rustfmt::skip]
fn read(stream: &Stream, i: usize) -> Result<ExternalUpdate, String> {
let record = stream.records[i]; let mut payload = vec![0; record.len]; let mut file = File::open(&stream.path).map_err(ioe)?; file.seek(SeekFrom::Start(record.at)).and_then(|_| file.read_exact(&mut payload)).map_err(ioe)?; Ok(ExternalUpdate { progress: record.progress, operation_id: record.operation, payload })
}
#[rustfmt::skip]
fn load(root: &Path) -> Result<(Map, Option<TxId>), Failure> {
ensure(root).map_err(Failure::Io)?; let dir = root.join("streams"); ensure(&dir).map_err(Failure::Io)?; let mut map = HashMap::new();
for item in fs::read_dir(&dir).map_err(Failure::Io)? {
let item = item.map_err(Failure::Io)?; if !item.file_type().map_err(Failure::Io)?.is_file() { return Err(Failure::Io(invalid(&item.path(), "regular file"))) }
let bytes = fs::read(item.path()).map_err(Failure::Io)?; let key = parse_header(&bytes)?.0; let name = format!("{}.ese", hex(&hash(&key)));
if item.file_name().to_str() != Some(&name) || map.insert(key, Arc::new(Mutex::new(parse_stream(&item.path())?))).is_some() { return Err(Failure::Bad) }
}
Ok((map, load_checkpoint(&root.join("checkpoint"))?))
}
#[rustfmt::skip]
fn parse_stream(path: &Path) -> Result<Stream, Failure> {
let bytes = fs::read(path).map_err(Failure::Io)?; let (_, mut at) = parse_header(&bytes)?; let mut stream = empty(path.into());
while at < bytes.len() {
let start = at; if bytes.len() - at < 8 { truncate(path, start)?; break }
let len = usize::try_from(u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())).map_err(|_| Failure::Bad)?; at += 8;
let end = at.checked_add(len).and_then(|v| v.checked_add(32)).ok_or(Failure::Bad)?; if end > bytes.len() { truncate(path, start)?; break }
if len < FIXED || Sha256::digest(&bytes[at..at + len]).as_slice() != &bytes[at + len..end] { return Err(Failure::Bad) }
let body = &bytes[at..at + len]; let progress = TxId::from_bytes(body[..12].try_into().unwrap()); let actor = UserId::from_tx_id(TxId::from_bytes(body[12..24].try_into().unwrap())); let operation = body[24..56].try_into().unwrap(); let payload_len = usize::try_from(u64::from_le_bytes(body[56..64].try_into().unwrap())).map_err(|_| Failure::Bad)?;
if payload_len != len - FIXED || stream.progress.contains_key(&progress) || stream.operations.contains_key(&operation) { return Err(Failure::Bad) }
let i = stream.records.len(); stream.records.push(Record { progress, actor, operation, at: u64::try_from(at + FIXED).map_err(|_| Failure::Bad)?, len: payload_len }); stream.progress.insert(progress, i); stream.operations.insert(operation, i); at = end;
}
Ok(stream)
}
#[rustfmt::skip]
fn identity(key: &ExternalSubsystem) -> Result<Vec<u8>, String> {
let (tag, id) = match key.authority() { Authority::User(value) => (1, value.as_tx_id()), Authority::Group(value) => (2, value.txid()) };
let mut out = vec![tag]; out.extend_from_slice(id.as_bytes()); out.extend_from_slice(&u64::try_from(key.name().len()).map_err(|_| "ESE name length exceeds u64")?.to_le_bytes()); out.extend_from_slice(key.name().as_bytes()); Ok(out)
}
#[rustfmt::skip]
fn hash(key: &ExternalSubsystem) -> [u8; 32] { Sha256::digest(identity(key).expect("name fits u64")).into() }
#[rustfmt::skip]
fn header(key: &ExternalSubsystem) -> Result<Vec<u8>, String> { let mut out = MAGIC.to_vec(); out.extend_from_slice(&identity(key)?); let digest = Sha256::digest(&out); out.extend_from_slice(&digest); Ok(out) }
#[rustfmt::skip]
fn parse_header(bytes: &[u8]) -> Result<(ExternalSubsystem, usize), Failure> {
if bytes.len() < 61 || &bytes[..8] != MAGIC { return Err(Failure::Bad) }
let id = TxId::from_bytes(bytes[9..21].try_into().unwrap()); let len = usize::try_from(u64::from_le_bytes(bytes[21..29].try_into().unwrap())).map_err(|_| Failure::Bad)?; let end = 29usize.checked_add(len).ok_or(Failure::Bad)?;
if end.checked_add(32).is_none_or(|v| v > bytes.len()) || Sha256::digest(&bytes[..end]).as_slice() != &bytes[end..end + 32] { return Err(Failure::Bad) }
let authority = match bytes[8] { 1 => Authority::User(UserId::from_tx_id(id)), 2 => Authority::Group(kcode_k1_ese_format::GroupId::new(id)), _ => return Err(Failure::Bad) };
let name = std::str::from_utf8(&bytes[29..end]).map_err(|_| Failure::Bad)?.to_owned(); ExternalSubsystem::new(authority, name).map(|key| (key, end + 32)).map_err(|_| Failure::Bad)
}
#[rustfmt::skip]
fn load_checkpoint(path: &Path) -> Result<Option<TxId>, Failure> {
match kind(path).map_err(Failure::Io)? { None => return Ok(None), Some(kind) if kind.is_file() => {}, Some(_) => return Err(Failure::Io(invalid(path, "regular file"))) }
let bytes = fs::read(path).map_err(Failure::Io)?; let complete = bytes.len() / 16 * 16; if complete != bytes.len() { truncate(path, complete)? }
let mut last = None; for record in bytes[..complete].chunks_exact(16) { let id = TxId::from_bytes(record[..12].try_into().unwrap()); if record[12..] != checksum(id.as_bytes()).to_le_bytes() { return Err(Failure::Bad) } last = Some(id); } Ok(last)
}
#[rustfmt::skip]
fn check_record(id: TxId) -> [u8; 16] { let mut out = [0; 16]; out[..12].copy_from_slice(id.as_bytes()); out[12..].copy_from_slice(&checksum(id.as_bytes()).to_le_bytes()); out }
#[rustfmt::skip]
fn checksum(bytes: &[u8; 12]) -> u32 { bytes.iter().fold(2_166_136_261, |sum, byte| (sum ^ u32::from(*byte)).wrapping_mul(16_777_619)) }
#[rustfmt::skip]
fn truncate(path: &Path, len: usize) -> Result<(), Failure> { let file = OpenOptions::new().write(true).open(path).map_err(Failure::Io)?; file.set_len(u64::try_from(len).map_err(|_| Failure::Bad)?).and_then(|_| file.sync_data()).map_err(Failure::Io) }
#[rustfmt::skip]
fn append_file(path: &Path) -> Result<File, String> { match kind(path).map_err(ioe)? { None => { let file = OpenOptions::new().append(true).create_new(true).open(path).map_err(ioe)?; sync(path.parent().unwrap_or(Path::new("."))).map_err(ioe)?; Ok(file) }, Some(kind) if kind.is_file() => OpenOptions::new().append(true).open(path).map_err(ioe), Some(_) => Err(ioe(invalid(path, "regular file"))) } }
#[rustfmt::skip]
fn ensure(path: &Path) -> io::Result<()> { match kind(path)? { Some(kind) if kind.is_dir() => Ok(()), Some(_) => Err(invalid(path, "directory")), None => { if let Some(parent) = path.parent().filter(|v| !v.as_os_str().is_empty()) { ensure(parent)? } fs::create_dir(path)?; sync(path.parent().unwrap_or(Path::new("."))) } } }
#[rustfmt::skip]
fn remove(path: &Path) -> io::Result<()> { match kind(path)? { None => Ok(()), Some(kind) if kind.is_dir() => { fs::remove_dir_all(path)?; sync(path.parent().unwrap_or(Path::new("."))) }, Some(_) => Err(invalid(path, "directory")) } }
#[rustfmt::skip]
fn sync(path: &Path) -> io::Result<()> { File::open(path)?.sync_all() }
#[rustfmt::skip]
fn kind(path: &Path) -> io::Result<Option<FileType>> { match fs::symlink_metadata(path) { Ok(meta) => Ok(Some(meta.file_type())), Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), Err(error) => Err(error) } }
#[rustfmt::skip]
fn invalid(path: &Path, expected: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, format!("{} is not a real {expected}", path.display())) }
#[rustfmt::skip]
fn ioe(error: io::Error) -> String { format!("ESE store I/O: {error}") }
#[rustfmt::skip]
fn failure(error: Failure) -> String { match error { Failure::Io(error) => ioe(error), Failure::Bad => "ESE derived state is malformed".into() } }
#[rustfmt::skip]
fn hex(bytes: &[u8]) -> String { const D: &[u8; 16] = b"0123456789abcdef"; bytes.iter().flat_map(|b| [D[(b >> 4) as usize] as char, D[(b & 15) as usize] as char]).collect() }
enum Failure {
Io(io::Error),
Bad,
}
#[cfg(test)]
#[rustfmt::skip]
mod tests {
use super::*;
fn tx(v: u8) -> TxId { TxId::from_bytes([v; 12]) }
fn user(v: u8) -> UserId { UserId::from_tx_id(tx(v)) }
fn key(v: &str) -> ExternalSubsystem { ExternalSubsystem::new(Authority::User(user(1)), v.into()).unwrap() }
fn reg(v: &str) -> Event { Event::Register { actor: user(1), stream: key(v) } }
fn sub(v: &str, op: u8, bytes: &[u8]) -> Event { Event::Submit { actor: user(1), stream: key(v), operation_id: [op; 32], payload: bytes.into() } }
#[test]
fn lifecycle_restart_and_cursor() {
let root = tempfile::tempdir().unwrap(); let store = EseStore::open(root.path()).unwrap(); store.apply(tx(1), ®("a")).unwrap(); store.apply(tx(2), &sub("a", 3, b"x")).unwrap();
assert_eq!(store.apply(tx(4), &sub("a", 3, b"x")).unwrap(), ApplyOutcome::Submitted { progress: tx(2), duplicate: true }); assert_eq!(store.checkpoint().unwrap(), Some(tx(4))); assert_eq!(store.history(&key("a"), None).unwrap().unwrap()[0].payload(), b"x"); drop(store);
let store = EseStore::open(root.path()).unwrap(); assert_eq!(store.operation(&key("a"), [3; 32]).unwrap().unwrap().progress(), tx(2)); assert!(store.history(&key("a"), Some(tx(9))).is_err()); assert!(store.history(&key("b"), Some(tx(2))).unwrap().is_none());
}
#[test]
fn conflict_faults_and_malformed_resets_only_root() {
let parent = tempfile::tempdir().unwrap(); fs::write(parent.path().join("keep"), b"yes").unwrap(); let root = parent.path().join("ese"); let store = EseStore::open(&root).unwrap(); store.apply(tx(1), ®("a")).unwrap(); store.apply(tx(2), &sub("a", 3, b"x")).unwrap(); assert!(store.apply(tx(4), &sub("a", 3, b"y")).is_err()); assert!(store.registered(&key("a")).is_err()); drop(store);
let path = fs::read_dir(root.join("streams")).unwrap().next().unwrap().unwrap().path(); fs::write(path, b"bad").unwrap(); assert!(!EseStore::open(&root).unwrap().registered(&key("a")).unwrap()); assert_eq!(fs::read(parent.path().join("keep")).unwrap(), b"yes");
}
#[test]
fn package_is_bounded() { let files = [include_str!("../Cargo.toml"), include_str!("../Documentation.md"), include_str!("lib.rs")]; let count = files.iter().flat_map(|v| v.lines()).filter(|v| !v.trim().is_empty()).count(); assert!(count < 500, "{count}"); }
}