1use std::fmt;
30use std::fs::{self, File};
31use std::io::{BufRead, BufReader};
32use std::path::{Path, PathBuf};
33
34use serde::de::{SeqAccess, Visitor};
35use serde::{Deserialize, Deserializer};
36use serde_json::value::RawValue;
37use sha2::{Digest, Sha256};
38
39use crate::state::{StateSeries, StateTime, SystemState, SystemStateSchema, schema_from_fields};
40
41use super::RecordingTiming;
42use super::error::PersistenceError;
43use super::json_payload_decoder::JsonPayloadDecoderRegistry;
44use super::jsonl_format::{ChunkMetadata, RecordingMetadata, RecordingStatus, StateStreamMetadata};
45
46const METADATA_FILE: &str = "metadata.json";
48
49pub struct StoredStateSeriesReader {
56 root: PathBuf,
57 metadata_path: PathBuf,
58 metadata: RecordingMetadata,
59 timing: RecordingTiming,
60 decoders: JsonPayloadDecoderRegistry,
61}
62
63impl StoredStateSeriesReader {
64 pub fn open_completed_recording(
81 root: &Path,
82 decoders: JsonPayloadDecoderRegistry,
83 ) -> Result<Self, PersistenceError> {
84 let root = root.to_path_buf();
85 let metadata_path = root.join(METADATA_FILE);
86 let bytes = fs::read(&metadata_path).map_err(|source| PersistenceError::Io {
87 operation: "read metadata",
88 path: metadata_path.clone(),
89 source,
90 })?;
91 let metadata: RecordingMetadata =
92 serde_json::from_slice(&bytes).map_err(|source| PersistenceError::Json {
93 operation: "parse metadata",
94 path: metadata_path.clone(),
95 source,
96 })?;
97 metadata.validate(&metadata_path)?;
98 if !matches!(metadata.status, RecordingStatus::Complete) {
99 return Err(PersistenceError::RecordingNotComplete {
100 path: metadata_path,
101 });
102 }
103 let timing = RecordingTiming::from_stored(&metadata.timing, &metadata_path)?;
104 Ok(Self {
105 root,
106 metadata_path,
107 metadata,
108 timing,
109 decoders,
110 })
111 }
112
113 pub fn recording_directory(&self) -> &Path {
115 &self.root
116 }
117
118 pub fn stream_names(&self) -> impl ExactSizeIterator<Item = &str> {
120 self.metadata
121 .streams
122 .iter()
123 .map(|stream| stream.name.as_str())
124 }
125
126 pub fn format_version(&self) -> u32 {
128 self.metadata.version
129 }
130
131 pub fn user_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
133 &self.metadata.user_metadata
134 }
135
136 pub fn terminal_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
138 &self.metadata.terminal_metadata
139 }
140
141 pub fn recording_timing(&self) -> &RecordingTiming {
143 &self.timing
144 }
145
146 pub fn stream_record_count(&self, stream: &str) -> Result<u64, PersistenceError> {
148 let declaration =
149 self.metadata
150 .stream(stream)
151 .ok_or_else(|| PersistenceError::UnknownStateStream {
152 stream: stream.to_owned(),
153 })?;
154 declaration
155 .chunks
156 .iter()
157 .try_fold(0_u64, |total, chunk| total.checked_add(chunk.records))
158 .ok_or_else(|| PersistenceError::ByteCountOverflow {
159 stream: declaration.name.clone(),
160 })
161 }
162
163 pub fn stream_encoded_bytes(&self, stream: &str) -> Result<u64, PersistenceError> {
165 let declaration =
166 self.metadata
167 .stream(stream)
168 .ok_or_else(|| PersistenceError::UnknownStateStream {
169 stream: stream.to_owned(),
170 })?;
171 declaration
172 .chunks
173 .iter()
174 .try_fold(0_u64, |total, chunk| total.checked_add(chunk.bytes))
175 .ok_or_else(|| PersistenceError::ByteCountOverflow {
176 stream: declaration.name.clone(),
177 })
178 }
179
180 pub fn read_stream_as_state_series(
193 &self,
194 stream: &str,
195 ) -> Result<StateSeries, PersistenceError> {
196 let declaration =
197 self.metadata
198 .stream(stream)
199 .ok_or_else(|| PersistenceError::UnknownStateStream {
200 stream: stream.to_owned(),
201 })?;
202 self.decoders
203 .require(declaration.fields.iter().map(|field| field.name.as_str()))?;
204
205 let spec = stream_spec(&self.metadata_path, declaration)?;
206 let total_records = self.stream_record_count(stream)?;
207 let capacity =
208 usize::try_from(total_records).map_err(|_| PersistenceError::ByteCountOverflow {
209 stream: declaration.name.clone(),
210 })?;
211 let mut series = StateSeries::with_capacity(spec, capacity);
212 let mut previous_iteration = None;
213
214 for chunk in &declaration.chunks {
215 self.read_chunk(declaration, chunk, &mut previous_iteration, &mut series)?;
216 }
217 Ok(series)
218 }
219
220 pub fn read_all_streams_as_state_series(
226 &self,
227 ) -> Result<Vec<(String, StateSeries)>, PersistenceError> {
228 self.metadata
229 .streams
230 .iter()
231 .map(|stream| {
232 self.read_stream_as_state_series(&stream.name)
233 .map(|series| (stream.name.clone(), series))
234 })
235 .collect()
236 }
237
238 pub fn read_latest_state_from_stream(
246 &self,
247 stream: &str,
248 ) -> Result<SystemState, PersistenceError> {
249 let declaration =
250 self.metadata
251 .stream(stream)
252 .ok_or_else(|| PersistenceError::UnknownStateStream {
253 stream: stream.to_owned(),
254 })?;
255 self.decoders
256 .require(declaration.fields.iter().map(|field| field.name.as_str()))?;
257 let chunk = declaration
258 .chunks
259 .last()
260 .ok_or_else(|| PersistenceError::NoRecordedState {
261 stream: declaration.name.clone(),
262 })?;
263 let path = self.root.join(&declaration.directory).join(&chunk.file);
264 let bytes = read_verified_chunk(&self.metadata_path, &path, chunk)?;
265 let record =
266 verified_final_jsonl_record(&self.metadata_path, &path, declaration, chunk, &bytes)?;
267 let spec = stream_spec(&self.metadata_path, declaration)?;
268 let state =
269 decode_state_record_with_decoders(record, &path, declaration, &spec, &self.decoders)?;
270 if state.time().iteration() != chunk.last_iteration {
271 return Err(invalid_record(
272 &path,
273 chunk.records,
274 format!(
275 "latest record iteration {} differs from chunk descriptor {}",
276 state.time().iteration(),
277 chunk.last_iteration
278 ),
279 ));
280 }
281 Ok(state)
282 }
283
284 fn read_chunk(
286 &self,
287 stream: &StateStreamMetadata,
288 chunk: &ChunkMetadata,
289 previous_iteration: &mut Option<u64>,
290 series: &mut StateSeries,
291 ) -> Result<(), PersistenceError> {
292 let path = self.root.join(&stream.directory).join(&chunk.file);
293 verify_file_size(&path, chunk.bytes)?;
294 let file = File::open(&path).map_err(|source| {
295 if source.kind() == std::io::ErrorKind::NotFound {
296 PersistenceError::MissingChunk { path: path.clone() }
297 } else {
298 PersistenceError::Io {
299 operation: "open chunk",
300 path: path.clone(),
301 source,
302 }
303 }
304 })?;
305 let mut input = BufReader::new(file);
306 let mut line = Vec::new();
307 let mut line_number = 0_u64;
308 let mut records = 0_u64;
309 let mut first_iteration = None;
310 let mut last_iteration = None;
311 let mut hasher = Sha256::new();
312
313 loop {
314 line.clear();
315 let bytes_read =
316 input
317 .read_until(b'\n', &mut line)
318 .map_err(|source| PersistenceError::Io {
319 operation: "read chunk",
320 path: path.clone(),
321 source,
322 })?;
323 if bytes_read == 0 {
324 break;
325 }
326 line_number =
327 line_number
328 .checked_add(1)
329 .ok_or_else(|| PersistenceError::ByteCountOverflow {
330 stream: stream.name.clone(),
331 })?;
332 hasher.update(&line);
333 if line.last() != Some(&b'\n') {
334 return Err(invalid_record(
335 &path,
336 line_number,
337 "record is not terminated by a newline",
338 ));
339 }
340 line.pop();
341 if line.is_empty() {
342 return Err(invalid_record(
343 &path,
344 line_number,
345 "record line must not be empty",
346 ));
347 }
348
349 let record: BorrowedRecord<'_> = serde_json::from_slice(&line).map_err(|source| {
350 invalid_record(&path, line_number, format!("invalid JSON record: {source}"))
351 })?;
352 validate_iteration(&path, line_number, record.iteration, *previous_iteration)?;
353 let iteration = record.iteration;
354 first_iteration.get_or_insert(iteration);
355 last_iteration = Some(iteration);
356 *previous_iteration = Some(iteration);
357
358 let time = match record.physical_time {
359 Some(physical_time) => {
360 StateTime::from_iteration_and_physical_time(iteration, physical_time)
361 .ok_or_else(|| {
362 invalid_record(&path, line_number, "physical time must be finite")
363 })?
364 }
365 None => StateTime::from_iteration(iteration),
366 };
367 let mut state = series.schema().create_empty_state(time);
368 decode_values(
369 &self.decoders,
370 stream,
371 &path,
372 line_number,
373 record.values,
374 &mut state,
375 )?;
376 series.push_state(state).map_err(|rejection| {
377 let (source, state) = rejection.into_parts();
378 let index = state.time().iteration();
379 drop(state);
380 PersistenceError::StateSeriesInvariant {
381 stream: stream.name.clone(),
382 iteration: index,
383 source,
384 }
385 })?;
386 records =
387 records
388 .checked_add(1)
389 .ok_or_else(|| PersistenceError::ByteCountOverflow {
390 stream: stream.name.clone(),
391 })?;
392 }
393
394 validate_chunk_facts(
395 &self.metadata_path,
396 stream,
397 chunk,
398 records,
399 first_iteration,
400 last_iteration,
401 )?;
402 verify_checksum(
403 &self.metadata_path,
404 &path,
405 &chunk.checksum,
406 hasher.finalize(),
407 )
408 }
409}
410
411fn verified_final_jsonl_record<'a>(
413 metadata_path: &Path,
414 path: &Path,
415 stream: &StateStreamMetadata,
416 chunk: &ChunkMetadata,
417 bytes: &'a [u8],
418) -> Result<&'a [u8], PersistenceError> {
419 let mut records = 0_u64;
420 let mut first_iteration = None;
421 let mut last_iteration = None;
422 let mut previous_iteration = None;
423 let mut final_record = None;
424
425 for framed in bytes.split_inclusive(|byte| *byte == b'\n') {
426 records = records
427 .checked_add(1)
428 .ok_or_else(|| PersistenceError::ByteCountOverflow {
429 stream: stream.name.clone(),
430 })?;
431 if !framed.ends_with(b"\n") {
432 return Err(invalid_record(
433 path,
434 records,
435 "record is not terminated by a newline",
436 ));
437 }
438 let record_bytes = &framed[..framed.len() - 1];
439 if record_bytes.is_empty() {
440 return Err(invalid_record(
441 path,
442 records,
443 "record line must not be empty",
444 ));
445 }
446 let record: BorrowedRecord<'_> =
447 serde_json::from_slice(record_bytes).map_err(|source| {
448 invalid_record(path, records, format!("invalid JSON record: {source}"))
449 })?;
450 if record.values.entries.len() != stream.fields.len() {
451 return Err(invalid_record(
452 path,
453 records,
454 format!(
455 "record contains {} payload values but stream `{}` declares {} fields",
456 record.values.entries.len(),
457 stream.name,
458 stream.fields.len()
459 ),
460 ));
461 }
462 if record.physical_time.is_some_and(|time| !time.is_finite()) {
463 return Err(invalid_record(
464 path,
465 records,
466 "physical time must be finite",
467 ));
468 }
469 validate_iteration(path, records, record.iteration, previous_iteration)?;
470 first_iteration.get_or_insert(record.iteration);
471 last_iteration = Some(record.iteration);
472 previous_iteration = Some(record.iteration);
473 final_record = Some(record_bytes);
474 }
475
476 validate_chunk_facts(
477 metadata_path,
478 stream,
479 chunk,
480 records,
481 first_iteration,
482 last_iteration,
483 )?;
484 final_record.ok_or_else(|| invalid_record(path, 1, "latest chunk contains no record"))
485}
486
487impl fmt::Debug for StoredStateSeriesReader {
488 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
490 formatter
491 .debug_struct("StoredStateSeriesReader")
492 .field("root", &self.root)
493 .field("streams", &self.metadata.streams.len())
494 .field("decoders", &self.decoders)
495 .finish_non_exhaustive()
496 }
497}
498
499fn decode_state_record_with_decoders(
501 record: &[u8],
502 path: &Path,
503 stream: &StateStreamMetadata,
504 full_spec: &SystemStateSchema,
505 decoders: &JsonPayloadDecoderRegistry,
506) -> Result<SystemState, PersistenceError> {
507 let record: BorrowedRecord<'_> = serde_json::from_slice(record)
508 .map_err(|source| invalid_record(path, 1, format!("invalid JSON record: {source}")))?;
509 let time = match record.physical_time {
510 Some(physical_time) => {
511 StateTime::from_iteration_and_physical_time(record.iteration, physical_time)
512 .ok_or_else(|| invalid_record(path, 1, "physical time must be finite"))?
513 }
514 None => StateTime::from_iteration(record.iteration),
515 };
516 let mut state = full_spec.create_empty_state(time);
517 decode_values(decoders, stream, path, 1, record.values, &mut state)?;
518 Ok(state)
519}
520
521#[derive(Deserialize)]
523#[serde(deny_unknown_fields)]
524struct BorrowedRecord<'a> {
525 iteration: u64,
526 #[serde(default)]
527 physical_time: Option<f64>,
528 #[serde(borrow)]
529 values: BorrowedValues<'a>,
530}
531
532struct BorrowedValues<'a> {
534 entries: Vec<&'a RawValue>,
535}
536
537impl<'de: 'a, 'a> Deserialize<'de> for BorrowedValues<'a> {
538 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
540 where
541 D: Deserializer<'de>,
542 {
543 deserializer.deserialize_seq(BorrowedValuesVisitor {
544 output: std::marker::PhantomData,
545 })
546 }
547}
548
549struct BorrowedValuesVisitor<'a> {
551 output: std::marker::PhantomData<&'a RawValue>,
553}
554
555impl<'de: 'a, 'a> Visitor<'de> for BorrowedValuesVisitor<'a> {
556 type Value = BorrowedValues<'a>;
557
558 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
560 formatter.write_str("an array of raw JSON payload values")
561 }
562
563 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
565 where
566 A: SeqAccess<'de>,
567 {
568 let mut entries = Vec::with_capacity(sequence.size_hint().unwrap_or(0));
569 while let Some(value) = sequence.next_element::<&'de RawValue>()? {
570 let value: &'a RawValue = value;
571 entries.push(value);
572 }
573 Ok(BorrowedValues { entries })
574 }
575}
576
577fn stream_spec(
579 metadata_path: &Path,
580 stream: &StateStreamMetadata,
581) -> Result<SystemStateSchema, PersistenceError> {
582 schema_from_fields(
583 metadata_path,
584 stream
585 .fields
586 .iter()
587 .map(|field| (field.name.as_str(), field.description.as_deref())),
588 )
589 .map_err(|source| PersistenceError::InvalidMetadata {
590 path: metadata_path.to_path_buf(),
591 reason: format!(
592 "stream `{}` has an invalid state schema: {source}",
593 stream.name
594 ),
595 })
596}
597
598fn verify_file_size(path: &Path, expected: u64) -> Result<(), PersistenceError> {
600 let actual = match fs::metadata(path) {
601 Ok(metadata) => metadata.len(),
602 Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
603 return Err(PersistenceError::MissingChunk {
604 path: path.to_path_buf(),
605 });
606 }
607 Err(source) => {
608 return Err(PersistenceError::Io {
609 operation: "inspect chunk",
610 path: path.to_path_buf(),
611 source,
612 });
613 }
614 };
615 if actual != expected {
616 return Err(PersistenceError::ChunkSizeMismatch {
617 path: path.to_path_buf(),
618 expected,
619 actual,
620 });
621 }
622 Ok(())
623}
624
625pub(crate) fn read_verified_chunk(
627 metadata_path: &Path,
628 path: &Path,
629 chunk: &ChunkMetadata,
630) -> Result<Vec<u8>, PersistenceError> {
631 verify_file_size(path, chunk.bytes)?;
632 let bytes = fs::read(path).map_err(|source| {
633 if source.kind() == std::io::ErrorKind::NotFound {
634 PersistenceError::MissingChunk {
635 path: path.to_path_buf(),
636 }
637 } else {
638 PersistenceError::Io {
639 operation: "read verified chunk",
640 path: path.to_path_buf(),
641 source,
642 }
643 }
644 })?;
645 verify_checksum(metadata_path, path, &chunk.checksum, Sha256::digest(&bytes))?;
646 Ok(bytes)
647}
648
649fn validate_iteration(
651 path: &Path,
652 line: u64,
653 iteration: u64,
654 previous: Option<u64>,
655) -> Result<(), PersistenceError> {
656 if let Some(previous) = previous
657 && iteration <= previous
658 {
659 return Err(invalid_record(
660 path,
661 line,
662 format!("iteration {iteration} is not greater than previous iteration {previous}"),
663 ));
664 }
665 Ok(())
666}
667
668fn decode_values(
670 decoders: &JsonPayloadDecoderRegistry,
671 stream: &StateStreamMetadata,
672 path: &Path,
673 line: u64,
674 values: BorrowedValues<'_>,
675 state: &mut crate::state::SystemState,
676) -> Result<(), PersistenceError> {
677 if values.entries.len() != stream.fields.len() {
678 return Err(invalid_record(
679 path,
680 line,
681 format!(
682 "record contains {} payload values but stream `{}` declares {} fields",
683 values.entries.len(),
684 stream.name,
685 stream.fields.len()
686 ),
687 ));
688 }
689 for (field, raw) in stream.fields.iter().zip(values.entries) {
690 decoders.decode_into(
691 &stream.name,
692 state.time().iteration(),
693 &field.name,
694 raw.get(),
695 state,
696 )?;
697 }
698 Ok(())
699}
700
701fn validate_chunk_facts(
703 metadata_path: &Path,
704 stream: &StateStreamMetadata,
705 chunk: &ChunkMetadata,
706 records: u64,
707 first_iteration: Option<u64>,
708 last_iteration: Option<u64>,
709) -> Result<(), PersistenceError> {
710 if records != chunk.records
711 || first_iteration != Some(chunk.first_iteration)
712 || last_iteration != Some(chunk.last_iteration)
713 {
714 return Err(PersistenceError::InvalidMetadata {
715 path: metadata_path.to_path_buf(),
716 reason: format!(
717 "stream `{}` chunk {} declares {} records at {}..={}, but contains {} records at {:?}..={:?}",
718 stream.name,
719 chunk.ordinal,
720 chunk.records,
721 chunk.first_iteration,
722 chunk.last_iteration,
723 records,
724 first_iteration,
725 last_iteration
726 ),
727 });
728 }
729 Ok(())
730}
731
732fn verify_checksum(
734 metadata_path: &Path,
735 path: &Path,
736 expected: &str,
737 digest: impl AsRef<[u8]>,
738) -> Result<(), PersistenceError> {
739 let Some(expected_digest) = expected.strip_prefix("sha256:") else {
740 return Err(PersistenceError::InvalidMetadata {
741 path: metadata_path.to_path_buf(),
742 reason: format!("unsupported chunk checksum algorithm in `{expected}`"),
743 });
744 };
745 let actual_digest = lowercase_hex(digest.as_ref());
746 if actual_digest != expected_digest {
747 return Err(PersistenceError::ChecksumMismatch {
748 path: path.to_path_buf(),
749 expected: expected.to_owned(),
750 actual: format!("sha256:{actual_digest}"),
751 });
752 }
753 Ok(())
754}
755
756fn lowercase_hex(bytes: &[u8]) -> String {
758 use std::fmt::Write as _;
759
760 let mut encoded = String::with_capacity(bytes.len() * 2);
761 for byte in bytes {
762 write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
763 }
764 encoded
765}
766
767fn invalid_record(path: &Path, line: u64, reason: impl Into<String>) -> PersistenceError {
769 PersistenceError::InvalidRecord {
770 path: path.to_path_buf(),
771 line,
772 reason: reason.into(),
773 }
774}