use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use fs4::FileExt;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::operational_time::{duration_nanoseconds, utc_now_rfc3339};
use crate::observation::{
BoundObservationPlan, BoundObservationStream, EncodedObservation, ObservationSession,
};
use crate::state::SystemState;
mod error;
mod json_payload_decoder;
mod jsonl_format;
mod queued_state_writer;
mod stored_state_series_reader;
pub use error::PersistenceError;
pub use json_payload_decoder::{JsonPayloadDecoder, JsonPayloadDecoderRegistry};
pub use stored_state_series_reader::StoredStateSeriesReader;
use jsonl_format::{
EncodedStateRecord, RecordingMetadata, RecordingStatus, StateFieldMetadata,
StateStreamMetadata, TimeAxisMetadata as StoredTimeAxis,
};
use queued_state_writer::{StateStreamStorageConfig, StateWriterWorker};
const METADATA_FILE: &str = "metadata.json";
const METADATA_TEMP_FILE: &str = ".metadata.json.tmp";
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecordingTiming {
created_at_utc: String,
finalized_at_utc: String,
active_duration_ns: u64,
}
impl RecordingTiming {
fn from_stored(
timing: &jsonl_format::RecordingTiming,
metadata_path: &Path,
) -> Result<Self, PersistenceError> {
let finalized_at_utc =
timing
.finalized_at_utc
.clone()
.ok_or_else(|| PersistenceError::InvalidMetadata {
path: metadata_path.to_path_buf(),
reason: "completed recording lacks finalized timestamp".to_owned(),
})?;
Ok(Self {
created_at_utc: timing.created_at_utc.clone(),
finalized_at_utc,
active_duration_ns: timing.active_duration_ns,
})
}
pub fn created_at_utc(&self) -> &str {
&self.created_at_utc
}
pub fn finalized_at_utc(&self) -> &str {
&self.finalized_at_utc
}
pub fn active_duration(&self) -> Duration {
Duration::from_nanos(self.active_duration_ns)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SamplingInterval {
Iterations(NonZeroU64),
InitialAndFinal(bool),
}
#[derive(Deserialize)]
#[serde(untagged, deny_unknown_fields)]
enum SamplingIntervalInput {
Tagged {
iterations: NonZeroU64,
},
Boundaries {
initial_and_final: bool,
},
}
impl<'de> Deserialize<'de> for SamplingInterval {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
match SamplingIntervalInput::deserialize(deserializer)? {
SamplingIntervalInput::Tagged {
iterations: interval,
} => Ok(Self::Iterations(interval)),
SamplingIntervalInput::Boundaries {
initial_and_final: true,
} => Ok(Self::InitialAndFinal(true)),
SamplingIntervalInput::Boundaries {
initial_and_final: false,
} => Err(serde::de::Error::custom("initial_and_final must be true")),
}
}
}
impl SamplingInterval {
pub(crate) const fn iterations(interval: u64) -> Option<Self> {
match NonZeroU64::new(interval) {
Some(interval) => Some(Self::Iterations(interval)),
None => None,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(crate) enum StateStreamLayout {
Chunked {
target_bytes: NonZeroU64,
},
IndividualFiles,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct StateStreamStorage {
layout: StateStreamLayout,
storage_queue_bytes: NonZeroU64,
}
impl StateStreamStorage {
pub(crate) const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
Self {
layout: StateStreamLayout::Chunked { target_bytes },
storage_queue_bytes,
}
}
pub(crate) const fn layout(self) -> StateStreamLayout {
self.layout
}
pub(crate) const fn storage_queue_bytes(self) -> NonZeroU64 {
self.storage_queue_bytes
}
}
pub(crate) struct SystemStateWriter {
manifest: Arc<RecordingManifest>,
session: ObservationSession,
writer: Option<StateWriterWorker>,
session_started: Instant,
_lease: RecordingLease,
}
impl SystemStateWriter {
pub(crate) fn create(
root: PathBuf,
descriptor: BoundObservationPlan,
user_metadata: Map<String, Value>,
storage: StateStreamStorage,
) -> Result<Self, PersistenceError> {
ensure_absent(&root)?;
let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
create_root(&prepared.root)?;
let lease = RecordingLease::acquire(&prepared.root)?;
for stream in &prepared.streams {
stream.create_directory()?;
}
commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
let manifest = Arc::new(RecordingManifest::new(
prepared.root.clone(),
prepared.metadata_path,
prepared.metadata,
));
Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
}
pub(crate) fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
let observations = self
.session
.observe(state)
.map_err(|source| PersistenceError::Observation { source })?;
let writer = self
.writer
.as_ref()
.expect("an active recording owns its writer worker");
submit_observations(writer, observations)?;
Ok(())
}
#[cfg(test)]
pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
self.complete_recording_with_terminal_metadata(Map::new())
}
pub(crate) fn complete_recording_with_terminal_metadata(
mut self,
terminal_metadata: Map<String, Value>,
) -> Result<(), PersistenceError> {
if let Err(error) = self.finish_writer() {
let _ = self.transition_terminal(
RecordingStatus::Failed {
message: error.to_string(),
},
Map::new(),
);
return Err(error);
}
self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
}
pub(crate) fn complete_recording_with_final_state(
mut self,
state: &SystemState,
terminal_metadata: Map<String, Value>,
) -> Result<(), PersistenceError> {
if let Err(error) = self.record_final_state(state) {
let _ = self.mark_recording_failed(error.to_string());
return Err(error);
}
self.complete_recording_with_terminal_metadata(terminal_metadata)
}
pub(crate) fn record_final_state(
&mut self,
state: &SystemState,
) -> Result<(), PersistenceError> {
let observations = self
.session
.observe_final(state)
.map_err(|source| PersistenceError::Observation { source })?;
let writer = self
.writer
.as_ref()
.expect("an active recording owns its writer worker");
submit_observations(writer, observations)?;
Ok(())
}
pub(crate) fn mark_recording_failed(
self,
message: impl Into<String>,
) -> Result<(), PersistenceError> {
self.mark_recording_failed_with_terminal_metadata(message, Map::new())
}
pub(crate) fn mark_recording_failed_with_terminal_metadata(
mut self,
message: impl Into<String>,
terminal_metadata: Map<String, Value>,
) -> Result<(), PersistenceError> {
let message = message.into();
if message.trim().is_empty() {
return Err(PersistenceError::InvalidConfiguration {
setting: "failure_message",
reason: "failed run message must not be empty".to_owned(),
});
}
if let Err(error) = self.finish_writer() {
let _ = self.transition_terminal(
RecordingStatus::Failed {
message: error.to_string(),
},
Map::new(),
);
return Err(error);
}
self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
}
fn start_new_prepared(
descriptor: BoundObservationPlan,
streams: Vec<StateStreamStorageConfig>,
manifest: Arc<RecordingManifest>,
lease: RecordingLease,
) -> Result<Self, PersistenceError> {
let mut configs = Vec::with_capacity(streams.len());
configs.extend(streams);
let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
Ok(Self {
manifest,
session: ObservationSession::new(descriptor),
writer: Some(writer),
session_started: Instant::now(),
_lease: lease,
})
}
fn finish_writer(&mut self) -> Result<(), PersistenceError> {
let Some(writer) = self.writer.take() else {
return Ok(());
};
writer.finish_recording()
}
fn transition_terminal(
&self,
status: RecordingStatus,
terminal_metadata: Map<String, Value>,
) -> Result<(), PersistenceError> {
let finalized_at_utc =
utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
operation: "finalize recording",
source,
})?;
let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
.ok_or(PersistenceError::OperationalDurationOverflow)?;
self.manifest.transition_terminal(
status,
finalized_at_utc,
active_duration_ns,
terminal_metadata,
)
}
}
struct PreparedRecording {
root: PathBuf,
metadata_path: PathBuf,
descriptor: BoundObservationPlan,
metadata: RecordingMetadata,
streams: Vec<StateStreamStorageConfig>,
}
impl PreparedRecording {
fn new(
root: PathBuf,
descriptor: BoundObservationPlan,
user_metadata: Map<String, Value>,
storage: StateStreamStorage,
) -> Result<Self, PersistenceError> {
let metadata_path = root.join(METADATA_FILE);
let stored_time = StoredTimeAxis {
iteration_name: "iteration".to_owned(),
iteration_unit: descriptor.iteration_unit().map(str::to_owned),
physical_time_name: Some("physical_time".to_owned()),
physical_time_unit: descriptor.physical_time_unit().map(str::to_owned),
};
let mut streams = Vec::with_capacity(descriptor.streams().len());
let mut declarations = Vec::with_capacity(descriptor.streams().len());
for (index, stream) in descriptor.streams().iter().enumerate() {
let stream: &BoundObservationStream = stream;
let directory = format!("stream_{index:04}");
let sampling_interval = stream
.every_iterations()
.map_or(SamplingInterval::InitialAndFinal(true), |n| {
SamplingInterval::iterations(n).expect("positive bound interval")
});
let fields = stream
.fields()
.iter()
.map(|field| StateFieldMetadata {
name: field.name().to_owned(),
description: field.description().map(str::to_owned),
})
.collect::<Vec<_>>();
declarations.push(StateStreamMetadata {
name: stream.name().to_owned(),
directory: directory.clone(),
sampling_interval,
fields,
storage,
chunks: Vec::new(),
});
streams.push(StateStreamStorageConfig::new(
stream.name(),
root.join(&directory),
storage,
)?);
}
let created_at_utc =
utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
operation: "create recording",
source,
})?;
let metadata =
RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
metadata.validate(&metadata_path)?;
Ok(Self {
root,
metadata_path,
descriptor,
metadata,
streams,
})
}
}
fn submit_observations(
writer: &StateWriterWorker,
observations: Vec<EncodedObservation>,
) -> Result<(), PersistenceError> {
for observation in observations {
let (stream, time, bytes) = observation.into_parts();
writer.submit_record(stream, EncodedStateRecord::new(time, bytes))?;
}
Ok(())
}
pub(crate) struct RecordingManifest {
root: PathBuf,
path: PathBuf,
metadata: Mutex<RecordingMetadata>,
}
impl RecordingManifest {
fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
Self {
root,
path,
metadata: Mutex::new(metadata),
}
}
pub(crate) fn prepare_chunk(
&self,
stream: &str,
descriptor: jsonl_format::ChunkMetadata,
) -> Result<(), PersistenceError> {
let mut current = lock_metadata(&self.metadata);
if !matches!(current.status, RecordingStatus::Running) {
return Err(PersistenceError::RecordingFinished);
}
let mut candidate = current.clone();
let declaration =
candidate
.stream_mut(stream)
.ok_or_else(|| PersistenceError::UnknownStateStream {
stream: stream.to_owned(),
})?;
let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
PersistenceError::ByteCountOverflow {
stream: stream.to_owned(),
}
})?;
if descriptor.ordinal != expected {
return Err(PersistenceError::InvalidMetadata {
path: self.path.clone(),
reason: format!(
"stream `{stream}` prepared chunk ordinal {}, expected {expected}",
descriptor.ordinal
),
});
}
declaration.chunks.push(descriptor);
commit_metadata(&self.root, &self.path, &candidate)?;
*current = candidate;
Ok(())
}
fn transition_terminal(
&self,
status: RecordingStatus,
finalized_at_utc: String,
active_duration_ns: u64,
terminal_metadata: Map<String, Value>,
) -> Result<(), PersistenceError> {
let mut current = lock_metadata(&self.metadata);
if !matches!(current.status, RecordingStatus::Running) {
return Err(PersistenceError::RecordingFinished);
}
let mut candidate = current.clone();
candidate.status = status;
candidate.timing.finalized_at_utc = Some(finalized_at_utc);
candidate.timing.active_duration_ns = candidate
.timing
.active_duration_ns
.checked_add(active_duration_ns)
.ok_or(PersistenceError::OperationalDurationOverflow)?;
candidate.terminal_metadata = terminal_metadata;
commit_metadata(&self.root, &self.path, &candidate)?;
*current = candidate;
Ok(())
}
}
struct RecordingLease {
directory: File,
}
impl RecordingLease {
fn acquire(root: &Path) -> Result<Self, PersistenceError> {
let directory = File::open(root).map_err(|source| PersistenceError::Io {
operation: "open output root for exclusive ownership",
path: root.to_path_buf(),
source,
})?;
match FileExt::try_lock(&directory) {
Ok(()) => Ok(Self { directory }),
Err(fs4::TryLockError::WouldBlock) => Err(PersistenceError::RecordingDirectoryInUse {
path: root.to_path_buf(),
}),
Err(source) => Err(PersistenceError::Io {
operation: "acquire exclusive output ownership",
path: root.to_path_buf(),
source: source.into(),
}),
}
}
}
impl Drop for RecordingLease {
fn drop(&mut self) {
let _ = FileExt::unlock(&self.directory);
}
}
fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
metadata
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
match root.try_exists() {
Ok(false) => Ok(()),
Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
path: root.to_path_buf(),
}),
Err(source) => Err(PersistenceError::Io {
operation: "inspect output root",
path: root.to_path_buf(),
source,
}),
}
}
fn create_root(root: &Path) -> Result<(), PersistenceError> {
if let Some(parent) = root.parent() {
fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
operation: "create recording parent directories",
path: parent.to_path_buf(),
source,
})?;
}
match fs::create_dir(root) {
Ok(()) => Ok(()),
Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
Err(PersistenceError::RecordingDirectoryExists {
path: root.to_path_buf(),
})
}
Err(source) => Err(PersistenceError::Io {
operation: "create output root",
path: root.to_path_buf(),
source,
}),
}
}
fn commit_metadata(
root: &Path,
metadata_path: &Path,
metadata: &RecordingMetadata,
) -> Result<(), PersistenceError> {
metadata.validate(metadata_path)?;
let mut bytes =
serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
operation: "serialize metadata",
path: metadata_path.to_path_buf(),
source,
})?;
bytes.push(b'\n');
let temporary_path = root.join(METADATA_TEMP_FILE);
let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
if result.is_err() {
let _ = fs::remove_file(&temporary_path);
}
result
}
fn write_and_replace_metadata(
root: &Path,
metadata_path: &Path,
temporary_path: &Path,
bytes: &[u8],
) -> Result<(), PersistenceError> {
let mut temporary = OpenOptions::new()
.write(true)
.create_new(true)
.open(temporary_path)
.map_err(|source| PersistenceError::Io {
operation: "create temporary metadata",
path: temporary_path.to_path_buf(),
source,
})?;
temporary
.write_all(bytes)
.map_err(|source| PersistenceError::Io {
operation: "write temporary metadata",
path: temporary_path.to_path_buf(),
source,
})?;
temporary
.sync_all()
.map_err(|source| PersistenceError::Io {
operation: "sync temporary metadata",
path: temporary_path.to_path_buf(),
source,
})?;
drop(temporary);
fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
operation: "publish metadata",
path: metadata_path.to_path_buf(),
source,
})?;
File::open(root)
.and_then(|directory| directory.sync_all())
.map_err(|source| PersistenceError::Io {
operation: "sync output root",
path: root.to_path_buf(),
source,
})
}