Skip to main content

kcode_k1_ese_store/
lib.rs

1pub use kcode_k1_ese_format::{Authority, Event, ExternalSubsystem, TxId, UserId};
2use sha2::{Digest, Sha256};
3use std::{
4    collections::HashMap,
5    fs::{self, File, FileType, OpenOptions},
6    io::{self, Read, Seek, SeekFrom, Write},
7    path::{Path, PathBuf},
8    sync::{
9        Arc, Mutex, RwLock,
10        atomic::{AtomicBool, Ordering},
11    },
12};
13
14const MAGIC: &[u8; 8] = b"K1ESE01\0";
15const FIXED: usize = 64;
16type Ref = Arc<Mutex<Stream>>;
17type Map = HashMap<ExternalSubsystem, Ref>;
18
19#[derive(Clone, Debug, Eq, PartialEq)]
20pub struct ExternalUpdate {
21    progress: TxId,
22    operation_id: [u8; 32],
23    payload: Vec<u8>,
24}
25impl ExternalUpdate {
26    pub const fn progress(&self) -> TxId {
27        self.progress
28    }
29    pub const fn operation_id(&self) -> &[u8; 32] {
30        &self.operation_id
31    }
32    pub fn payload(&self) -> &[u8] {
33        &self.payload
34    }
35}
36
37#[derive(Clone, Debug, Eq, PartialEq)]
38pub enum ApplyOutcome {
39    Registered,
40    Submitted { progress: TxId, duplicate: bool },
41}
42
43#[derive(Clone, Copy)]
44struct Record {
45    progress: TxId,
46    actor: UserId,
47    operation: [u8; 32],
48    at: u64,
49    len: usize,
50}
51struct Stream {
52    path: PathBuf,
53    records: Vec<Record>,
54    operations: HashMap<[u8; 32], usize>,
55    progress: HashMap<TxId, usize>,
56}
57pub struct EseStore {
58    root: PathBuf,
59    streams: RwLock<Map>,
60    checkpoint: Mutex<Option<TxId>>,
61    poisoned: AtomicBool,
62}
63
64impl EseStore {
65    pub fn open(root: &Path) -> Result<Self, String> {
66        let (streams, checkpoint) = match load(root) {
67            Ok(value) => value,
68            Err(Failure::Bad) => {
69                remove(root).map_err(ioe)?;
70                load(root).map_err(failure)?
71            }
72            Err(error) => return Err(failure(error)),
73        };
74        Ok(Self {
75            root: root.into(),
76            streams: RwLock::new(streams),
77            checkpoint: Mutex::new(checkpoint),
78            poisoned: AtomicBool::new(false),
79        })
80    }
81
82    pub fn apply(&self, id: TxId, event: &Event) -> Result<ApplyOutcome, String> {
83        self.ready()?;
84        let result = match event {
85            Event::Register { stream, .. } => self.register(id, stream),
86            Event::Submit {
87                actor,
88                stream,
89                operation_id,
90                payload,
91            } => self.submit(id, *actor, stream, *operation_id, payload),
92        };
93        if result.is_err() {
94            self.poisoned.store(true, Ordering::Release);
95        }
96        result
97    }
98
99    pub fn registered(&self, stream: &ExternalSubsystem) -> Result<bool, String> {
100        self.ready()?;
101        Ok(self.map()?.contains_key(stream))
102    }
103
104    pub fn operation(
105        &self,
106        stream: &ExternalSubsystem,
107        operation: [u8; 32],
108    ) -> Result<Option<ExternalUpdate>, String> {
109        self.ready()?;
110        let Some(stream) = self.stream(stream)? else {
111            return Ok(None);
112        };
113        let stream = lock(&stream)?;
114        stream
115            .operations
116            .get(&operation)
117            .map(|&i| read(&stream, i))
118            .transpose()
119    }
120
121    pub fn history(
122        &self,
123        key: &ExternalSubsystem,
124        after: Option<TxId>,
125    ) -> Result<Option<Vec<ExternalUpdate>>, String> {
126        self.ready()?;
127        let Some(stream) = self.stream(key)? else {
128            return Ok(None);
129        };
130        let stream = lock(&stream)?;
131        let start =
132            match after {
133                None => 0,
134                Some(id) => {
135                    stream.progress.get(&id).copied().ok_or_else(|| {
136                        "external subsystem progress is not in this stream".to_owned()
137                    })? + 1
138                }
139            };
140        (start..stream.records.len())
141            .map(|i| read(&stream, i))
142            .collect::<Result<_, _>>()
143            .map(Some)
144    }
145
146    pub fn checkpoint(&self) -> Result<Option<TxId>, String> {
147        self.ready()?;
148        self.checkpoint
149            .lock()
150            .map(|value| *value)
151            .map_err(|_| "ESE checkpoint lock poisoned".into())
152    }
153
154    pub fn discard(&self) -> Result<(), String> {
155        self.ready()?;
156        let result = remove(&self.root).map_err(ioe);
157        self.poisoned.store(true, Ordering::Release);
158        result
159    }
160
161    fn register(&self, id: TxId, key: &ExternalSubsystem) -> Result<ApplyOutcome, String> {
162        let mut map = self
163            .streams
164            .write()
165            .map_err(|_| "ESE stream map lock poisoned".to_owned())?;
166        if !map.contains_key(key) {
167            map.insert(
168                key.clone(),
169                Arc::new(Mutex::new(create(&self.root.join("streams"), key)?)),
170            );
171        }
172        drop(map);
173        self.advance(id)?;
174        Ok(ApplyOutcome::Registered)
175    }
176
177    fn submit(
178        &self,
179        id: TxId,
180        actor: UserId,
181        key: &ExternalSubsystem,
182        operation: [u8; 32],
183        payload: &[u8],
184    ) -> Result<ApplyOutcome, String> {
185        let stream = self
186            .stream(key)?
187            .ok_or_else(|| "external subsystem is not registered".to_owned())?;
188        let (progress, duplicate) = {
189            let mut stream = lock(&stream)?;
190            if let Some(&i) = stream.progress.get(&id) {
191                let record = stream.records[i];
192                let update = read(&stream, i)?;
193                if record.actor != actor
194                    || record.operation != operation
195                    || update.payload() != payload
196                {
197                    return Err("external subsystem transaction replay mismatch".into());
198                }
199                (id, true)
200            } else if let Some(&i) = stream.operations.get(&operation) {
201                let update = read(&stream, i)?;
202                if update.payload() != payload {
203                    return Err(
204                        "external subsystem operation conflicts with its existing payload".into(),
205                    );
206                }
207                (update.progress(), true)
208            } else {
209                append(&mut stream, id, actor, operation, payload)?;
210                (id, false)
211            }
212        };
213        self.advance(id)?;
214        Ok(ApplyOutcome::Submitted {
215            progress,
216            duplicate,
217        })
218    }
219
220    fn stream(&self, key: &ExternalSubsystem) -> Result<Option<Ref>, String> {
221        Ok(self.map()?.get(key).cloned())
222    }
223
224    fn map(&self) -> Result<std::sync::RwLockReadGuard<'_, Map>, String> {
225        self.streams
226            .read()
227            .map_err(|_| "ESE stream map lock poisoned".into())
228    }
229
230    fn advance(&self, id: TxId) -> Result<(), String> {
231        let mut current = self
232            .checkpoint
233            .lock()
234            .map_err(|_| "ESE checkpoint lock poisoned".to_owned())?;
235        if *current != Some(id) {
236            let mut file = append_file(&self.root.join("checkpoint"))?;
237            file.write_all(&check_record(id))
238                .and_then(|_| file.sync_data())
239                .map_err(ioe)?;
240            *current = Some(id);
241        }
242        Ok(())
243    }
244
245    fn ready(&self) -> Result<(), String> {
246        if self.poisoned.load(Ordering::Acquire) {
247            Err("ESE store is unavailable".into())
248        } else {
249            Ok(())
250        }
251    }
252}
253
254#[rustfmt::skip]
255fn lock(stream: &Ref) -> Result<std::sync::MutexGuard<'_, Stream>, String> { stream.lock().map_err(|_| "ESE stream lock poisoned".into()) }
256#[rustfmt::skip]
257fn empty(path: PathBuf) -> Stream { Stream { path, records: vec![], operations: HashMap::new(), progress: HashMap::new() } }
258#[rustfmt::skip]
259fn create(dir: &Path, key: &ExternalSubsystem) -> Result<Stream, String> {
260    let path = dir.join(format!("{}.ese", hex(&hash(key))));
261    match kind(&path).map_err(ioe)? {
262        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)) }
263        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) }
264        Some(_) => Err(ioe(invalid(&path, "regular file"))),
265    }
266}
267#[rustfmt::skip]
268fn append(stream: &mut Stream, progress: TxId, actor: UserId, operation: [u8; 32], payload: &[u8]) -> Result<(), String> {
269    let len = FIXED.checked_add(payload.len()).ok_or_else(|| "ESE update length exceeds usize".to_owned())?;
270    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);
271    let mut file = OpenOptions::new().append(true).open(&stream.path).map_err(ioe)?; let start = file.metadata().map_err(ioe)?.len();
272    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)?;
273    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(())
274}
275#[rustfmt::skip]
276fn read(stream: &Stream, i: usize) -> Result<ExternalUpdate, String> {
277    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 })
278}
279#[rustfmt::skip]
280fn load(root: &Path) -> Result<(Map, Option<TxId>), Failure> {
281    ensure(root).map_err(Failure::Io)?; let dir = root.join("streams"); ensure(&dir).map_err(Failure::Io)?; let mut map = HashMap::new();
282    for item in fs::read_dir(&dir).map_err(Failure::Io)? {
283        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"))) }
284        let bytes = fs::read(item.path()).map_err(Failure::Io)?; let key = parse_header(&bytes)?.0; let name = format!("{}.ese", hex(&hash(&key)));
285        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) }
286    }
287    Ok((map, load_checkpoint(&root.join("checkpoint"))?))
288}
289#[rustfmt::skip]
290fn parse_stream(path: &Path) -> Result<Stream, Failure> {
291    let bytes = fs::read(path).map_err(Failure::Io)?; let (_, mut at) = parse_header(&bytes)?; let mut stream = empty(path.into());
292    while at < bytes.len() {
293        let start = at; if bytes.len() - at < 8 { truncate(path, start)?; break }
294        let len = usize::try_from(u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())).map_err(|_| Failure::Bad)?; at += 8;
295        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 }
296        if len < FIXED || Sha256::digest(&bytes[at..at + len]).as_slice() != &bytes[at + len..end] { return Err(Failure::Bad) }
297        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)?;
298        if payload_len != len - FIXED || stream.progress.contains_key(&progress) || stream.operations.contains_key(&operation) { return Err(Failure::Bad) }
299        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;
300    }
301    Ok(stream)
302}
303#[rustfmt::skip]
304fn identity(key: &ExternalSubsystem) -> Result<Vec<u8>, String> {
305    let (tag, id) = match key.authority() { Authority::User(value) => (1, value.as_tx_id()), Authority::Group(value) => (2, value.txid()) };
306    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)
307}
308#[rustfmt::skip]
309fn hash(key: &ExternalSubsystem) -> [u8; 32] { Sha256::digest(identity(key).expect("name fits u64")).into() }
310#[rustfmt::skip]
311fn 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) }
312#[rustfmt::skip]
313fn parse_header(bytes: &[u8]) -> Result<(ExternalSubsystem, usize), Failure> {
314    if bytes.len() < 61 || &bytes[..8] != MAGIC { return Err(Failure::Bad) }
315    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)?;
316    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) }
317    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) };
318    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)
319}
320#[rustfmt::skip]
321fn load_checkpoint(path: &Path) -> Result<Option<TxId>, Failure> {
322    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"))) }
323    let bytes = fs::read(path).map_err(Failure::Io)?; let complete = bytes.len() / 16 * 16; if complete != bytes.len() { truncate(path, complete)? }
324    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)
325}
326#[rustfmt::skip]
327fn 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 }
328#[rustfmt::skip]
329fn checksum(bytes: &[u8; 12]) -> u32 { bytes.iter().fold(2_166_136_261, |sum, byte| (sum ^ u32::from(*byte)).wrapping_mul(16_777_619)) }
330#[rustfmt::skip]
331fn 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) }
332#[rustfmt::skip]
333fn 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"))) } }
334#[rustfmt::skip]
335fn 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("."))) } } }
336#[rustfmt::skip]
337fn 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")) } }
338#[rustfmt::skip]
339fn sync(path: &Path) -> io::Result<()> { File::open(path)?.sync_all() }
340#[rustfmt::skip]
341fn 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) } }
342#[rustfmt::skip]
343fn invalid(path: &Path, expected: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, format!("{} is not a real {expected}", path.display())) }
344#[rustfmt::skip]
345fn ioe(error: io::Error) -> String { format!("ESE store I/O: {error}") }
346#[rustfmt::skip]
347fn failure(error: Failure) -> String { match error { Failure::Io(error) => ioe(error), Failure::Bad => "ESE derived state is malformed".into() } }
348#[rustfmt::skip]
349fn 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() }
350
351enum Failure {
352    Io(io::Error),
353    Bad,
354}
355
356#[cfg(test)]
357#[rustfmt::skip]
358mod tests {
359    use super::*;
360    fn tx(v: u8) -> TxId { TxId::from_bytes([v; 12]) }
361    fn user(v: u8) -> UserId { UserId::from_tx_id(tx(v)) }
362    fn key(v: &str) -> ExternalSubsystem { ExternalSubsystem::new(Authority::User(user(1)), v.into()).unwrap() }
363    fn reg(v: &str) -> Event { Event::Register { actor: user(1), stream: key(v) } }
364    fn sub(v: &str, op: u8, bytes: &[u8]) -> Event { Event::Submit { actor: user(1), stream: key(v), operation_id: [op; 32], payload: bytes.into() } }
365    #[test]
366    fn lifecycle_restart_and_cursor() {
367        let root = tempfile::tempdir().unwrap(); let store = EseStore::open(root.path()).unwrap(); store.apply(tx(1), &reg("a")).unwrap(); store.apply(tx(2), &sub("a", 3, b"x")).unwrap();
368        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);
369        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());
370    }
371    #[test]
372    fn conflict_faults_and_malformed_resets_only_root() {
373        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), &reg("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);
374        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");
375    }
376    #[test]
377    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}"); }
378}