1use crate::{JournalEntry, JournalError, JournalHead, StoredDatumRef};
7use sha2::{Digest, Sha256};
8use sim_kernel::{ContentId, Datum, Symbol};
9use sim_storage_port::HostDirPort;
10
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct BackendCapabilities {
14 pub linearizable_cas: bool,
16 pub durable_publish: bool,
18}
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum NativeFormatId {
23 V1,
25 V2,
27}
28
29#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
31pub struct EntryNamespace(pub String);
32
33#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
35pub struct EntryLocation {
36 pub namespace: EntryNamespace,
37 pub sequence: u64,
38 pub entry: ContentId,
39 pub storage: ContentId,
40}
41
42#[derive(Clone, Debug, Eq, PartialEq)]
44pub struct VerifiedNativePrefixRef {
45 pub entries: u64,
46 pub physical_head: JournalHead,
47 pub canonical_head: JournalHead,
48 pub descriptor: ContentId,
49}
50
51#[derive(Clone, Debug, Eq, PartialEq)]
53pub struct NativeStateEnvelope {
54 pub format: NativeFormatId,
55 pub fence: u64,
56 pub namespace: EntryNamespace,
57 pub prefix: Option<VerifiedNativePrefixRef>,
58 pub head: Option<JournalHead>,
59 pub head_location: Option<EntryLocation>,
60}
61
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
64pub enum Failpoint {
65 BeforePrefixDescriptor,
66 AfterPrefixDescriptor,
67 AfterNamespaceReservation,
68 BeforeFormatCas,
69 AfterFormatCas,
70 BeforeObjectPublish,
71 AfterObjectPublish,
72 AfterDurabilityReceipt,
73 BeforeCas,
74 AfterCas,
75 BeforeAcknowledgement,
76}
77
78impl Failpoint {
79 #[cfg(any(test, feature = "fault-injection"))]
80 pub(crate) fn label(self) -> &'static str {
81 match self {
82 Self::BeforePrefixDescriptor => "before-prefix-descriptor",
83 Self::AfterPrefixDescriptor => "after-prefix-descriptor",
84 Self::AfterNamespaceReservation => "after-namespace-reservation",
85 Self::BeforeFormatCas => "before-format-cas",
86 Self::AfterFormatCas => "after-format-cas",
87 Self::BeforeObjectPublish => "before-object-publish",
88 Self::AfterObjectPublish => "after-object-publish",
89 Self::AfterDurabilityReceipt => "after-durability-receipt",
90 Self::BeforeCas => "before-cas",
91 Self::AfterCas => "after-cas",
92 Self::BeforeAcknowledgement => "before-acknowledgement",
93 }
94 }
95}
96
97#[derive(Clone)]
98pub(crate) struct PhysicalEntry {
99 pub(crate) entry: JournalEntry,
100 pub(crate) previous_location: Option<EntryLocation>,
101 pub(crate) payloads: Vec<StoredDatumRef>,
102}
103
104#[derive(Clone)]
105pub(crate) struct V1Entry {
106 pub(crate) id: ContentId,
107 pub(crate) sequence: u64,
108 pub(crate) previous: Option<ContentId>,
109 pub(crate) kind: Symbol,
110 pub(crate) payloads: Vec<ContentId>,
111}
112
113impl V1Entry {
114 pub(crate) fn canonical_id(&self) -> ContentId {
115 let mut hasher = Sha256::new();
116 hasher.update(b"sim-journal-entry-v1\0");
117 hasher.update(self.sequence.to_be_bytes());
118 put_v1_optional_id_hash(&mut hasher, self.previous.as_ref());
119 put_v1_symbol_hash(&mut hasher, &self.kind);
120 hasher.update((self.payloads.len() as u64).to_be_bytes());
121 for id in &self.payloads {
122 put_v1_id_hash(&mut hasher, id);
123 }
124 ContentId::from_bytes(
125 Symbol::qualified("journal", "sha256-entry-v1"),
126 hasher.finalize().into(),
127 )
128 }
129}
130
131pub(crate) fn encode_envelope(value: &NativeStateEnvelope) -> Vec<u8> {
132 let mut out = b"SIMJSTATE2".to_vec();
133 out.extend(value.fence.to_be_bytes());
134 put_text(&mut out, &value.namespace.0);
135 match &value.prefix {
136 Some(prefix) => {
137 out.push(1);
138 out.extend(prefix.entries.to_be_bytes());
139 put_head(&mut out, &prefix.physical_head);
140 put_head(&mut out, &prefix.canonical_head);
141 put_id(&mut out, &prefix.descriptor);
142 }
143 None => out.push(0),
144 }
145 put_optional_head(&mut out, value.head.as_ref());
146 put_optional_location(&mut out, value.head_location.as_ref());
147 out
148}
149
150pub(crate) fn decode_envelope(bytes: &[u8]) -> Result<NativeStateEnvelope, JournalError> {
151 let mut cursor = Cursor::new(bytes);
152 if cursor.take(10)? != b"SIMJSTATE2" {
153 return Err(JournalError::CorruptState("state format"));
154 }
155 let fence = cursor.u64()?;
156 let namespace = EntryNamespace(cursor.text()?);
157 let prefix = match cursor.byte()? {
158 0 => None,
159 1 => Some(VerifiedNativePrefixRef {
160 entries: cursor.u64()?,
161 physical_head: cursor.head()?,
162 canonical_head: cursor.head()?,
163 descriptor: cursor.id()?,
164 }),
165 _ => return Err(JournalError::CorruptState("prefix tag")),
166 };
167 let head = cursor.optional_head()?;
168 let head_location = cursor.optional_location()?;
169 cursor.end()?;
170 if prefix.is_none() && head.is_some() && head_location.is_none() {
171 return Err(JournalError::CorruptState("head without locator"));
172 }
173 Ok(NativeStateEnvelope {
174 format: NativeFormatId::V2,
175 fence,
176 namespace,
177 prefix,
178 head,
179 head_location,
180 })
181}
182
183pub(crate) fn encode_descriptor(old_state: &[u8], canonical_head: &JournalHead) -> Vec<u8> {
184 let mut out = b"SIMJPREFIX1".to_vec();
185 out.extend((old_state.len() as u64).to_be_bytes());
186 out.extend(old_state);
187 put_head(&mut out, canonical_head);
188 out
189}
190
191pub(crate) fn decode_descriptor(bytes: &[u8]) -> Result<(Vec<u8>, JournalHead), JournalError> {
192 let mut cursor = Cursor::new(bytes);
193 if cursor.take(11)? != b"SIMJPREFIX1" {
194 return Err(JournalError::CorruptState("prefix descriptor"));
195 }
196 let len = usize::try_from(cursor.u64()?).map_err(|_| JournalError::WorkBoundExceeded)?;
197 let state = cursor.take(len)?.to_vec();
198 let canonical_head = cursor.head()?;
199 cursor.end()?;
200 Ok((state, canonical_head))
201}
202
203pub(crate) fn encode_v2_entry(value: &PhysicalEntry) -> Vec<u8> {
204 let mut out = b"SIMJENTRY2".to_vec();
205 let datum = crate::datum_codec::encode(&value.entry.canonical_datum())
206 .expect("canonical entry datum encodes");
207 out.extend((datum.len() as u64).to_be_bytes());
208 out.extend(datum);
209 put_optional_location(&mut out, value.previous_location.as_ref());
210 out.extend((value.payloads.len() as u64).to_be_bytes());
211 for reference in &value.payloads {
212 put_id(&mut out, &reference.meaning);
213 put_id(&mut out, &reference.storage);
214 }
215 out
216}
217
218pub(crate) fn decode_v2_entry(bytes: &[u8]) -> Result<PhysicalEntry, JournalError> {
219 let mut cursor = Cursor::new(bytes);
220 if cursor.take(10)? != b"SIMJENTRY2" {
221 return Err(JournalError::CorruptState("entry format"));
222 }
223 let datum_len = usize::try_from(cursor.u64()?).map_err(|_| JournalError::WorkBoundExceeded)?;
224 let datum = crate::datum_codec::decode(cursor.take(datum_len)?)?;
225 let entry = entry_from_datum(datum)?;
226 let previous_location = cursor.optional_location()?;
227 let count = usize::try_from(cursor.u64()?).map_err(|_| JournalError::WorkBoundExceeded)?;
228 let mut payloads = Vec::with_capacity(count);
229 for _ in 0..count {
230 payloads.push(StoredDatumRef {
231 meaning: cursor.id()?,
232 storage: cursor.id()?,
233 });
234 }
235 cursor.end()?;
236 Ok(PhysicalEntry {
237 entry,
238 previous_location,
239 payloads,
240 })
241}
242
243pub(crate) fn entry_from_datum(datum: Datum) -> Result<JournalEntry, JournalError> {
244 let id = datum.content_id().map_err(|_| JournalError::CorruptEntry)?;
245 let Datum::Node { tag, fields } = datum else {
246 return Err(JournalError::CorruptEntry);
247 };
248 if tag != Symbol::qualified("journal", "entry-v2") || fields.len() != 4 {
249 return Err(JournalError::CorruptEntry);
250 }
251 let field = |name: &str| {
252 fields
253 .iter()
254 .find(|(field, _)| *field == Symbol::new(name))
255 .map(|(_, value)| value)
256 .ok_or(JournalError::CorruptEntry)
257 };
258 let sequence = match field("sequence")? {
259 Datum::Number(number)
260 if number.domain == Symbol::qualified("numbers", "u64")
261 && number
262 .canonical
263 .parse::<u64>()
264 .ok()
265 .is_some_and(|value| value.to_string() == number.canonical) =>
266 {
267 number
268 .canonical
269 .parse()
270 .map_err(|_| JournalError::CorruptEntry)?
271 }
272 _ => return Err(JournalError::CorruptEntry),
273 };
274 let previous = match field("previous")? {
275 Datum::Nil => None,
276 value => Some(id_from_datum(value)?),
277 };
278 let kind = match field("kind")? {
279 Datum::Symbol(kind) => kind.clone(),
280 _ => return Err(JournalError::CorruptEntry),
281 };
282 let payloads = match field("payloads")? {
283 Datum::Vector(values) => values.iter().map(id_from_datum).collect::<Result<_, _>>()?,
284 _ => return Err(JournalError::CorruptEntry),
285 };
286 let entry = JournalEntry {
287 id,
288 sequence,
289 previous,
290 kind,
291 payloads,
292 };
293 if entry.canonical_id()? != entry.id {
294 return Err(JournalError::CorruptEntry);
295 }
296 Ok(entry)
297}
298
299pub(crate) fn id_from_datum(value: &Datum) -> Result<ContentId, JournalError> {
300 let Datum::Node { tag, fields } = value else {
301 return Err(JournalError::CorruptEntry);
302 };
303 if *tag != Symbol::qualified("journal", "content-id-v1") || fields.len() != 2 {
304 return Err(JournalError::CorruptEntry);
305 }
306 let algorithm = fields
307 .iter()
308 .find_map(|(name, value)| (*name == Symbol::new("algorithm")).then_some(value));
309 let digest = fields
310 .iter()
311 .find_map(|(name, value)| (*name == Symbol::new("digest")).then_some(value));
312 let (Some(Datum::Symbol(algorithm)), Some(Datum::Bytes(bytes))) = (algorithm, digest) else {
313 return Err(JournalError::CorruptEntry);
314 };
315 let digest: [u8; 32] = bytes
316 .as_slice()
317 .try_into()
318 .map_err(|_| JournalError::CorruptEntry)?;
319 Ok(ContentId::from_bytes(algorithm.clone(), digest))
320}
321
322pub(crate) fn decode_v1_state(bytes: &[u8]) -> Result<(u64, Option<JournalHead>), JournalError> {
323 let mut cursor = Cursor::new(bytes);
324 if cursor.take(10)? != b"SIMJSTATE1" {
325 return Err(JournalError::CorruptState("state format"));
326 }
327 let fence = cursor.u64()?;
328 let head = cursor.optional_head()?;
329 cursor.end()?;
330 Ok((fence, head))
331}
332
333pub(crate) fn decode_v1_entry(bytes: &[u8]) -> Result<V1Entry, JournalError> {
334 let mut cursor = Cursor::new(bytes);
335 if cursor.take(10)? != b"SIMJENTRY1" {
336 return Err(JournalError::CorruptState("entry format"));
337 }
338 let id = cursor.id()?;
339 let sequence = cursor.u64()?;
340 let previous = match cursor.byte()? {
341 0 => None,
342 1 => Some(cursor.id()?),
343 _ => return Err(JournalError::CorruptState("entry tag")),
344 };
345 let kind = parse_symbol(&cursor.text()?)?;
346 let count = cursor.u32()? as usize;
347 let mut payloads = Vec::with_capacity(count);
348 for _ in 0..count {
349 payloads.push(cursor.id()?);
350 }
351 cursor.end()?;
352 Ok(V1Entry {
353 id,
354 sequence,
355 previous,
356 kind,
357 payloads,
358 })
359}
360
361pub(crate) fn v1_object_id(bytes: &[u8]) -> ContentId {
362 ContentId::from_bytes(
363 Symbol::qualified("journal", "sha256-bytes-v1"),
364 Sha256::digest(bytes).into(),
365 )
366}
367
368pub(crate) fn put_v1_optional_id_hash(hasher: &mut Sha256, id: Option<&ContentId>) {
369 match id {
370 Some(id) => {
371 hasher.update([1]);
372 put_v1_id_hash(hasher, id);
373 }
374 None => hasher.update([0]),
375 }
376}
377
378pub(crate) fn put_v1_id_hash(hasher: &mut Sha256, id: &ContentId) {
379 put_v1_symbol_hash(hasher, &id.algorithm);
380 hasher.update(id.bytes);
381}
382
383pub(crate) fn put_v1_symbol_hash(hasher: &mut Sha256, symbol: &Symbol) {
384 let text = symbol.as_qualified_str();
385 hasher.update((text.len() as u64).to_be_bytes());
386 hasher.update(text.as_bytes());
387}
388
389pub(crate) fn namespace_root(namespace: &EntryNamespace) -> Vec<String> {
390 vec!["namespaces-v2".into(), namespace.0.clone()]
391}
392
393pub(crate) fn ensure_entry_dirs(
394 port: &dyn HostDirPort,
395 location: &EntryLocation,
396) -> Result<(), JournalError> {
397 let root = [namespace_root(&location.namespace), vec!["entries".into()]].concat();
398 let sequence = [root, vec![format!("{:016x}", location.sequence)]].concat();
399 port.create_dir(&sequence).map_err(port_error)?;
400 port.create_dir(&[sequence, vec![id_key(&location.entry)]].concat())
401 .map_err(port_error)
402}
403
404pub(crate) fn entry_path(location: &EntryLocation) -> Vec<String> {
405 vec![
406 "namespaces-v2".into(),
407 location.namespace.0.clone(),
408 "entries".into(),
409 format!("{:016x}", location.sequence),
410 id_key(&location.entry),
411 id_key(&location.storage),
412 ]
413}
414
415pub(crate) fn object_path(reference: &StoredDatumRef) -> Vec<String> {
416 vec![
417 "objects-v2".into(),
418 id_key(&reference.meaning),
419 id_key(&reference.storage),
420 ]
421}
422
423pub(crate) fn descriptor_path(id: &ContentId) -> Vec<String> {
424 vec!["compat-v1".into(), id_key(id)]
425}
426
427pub(crate) fn v1_entry_path(sequence: u64) -> Vec<String> {
428 vec!["entries".into(), format!("{sequence:016x}")]
429}
430
431pub(crate) fn v1_object_path(id: &ContentId) -> Vec<String> {
432 vec!["objects".into(), hex(&id.bytes)]
433}
434
435pub(crate) fn id_key(id: &ContentId) -> String {
436 format!(
437 "{}-{}",
438 hex(id.algorithm.as_qualified_str().as_bytes()),
439 hex(&id.bytes)
440 )
441}
442
443pub(crate) fn parse_id_key(text: &str) -> Result<ContentId, JournalError> {
444 let (algorithm, digest) = text
445 .split_once('-')
446 .ok_or(JournalError::CorruptState("id path"))?;
447 let algorithm = String::from_utf8(unhex(algorithm)?)
448 .map_err(|_| JournalError::CorruptState("id path utf8"))?;
449 let digest = unhex(digest)?;
450 let bytes: [u8; 32] = digest
451 .try_into()
452 .map_err(|_| JournalError::CorruptState("id path digest"))?;
453 Ok(ContentId::from_bytes(parse_symbol(&algorithm)?, bytes))
454}
455
456pub(crate) fn hex(bytes: &[u8]) -> String {
457 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
458}
459
460pub(crate) fn unhex(text: &str) -> Result<Vec<u8>, JournalError> {
461 let (pairs, remainder) = text.as_bytes().as_chunks::<2>();
462 if !remainder.is_empty() {
463 return Err(JournalError::CorruptState("hex path"));
464 }
465 pairs
466 .iter()
467 .map(|pair| {
468 let high = (pair[0] as char)
469 .to_digit(16)
470 .ok_or(JournalError::CorruptState("hex path"))?;
471 let low = (pair[1] as char)
472 .to_digit(16)
473 .ok_or(JournalError::CorruptState("hex path"))?;
474 Ok(((high << 4) | low) as u8)
475 })
476 .collect()
477}
478
479pub(crate) fn put_head(out: &mut Vec<u8>, head: &JournalHead) {
480 out.extend(head.sequence.to_be_bytes());
481 put_id(out, &head.entry);
482}
483
484pub(crate) fn put_optional_head(out: &mut Vec<u8>, head: Option<&JournalHead>) {
485 match head {
486 Some(head) => {
487 out.push(1);
488 put_head(out, head);
489 }
490 None => out.push(0),
491 }
492}
493
494pub(crate) fn put_optional_location(out: &mut Vec<u8>, location: Option<&EntryLocation>) {
495 match location {
496 Some(location) => {
497 out.push(1);
498 put_text(out, &location.namespace.0);
499 out.extend(location.sequence.to_be_bytes());
500 put_id(out, &location.entry);
501 put_id(out, &location.storage);
502 }
503 None => out.push(0),
504 }
505}
506
507pub(crate) fn put_id(out: &mut Vec<u8>, id: &ContentId) {
508 put_text(out, &id.algorithm.as_qualified_str());
509 out.extend(id.bytes);
510}
511
512pub(crate) fn put_text(out: &mut Vec<u8>, text: &str) {
513 out.extend((text.len() as u32).to_be_bytes());
514 out.extend(text.as_bytes());
515}
516
517pub(crate) fn parse_symbol(text: &str) -> Result<Symbol, JournalError> {
518 match text.split_once('/') {
519 Some((namespace, name)) if !namespace.is_empty() && !name.is_empty() => {
520 Ok(Symbol::qualified(namespace, name))
521 }
522 None => Symbol::checked(text).map_err(|_| JournalError::CorruptState("symbol")),
523 _ => Err(JournalError::CorruptState("symbol")),
524 }
525}
526
527pub(crate) fn port_error(error: sim_storage_port::HostDirError) -> JournalError {
528 JournalError::Backend(error.to_string())
529}
530
531struct Cursor<'a> {
532 bytes: &'a [u8],
533 at: usize,
534}
535
536impl<'a> Cursor<'a> {
537 fn new(bytes: &'a [u8]) -> Self {
538 Self { bytes, at: 0 }
539 }
540 fn take(&mut self, len: usize) -> Result<&'a [u8], JournalError> {
541 let end = self
542 .at
543 .checked_add(len)
544 .ok_or(JournalError::CorruptState("length"))?;
545 let value = self
546 .bytes
547 .get(self.at..end)
548 .ok_or(JournalError::CorruptState("truncated"))?;
549 self.at = end;
550 Ok(value)
551 }
552 fn byte(&mut self) -> Result<u8, JournalError> {
553 Ok(self.take(1)?[0])
554 }
555 fn u32(&mut self) -> Result<u32, JournalError> {
556 Ok(u32::from_be_bytes(
557 self.take(4)?
558 .try_into()
559 .map_err(|_| JournalError::CorruptState("u32"))?,
560 ))
561 }
562 fn u64(&mut self) -> Result<u64, JournalError> {
563 Ok(u64::from_be_bytes(
564 self.take(8)?
565 .try_into()
566 .map_err(|_| JournalError::CorruptState("u64"))?,
567 ))
568 }
569 fn text(&mut self) -> Result<String, JournalError> {
570 let len = self.u32()? as usize;
571 String::from_utf8(self.take(len)?.to_vec()).map_err(|_| JournalError::CorruptState("utf8"))
572 }
573 fn id(&mut self) -> Result<ContentId, JournalError> {
574 let algorithm = parse_symbol(&self.text()?)?;
575 let bytes = self
576 .take(32)?
577 .try_into()
578 .map_err(|_| JournalError::CorruptState("id"))?;
579 Ok(ContentId::from_bytes(algorithm, bytes))
580 }
581 fn head(&mut self) -> Result<JournalHead, JournalError> {
582 Ok(JournalHead {
583 sequence: self.u64()?,
584 entry: self.id()?,
585 })
586 }
587 fn optional_head(&mut self) -> Result<Option<JournalHead>, JournalError> {
588 match self.byte()? {
589 0 => Ok(None),
590 1 => Ok(Some(self.head()?)),
591 _ => Err(JournalError::CorruptState("head tag")),
592 }
593 }
594 fn optional_location(&mut self) -> Result<Option<EntryLocation>, JournalError> {
595 match self.byte()? {
596 0 => Ok(None),
597 1 => Ok(Some(EntryLocation {
598 namespace: EntryNamespace(self.text()?),
599 sequence: self.u64()?,
600 entry: self.id()?,
601 storage: self.id()?,
602 })),
603 _ => Err(JournalError::CorruptState("location tag")),
604 }
605 }
606 fn end(&self) -> Result<(), JournalError> {
607 if self.at == self.bytes.len() {
608 Ok(())
609 } else {
610 Err(JournalError::CorruptState("trailing bytes"))
611 }
612 }
613}