use std::fmt;
use std::fs;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use serde::de::{SeqAccess, Visitor};
use serde::{Deserialize, Deserializer};
use serde_json::value::RawValue;
use sha2::{Digest, Sha256};
use crate::state::{StateSeries, StateTime, SystemState, SystemStateSchema, schema_from_fields};
use super::RecordingTiming;
use super::error::PersistenceError;
use super::json_payload_decoder::JsonPayloadDecoderRegistry;
use super::jsonl_format::{ChunkMetadata, RecordingMetadata, RecordingStatus, StateStreamMetadata};
const METADATA_FILE: &str = "metadata.json";
pub struct StoredStateSeriesReader {
artifacts: Option<crate::artifact::ArtifactSet>,
root: PathBuf,
metadata_path: PathBuf,
metadata: RecordingMetadata,
timing: RecordingTiming,
decoders: JsonPayloadDecoderRegistry,
}
impl StoredStateSeriesReader {
pub fn open_completed_recording(
root: &Path,
decoders: JsonPayloadDecoderRegistry,
) -> Result<Self, PersistenceError> {
let root = root.to_path_buf();
let metadata_path = root.join(METADATA_FILE);
let bytes = fs::read(&metadata_path).map_err(|source| PersistenceError::Io {
operation: "read metadata",
path: metadata_path.clone(),
source,
})?;
let metadata: RecordingMetadata =
serde_json::from_slice(&bytes).map_err(|source| PersistenceError::Json {
operation: "parse metadata",
path: metadata_path.clone(),
source,
})?;
metadata.validate(&metadata_path)?;
if !matches!(metadata.status, RecordingStatus::Complete) {
return Err(PersistenceError::RecordingNotComplete {
path: metadata_path,
});
}
let timing = RecordingTiming::from_stored(&metadata.timing, &metadata_path)?;
Ok(Self {
artifacts: None,
root,
metadata_path,
metadata,
timing,
decoders,
})
}
pub fn from_artifacts(
artifacts: crate::artifact::ArtifactSet,
decoders: JsonPayloadDecoderRegistry,
) -> Result<Self, PersistenceError> {
let root = PathBuf::from(artifacts.prefix());
let metadata_path = root.join(METADATA_FILE);
let input = artifacts
.reader(METADATA_FILE)
.map_err(|source| PersistenceError::Io {
operation: "open artifact metadata",
path: metadata_path.clone(),
source,
})?;
let metadata: RecordingMetadata =
serde_json::from_reader(input).map_err(|source| PersistenceError::Json {
operation: "parse artifact metadata",
path: metadata_path.clone(),
source,
})?;
metadata.validate(&metadata_path)?;
if !matches!(metadata.status, RecordingStatus::Complete) {
return Err(PersistenceError::RecordingNotComplete {
path: metadata_path,
});
}
let timing = RecordingTiming::from_stored(&metadata.timing, &metadata_path)?;
Ok(Self {
artifacts: Some(artifacts),
root,
metadata_path,
metadata,
timing,
decoders,
})
}
pub fn recording_directory(&self) -> Option<&Path> {
self.artifacts.is_none().then_some(self.root.as_path())
}
pub fn stream_names(&self) -> impl ExactSizeIterator<Item = &str> {
self.metadata
.streams
.iter()
.map(|stream| stream.name.as_str())
}
pub fn format_version(&self) -> u32 {
self.metadata.version
}
pub fn user_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
&self.metadata.user_metadata
}
pub fn terminal_metadata(&self) -> &serde_json::Map<String, serde_json::Value> {
&self.metadata.terminal_metadata
}
pub fn recording_timing(&self) -> &RecordingTiming {
&self.timing
}
pub fn stream_record_count(&self, stream: &str) -> Result<u64, PersistenceError> {
let declaration =
self.metadata
.stream(stream)
.ok_or_else(|| PersistenceError::UnknownStateStream {
stream: stream.to_owned(),
})?;
declaration
.chunks
.iter()
.try_fold(0_u64, |total, chunk| total.checked_add(chunk.records))
.ok_or_else(|| PersistenceError::ByteCountOverflow {
stream: declaration.name.clone(),
})
}
pub fn stream_encoded_bytes(&self, stream: &str) -> Result<u64, PersistenceError> {
let declaration =
self.metadata
.stream(stream)
.ok_or_else(|| PersistenceError::UnknownStateStream {
stream: stream.to_owned(),
})?;
declaration
.chunks
.iter()
.try_fold(0_u64, |total, chunk| total.checked_add(chunk.bytes))
.ok_or_else(|| PersistenceError::ByteCountOverflow {
stream: declaration.name.clone(),
})
}
pub fn read_stream_as_state_series(
&self,
stream: &str,
) -> Result<StateSeries, PersistenceError> {
let declaration =
self.metadata
.stream(stream)
.ok_or_else(|| PersistenceError::UnknownStateStream {
stream: stream.to_owned(),
})?;
self.decoders
.require(declaration.fields.iter().map(|field| field.name.as_str()))?;
let spec = stream_spec(&self.metadata_path, declaration)?;
let total_records = self.stream_record_count(stream)?;
let capacity =
usize::try_from(total_records).map_err(|_| PersistenceError::ByteCountOverflow {
stream: declaration.name.clone(),
})?;
let mut series = StateSeries::with_capacity(spec, capacity);
let mut previous_iteration = None;
for chunk in &declaration.chunks {
self.read_chunk(declaration, chunk, &mut previous_iteration, &mut series)?;
}
Ok(series)
}
pub fn read_all_streams_as_state_series(
&self,
) -> Result<Vec<(String, StateSeries)>, PersistenceError> {
self.metadata
.streams
.iter()
.map(|stream| {
self.read_stream_as_state_series(&stream.name)
.map(|series| (stream.name.clone(), series))
})
.collect()
}
pub fn read_latest_state_from_stream(
&self,
stream: &str,
) -> Result<SystemState, PersistenceError> {
let declaration =
self.metadata
.stream(stream)
.ok_or_else(|| PersistenceError::UnknownStateStream {
stream: stream.to_owned(),
})?;
self.decoders
.require(declaration.fields.iter().map(|field| field.name.as_str()))?;
let chunk = declaration
.chunks
.last()
.ok_or_else(|| PersistenceError::NoRecordedState {
stream: declaration.name.clone(),
})?;
let path = self.root.join(&declaration.directory).join(&chunk.file);
let bytes = if let Some(artifacts) = &self.artifacts {
let relative = format!("{}/{}", declaration.directory, chunk.file);
let mut bytes = Vec::new();
artifacts
.reader(&relative)
.and_then(|r| {
r.take(chunk.bytes.saturating_add(1))
.read_to_end(&mut bytes)
})
.map_err(|source| PersistenceError::Io {
operation: "read artifact chunk",
path: path.clone(),
source,
})?;
if bytes.len() as u64 != chunk.bytes {
return Err(PersistenceError::ChunkSizeMismatch {
path: path.clone(),
expected: chunk.bytes,
actual: bytes.len() as u64,
});
}
verify_checksum(
&self.metadata_path,
&path,
&chunk.checksum,
Sha256::digest(&bytes),
)?;
bytes
} else {
read_verified_chunk(&self.metadata_path, &path, chunk)?
};
let record =
verified_final_jsonl_record(&self.metadata_path, &path, declaration, chunk, &bytes)?;
let spec = stream_spec(&self.metadata_path, declaration)?;
let state =
decode_state_record_with_decoders(record, &path, declaration, &spec, &self.decoders)?;
if state.time().iteration() != chunk.last_iteration {
return Err(invalid_record(
&path,
chunk.records,
format!(
"latest record iteration {} differs from chunk descriptor {}",
state.time().iteration(),
chunk.last_iteration
),
));
}
Ok(state)
}
fn read_chunk(
&self,
stream: &StateStreamMetadata,
chunk: &ChunkMetadata,
previous_iteration: &mut Option<u64>,
series: &mut StateSeries,
) -> Result<(), PersistenceError> {
let path = self.root.join(&stream.directory).join(&chunk.file);
let relative = format!("{}/{}", stream.directory, chunk.file);
let file = if let Some(artifacts) = &self.artifacts {
let reference =
artifacts
.reference(&relative)
.map_err(|source| PersistenceError::Io {
operation: "inspect artifact chunk",
path: path.clone(),
source,
})?;
if reference.bytes != chunk.bytes {
return Err(PersistenceError::ChunkSizeMismatch {
path: path.clone(),
expected: chunk.bytes,
actual: reference.bytes,
});
}
artifacts.reader(&relative)
} else {
verify_file_size(&path, chunk.bytes)?;
crate::workspace::open_file(&path)
}
.map_err(|source| {
if source.kind() == std::io::ErrorKind::NotFound {
PersistenceError::MissingChunk { path: path.clone() }
} else {
PersistenceError::Io {
operation: "open chunk",
path: path.clone(),
source,
}
}
})?;
let mut input = BufReader::new(file);
let mut line = Vec::new();
let mut line_number = 0_u64;
let mut records = 0_u64;
let mut first_iteration = None;
let mut last_iteration = None;
let mut hasher = Sha256::new();
loop {
line.clear();
let bytes_read =
input
.read_until(b'\n', &mut line)
.map_err(|source| PersistenceError::Io {
operation: "read chunk",
path: path.clone(),
source,
})?;
if bytes_read == 0 {
break;
}
line_number =
line_number
.checked_add(1)
.ok_or_else(|| PersistenceError::ByteCountOverflow {
stream: stream.name.clone(),
})?;
hasher.update(&line);
if line.last() != Some(&b'\n') {
return Err(invalid_record(
&path,
line_number,
"record is not terminated by a newline",
));
}
line.pop();
if line.is_empty() {
return Err(invalid_record(
&path,
line_number,
"record line must not be empty",
));
}
let record: BorrowedRecord<'_> = serde_json::from_slice(&line).map_err(|source| {
invalid_record(&path, line_number, format!("invalid JSON record: {source}"))
})?;
validate_iteration(&path, line_number, record.iteration, *previous_iteration)?;
let iteration = record.iteration;
first_iteration.get_or_insert(iteration);
last_iteration = Some(iteration);
*previous_iteration = Some(iteration);
let time = match record.physical_time {
Some(physical_time) => {
StateTime::from_iteration_and_physical_time(iteration, physical_time)
.ok_or_else(|| {
invalid_record(&path, line_number, "physical time must be finite")
})?
}
None => StateTime::from_iteration(iteration),
};
let mut state = series.schema().create_empty_state(time);
decode_values(
&self.decoders,
stream,
&path,
line_number,
record.values,
&mut state,
)?;
series.push_state(state).map_err(|rejection| {
let (source, state) = rejection.into_parts();
let index = state.time().iteration();
drop(state);
PersistenceError::StateSeriesInvariant {
stream: stream.name.clone(),
iteration: index,
source,
}
})?;
records =
records
.checked_add(1)
.ok_or_else(|| PersistenceError::ByteCountOverflow {
stream: stream.name.clone(),
})?;
}
validate_chunk_facts(
&self.metadata_path,
stream,
chunk,
records,
first_iteration,
last_iteration,
)?;
verify_checksum(
&self.metadata_path,
&path,
&chunk.checksum,
hasher.finalize(),
)
}
}
fn verified_final_jsonl_record<'a>(
metadata_path: &Path,
path: &Path,
stream: &StateStreamMetadata,
chunk: &ChunkMetadata,
bytes: &'a [u8],
) -> Result<&'a [u8], PersistenceError> {
let mut records = 0_u64;
let mut first_iteration = None;
let mut last_iteration = None;
let mut previous_iteration = None;
let mut final_record = None;
for framed in bytes.split_inclusive(|byte| *byte == b'\n') {
records = records
.checked_add(1)
.ok_or_else(|| PersistenceError::ByteCountOverflow {
stream: stream.name.clone(),
})?;
if !framed.ends_with(b"\n") {
return Err(invalid_record(
path,
records,
"record is not terminated by a newline",
));
}
let record_bytes = &framed[..framed.len() - 1];
if record_bytes.is_empty() {
return Err(invalid_record(
path,
records,
"record line must not be empty",
));
}
let record: BorrowedRecord<'_> =
serde_json::from_slice(record_bytes).map_err(|source| {
invalid_record(path, records, format!("invalid JSON record: {source}"))
})?;
if record.values.entries.len() != stream.fields.len() {
return Err(invalid_record(
path,
records,
format!(
"record contains {} payload values but stream `{}` declares {} fields",
record.values.entries.len(),
stream.name,
stream.fields.len()
),
));
}
if record.physical_time.is_some_and(|time| !time.is_finite()) {
return Err(invalid_record(
path,
records,
"physical time must be finite",
));
}
validate_iteration(path, records, record.iteration, previous_iteration)?;
first_iteration.get_or_insert(record.iteration);
last_iteration = Some(record.iteration);
previous_iteration = Some(record.iteration);
final_record = Some(record_bytes);
}
validate_chunk_facts(
metadata_path,
stream,
chunk,
records,
first_iteration,
last_iteration,
)?;
final_record.ok_or_else(|| invalid_record(path, 1, "latest chunk contains no record"))
}
impl fmt::Debug for StoredStateSeriesReader {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("StoredStateSeriesReader")
.field("root", &self.root)
.field("streams", &self.metadata.streams.len())
.field("decoders", &self.decoders)
.finish_non_exhaustive()
}
}
fn decode_state_record_with_decoders(
record: &[u8],
path: &Path,
stream: &StateStreamMetadata,
full_spec: &SystemStateSchema,
decoders: &JsonPayloadDecoderRegistry,
) -> Result<SystemState, PersistenceError> {
let record: BorrowedRecord<'_> = serde_json::from_slice(record)
.map_err(|source| invalid_record(path, 1, format!("invalid JSON record: {source}")))?;
let time = match record.physical_time {
Some(physical_time) => {
StateTime::from_iteration_and_physical_time(record.iteration, physical_time)
.ok_or_else(|| invalid_record(path, 1, "physical time must be finite"))?
}
None => StateTime::from_iteration(record.iteration),
};
let mut state = full_spec.create_empty_state(time);
decode_values(decoders, stream, path, 1, record.values, &mut state)?;
Ok(state)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct BorrowedRecord<'a> {
iteration: u64,
#[serde(default)]
physical_time: Option<f64>,
#[serde(borrow)]
values: BorrowedValues<'a>,
}
struct BorrowedValues<'a> {
entries: Vec<&'a RawValue>,
}
impl<'de: 'a, 'a> Deserialize<'de> for BorrowedValues<'a> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_seq(BorrowedValuesVisitor {
output: std::marker::PhantomData,
})
}
}
struct BorrowedValuesVisitor<'a> {
output: std::marker::PhantomData<&'a RawValue>,
}
impl<'de: 'a, 'a> Visitor<'de> for BorrowedValuesVisitor<'a> {
type Value = BorrowedValues<'a>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("an array of raw JSON payload values")
}
fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
let mut entries = Vec::with_capacity(sequence.size_hint().unwrap_or(0));
while let Some(value) = sequence.next_element::<&'de RawValue>()? {
let value: &'a RawValue = value;
entries.push(value);
}
Ok(BorrowedValues { entries })
}
}
fn stream_spec(
metadata_path: &Path,
stream: &StateStreamMetadata,
) -> Result<SystemStateSchema, PersistenceError> {
schema_from_fields(
metadata_path,
stream
.fields
.iter()
.map(|field| (field.name.as_str(), field.description.as_deref())),
)
.map_err(|source| PersistenceError::InvalidMetadata {
path: metadata_path.to_path_buf(),
reason: format!(
"stream `{}` has an invalid state schema: {source}",
stream.name
),
})
}
fn verify_file_size(path: &Path, expected: u64) -> Result<(), PersistenceError> {
let actual = match crate::workspace::file_size(path) {
Ok(bytes) => bytes,
Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
return Err(PersistenceError::MissingChunk {
path: path.to_path_buf(),
});
}
Err(source) => {
return Err(PersistenceError::Io {
operation: "inspect chunk",
path: path.to_path_buf(),
source,
});
}
};
if actual != expected {
return Err(PersistenceError::ChunkSizeMismatch {
path: path.to_path_buf(),
expected,
actual,
});
}
Ok(())
}
pub(crate) fn read_verified_chunk(
metadata_path: &Path,
path: &Path,
chunk: &ChunkMetadata,
) -> Result<Vec<u8>, PersistenceError> {
verify_file_size(path, chunk.bytes)?;
let bytes = crate::workspace::open_file(path)
.and_then(|r| {
let mut bytes = Vec::new();
r.take(chunk.bytes.saturating_add(1))
.read_to_end(&mut bytes)?;
Ok(bytes)
})
.map_err(|source| {
if source.kind() == std::io::ErrorKind::NotFound {
PersistenceError::MissingChunk {
path: path.to_path_buf(),
}
} else {
PersistenceError::Io {
operation: "read verified chunk",
path: path.to_path_buf(),
source,
}
}
})?;
verify_checksum(metadata_path, path, &chunk.checksum, Sha256::digest(&bytes))?;
Ok(bytes)
}
fn validate_iteration(
path: &Path,
line: u64,
iteration: u64,
previous: Option<u64>,
) -> Result<(), PersistenceError> {
if let Some(previous) = previous
&& iteration <= previous
{
return Err(invalid_record(
path,
line,
format!("iteration {iteration} is not greater than previous iteration {previous}"),
));
}
Ok(())
}
fn decode_values(
decoders: &JsonPayloadDecoderRegistry,
stream: &StateStreamMetadata,
path: &Path,
line: u64,
values: BorrowedValues<'_>,
state: &mut crate::state::SystemState,
) -> Result<(), PersistenceError> {
if values.entries.len() != stream.fields.len() {
return Err(invalid_record(
path,
line,
format!(
"record contains {} payload values but stream `{}` declares {} fields",
values.entries.len(),
stream.name,
stream.fields.len()
),
));
}
for (field, raw) in stream.fields.iter().zip(values.entries) {
decoders.decode_into(
&stream.name,
state.time().iteration(),
&field.name,
raw.get(),
state,
)?;
}
Ok(())
}
fn validate_chunk_facts(
metadata_path: &Path,
stream: &StateStreamMetadata,
chunk: &ChunkMetadata,
records: u64,
first_iteration: Option<u64>,
last_iteration: Option<u64>,
) -> Result<(), PersistenceError> {
if records != chunk.records
|| first_iteration != Some(chunk.first_iteration)
|| last_iteration != Some(chunk.last_iteration)
{
return Err(PersistenceError::InvalidMetadata {
path: metadata_path.to_path_buf(),
reason: format!(
"stream `{}` chunk {} declares {} records at {}..={}, but contains {} records at {:?}..={:?}",
stream.name,
chunk.ordinal,
chunk.records,
chunk.first_iteration,
chunk.last_iteration,
records,
first_iteration,
last_iteration
),
});
}
Ok(())
}
fn verify_checksum(
metadata_path: &Path,
path: &Path,
expected: &str,
digest: impl AsRef<[u8]>,
) -> Result<(), PersistenceError> {
let Some(expected_digest) = expected.strip_prefix("sha256:") else {
return Err(PersistenceError::InvalidMetadata {
path: metadata_path.to_path_buf(),
reason: format!("unsupported chunk checksum algorithm in `{expected}`"),
});
};
let actual_digest = lowercase_hex(digest.as_ref());
if actual_digest != expected_digest {
return Err(PersistenceError::ChecksumMismatch {
path: path.to_path_buf(),
expected: expected.to_owned(),
actual: format!("sha256:{actual_digest}"),
});
}
Ok(())
}
fn lowercase_hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut encoded = String::with_capacity(bytes.len() * 2);
for byte in bytes {
write!(&mut encoded, "{byte:02x}").expect("writing to String cannot fail");
}
encoded
}
fn invalid_record(path: &Path, line: u64, reason: impl Into<String>) -> PersistenceError {
PersistenceError::InvalidRecord {
path: path.to_path_buf(),
line,
reason: reason.into(),
}
}