1use std::fs::{self, File, OpenOptions};
54use std::io::Write;
55use std::num::NonZeroU64;
56use std::path::{Path, PathBuf};
57use std::sync::{Arc, Mutex, MutexGuard};
58use std::time::{Duration, Instant};
59
60use fs2::FileExt;
61use serde::{Deserialize, Serialize};
62use serde_json::{Map, Value};
63
64use crate::clock::{duration_nanoseconds, utc_now_rfc3339};
65use crate::observation::advanced::{BoundObservationPlan, ObservationSession};
66use crate::state::advanced::SystemState;
67
68mod error;
69mod json_payload_decoder;
70mod jsonl_format;
71mod queued_state_writer;
72mod stored_state_series_reader;
73
74pub use error::PersistenceError;
75pub use json_payload_decoder::{
76 JsonPayloadDecoder, JsonPayloadDecoderRegistry, JsonStringDecoder, JsonVecF64Decoder,
77};
78pub use stored_state_series_reader::StoredStateSeriesReader;
79
80use jsonl_format::{
81 EncodedStateRecord, RecordingMetadata, RecordingStatus, StateFieldMetadata,
82 StateStreamMetadata, TimeAxisMetadata as StoredTimeAxis,
83};
84use queued_state_writer::{StateStreamStorageConfig, StateWriterWorker};
85
86const METADATA_FILE: &str = "metadata.json";
88
89const METADATA_TEMP_FILE: &str = ".metadata.json.tmp";
91
92#[derive(Clone, Debug, Eq, PartialEq)]
98pub struct RecordingTiming {
99 created_at_utc: String,
100 finalized_at_utc: String,
101 active_duration_ns: u64,
102 continuation_count: u64,
103}
104
105impl RecordingTiming {
106 fn from_stored(
108 timing: &jsonl_format::RecordingTiming,
109 metadata_path: &Path,
110 ) -> Result<Self, PersistenceError> {
111 let finalized_at_utc =
112 timing
113 .finalized_at_utc
114 .clone()
115 .ok_or_else(|| PersistenceError::InvalidMetadata {
116 path: metadata_path.to_path_buf(),
117 reason: "completed recording lacks finalized timestamp".to_owned(),
118 })?;
119 Ok(Self {
120 created_at_utc: timing.created_at_utc.clone(),
121 finalized_at_utc,
122 active_duration_ns: timing.active_duration_ns,
123 continuation_count: timing.continuation_count,
124 })
125 }
126
127 pub fn created_at_utc(&self) -> &str {
129 &self.created_at_utc
130 }
131
132 pub fn finalized_at_utc(&self) -> &str {
134 &self.finalized_at_utc
135 }
136
137 pub fn active_duration_ns(&self) -> u64 {
139 self.active_duration_ns
140 }
141
142 pub fn active_duration(&self) -> Duration {
144 Duration::from_nanos(self.active_duration_ns)
145 }
146
147 pub fn continuation_count(&self) -> u64 {
149 self.continuation_count
150 }
151}
152
153#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
164#[serde(rename_all = "snake_case")]
165pub(crate) enum SamplingInterval {
166 Iterations(NonZeroU64),
168}
169
170#[derive(Deserialize)]
171#[serde(untagged)]
172enum SamplingIntervalInput {
173 Iterations(NonZeroU64),
175 Tagged { iterations: NonZeroU64 },
177}
178
179impl<'de> Deserialize<'de> for SamplingInterval {
180 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
181 where
182 D: serde::Deserializer<'de>,
183 {
184 match SamplingIntervalInput::deserialize(deserializer)? {
185 SamplingIntervalInput::Iterations(interval)
186 | SamplingIntervalInput::Tagged {
187 iterations: interval,
188 } => Ok(Self::Iterations(interval)),
189 }
190 }
191}
192
193impl SamplingInterval {
194 pub(crate) const fn iterations(interval: u64) -> Option<Self> {
196 match NonZeroU64::new(interval) {
197 Some(interval) => Some(Self::Iterations(interval)),
198 None => None,
199 }
200 }
201}
202
203#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
205#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
206pub enum StateStreamLayout {
207 Chunked {
209 target_bytes: NonZeroU64,
211 },
212 IndividualFiles,
214}
215
216#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
218#[serde(deny_unknown_fields)]
219pub struct StateStreamStorage {
220 layout: StateStreamLayout,
221 storage_queue_bytes: NonZeroU64,
222}
223
224impl StateStreamStorage {
225 pub const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
227 Self {
228 layout: StateStreamLayout::Chunked { target_bytes },
229 storage_queue_bytes,
230 }
231 }
232
233 pub const fn layout(self) -> StateStreamLayout {
235 self.layout
236 }
237
238 pub const fn storage_queue_bytes(self) -> NonZeroU64 {
240 self.storage_queue_bytes
241 }
242}
243
244pub struct SystemStateWriter {
251 manifest: Arc<RecordingManifest>,
252 session: ObservationSession,
253 writer: Option<StateWriterWorker>,
254 session_started: Instant,
255 _lease: RecordingLease,
258}
259
260impl SystemStateWriter {
261 pub(crate) fn create(
263 root: PathBuf,
264 descriptor: BoundObservationPlan,
265 user_metadata: Map<String, Value>,
266 storage: StateStreamStorage,
267 ) -> Result<Self, PersistenceError> {
268 ensure_absent(&root)?;
269 let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
270 create_root(&prepared.root)?;
271 let lease = RecordingLease::acquire(&prepared.root)?;
272 for stream in &prepared.streams {
273 stream.create_directory()?;
274 }
275 commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
276 let manifest = Arc::new(RecordingManifest::new(
277 prepared.root.clone(),
278 prepared.metadata_path,
279 prepared.metadata,
280 ));
281 Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
282 }
283
284 pub fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
298 let observations = self
299 .session
300 .observe(state)
301 .map_err(|source| PersistenceError::Observation { source })?;
302 let writer = self
303 .writer
304 .as_ref()
305 .expect("an active recording owns its writer worker");
306 for observation in observations {
307 let stream = observation.stream().to_owned();
308 let record = EncodedStateRecord::new(observation.time(), observation.into_bytes());
309 writer.submit_record(&stream, record)?;
310 }
311 Ok(())
312 }
313
314 pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
322 self.complete_recording_with_terminal_metadata(Map::new())
323 }
324
325 pub(crate) fn complete_recording_with_terminal_metadata(
331 mut self,
332 terminal_metadata: Map<String, Value>,
333 ) -> Result<(), PersistenceError> {
334 if let Err(error) = self.finish_writer() {
335 let _ = self.transition_terminal(
336 RecordingStatus::Failed {
337 message: error.to_string(),
338 },
339 Map::new(),
340 );
341 return Err(error);
342 }
343 self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
344 }
345
346 pub(crate) fn complete_recording_with_final_state(
353 mut self,
354 state: &SystemState,
355 ) -> Result<(), PersistenceError> {
356 self.record_final_state(state)?;
357 self.complete_recording()
358 }
359
360 pub(crate) fn record_final_state(
362 &mut self,
363 state: &SystemState,
364 ) -> Result<(), PersistenceError> {
365 let observations = self
366 .session
367 .observe_final(state)
368 .map_err(|source| PersistenceError::Observation { source })?;
369 let writer = self
370 .writer
371 .as_ref()
372 .expect("an active recording owns its writer worker");
373 for observation in observations {
374 let stream = observation.stream().to_owned();
375 let record = EncodedStateRecord::new(observation.time(), observation.into_bytes());
376 writer.submit_record(&stream, record)?;
377 }
378 Ok(())
379 }
380
381 pub(crate) fn mark_recording_failed(
393 self,
394 message: impl Into<String>,
395 ) -> Result<(), PersistenceError> {
396 self.mark_recording_failed_with_terminal_metadata(message, Map::new())
397 }
398
399 pub(crate) fn mark_recording_failed_with_terminal_metadata(
401 mut self,
402 message: impl Into<String>,
403 terminal_metadata: Map<String, Value>,
404 ) -> Result<(), PersistenceError> {
405 let message = message.into();
406 if message.trim().is_empty() {
407 return Err(PersistenceError::InvalidConfiguration {
408 setting: "failure_message",
409 reason: "failed run message must not be empty".to_owned(),
410 });
411 }
412
413 if let Err(error) = self.finish_writer() {
414 let _ = self.transition_terminal(
415 RecordingStatus::Failed {
416 message: error.to_string(),
417 },
418 Map::new(),
419 );
420 return Err(error);
421 }
422 self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
423 }
424
425 fn start_new_prepared(
427 descriptor: BoundObservationPlan,
428 streams: Vec<StateStreamStorageConfig>,
429 manifest: Arc<RecordingManifest>,
430 lease: RecordingLease,
431 ) -> Result<Self, PersistenceError> {
432 let mut configs = Vec::with_capacity(streams.len());
433 configs.extend(streams);
434 let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
435 Ok(Self {
436 manifest,
437 session: ObservationSession::new(descriptor),
438 writer: Some(writer),
439 session_started: Instant::now(),
440 _lease: lease,
441 })
442 }
443
444 fn finish_writer(&mut self) -> Result<(), PersistenceError> {
446 let Some(writer) = self.writer.take() else {
447 return Ok(());
448 };
449 writer.finish_recording()
450 }
451
452 fn transition_terminal(
454 &self,
455 status: RecordingStatus,
456 terminal_metadata: Map<String, Value>,
457 ) -> Result<(), PersistenceError> {
458 let finalized_at_utc =
459 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
460 operation: "finalize recording",
461 source,
462 })?;
463 let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
464 .ok_or(PersistenceError::OperationalDurationOverflow)?;
465 self.manifest.transition_terminal(
466 status,
467 finalized_at_utc,
468 active_duration_ns,
469 terminal_metadata,
470 )
471 }
472}
473
474struct PreparedRecording {
476 root: PathBuf,
477 metadata_path: PathBuf,
478 descriptor: BoundObservationPlan,
479 metadata: RecordingMetadata,
480 streams: Vec<StateStreamStorageConfig>,
481}
482
483impl PreparedRecording {
484 fn new(
486 root: PathBuf,
487 descriptor: BoundObservationPlan,
488 user_metadata: Map<String, Value>,
489 storage: StateStreamStorage,
490 ) -> Result<Self, PersistenceError> {
491 let metadata_path = root.join(METADATA_FILE);
492 let stored_time = StoredTimeAxis {
493 iteration_name: "iteration".to_owned(),
494 iteration_unit: descriptor.iteration_unit().map(str::to_owned),
495 physical_time_name: Some("physical_time".to_owned()),
496 physical_time_unit: descriptor.physical_time_unit().map(str::to_owned),
497 };
498 let mut streams = Vec::with_capacity(descriptor.streams().len());
499 let mut declarations = Vec::with_capacity(descriptor.streams().len());
500
501 for (index, stream) in descriptor.streams().iter().enumerate() {
502 let directory = format!("stream_{index:04}");
503 let sampling_interval = SamplingInterval::iterations(stream.every_iterations())
504 .expect("bound observation streams contain positive sampling intervals");
505 let fields = stream
506 .fields()
507 .iter()
508 .map(|field| StateFieldMetadata {
509 name: field.name().to_owned(),
510 description: field.description().map(str::to_owned),
511 })
512 .collect::<Vec<_>>();
513 declarations.push(StateStreamMetadata {
514 name: stream.name().to_owned(),
515 directory: directory.clone(),
516 sampling_interval,
517 fields,
518 storage,
519 chunks: Vec::new(),
520 });
521 streams.push(StateStreamStorageConfig::new(
522 stream.name(),
523 root.join(&directory),
524 storage,
525 )?);
526 }
527
528 let created_at_utc =
529 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
530 operation: "create recording",
531 source,
532 })?;
533 let metadata =
534 RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
535 metadata.validate(&metadata_path)?;
536 Ok(Self {
537 root,
538 metadata_path,
539 descriptor,
540 metadata,
541 streams,
542 })
543 }
544}
545
546pub(crate) struct RecordingManifest {
552 root: PathBuf,
553 path: PathBuf,
554 metadata: Mutex<RecordingMetadata>,
555}
556
557impl RecordingManifest {
558 fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
560 Self {
561 root,
562 path,
563 metadata: Mutex::new(metadata),
564 }
565 }
566
567 pub(crate) fn prepare_chunk(
569 &self,
570 stream: &str,
571 descriptor: jsonl_format::ChunkMetadata,
572 ) -> Result<(), PersistenceError> {
573 let mut current = lock_metadata(&self.metadata);
574 if !matches!(current.status, RecordingStatus::Running) {
575 return Err(PersistenceError::RecordingFinished);
576 }
577 let mut candidate = current.clone();
578 let declaration =
579 candidate
580 .stream_mut(stream)
581 .ok_or_else(|| PersistenceError::UnknownStateStream {
582 stream: stream.to_owned(),
583 })?;
584 let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
585 PersistenceError::ByteCountOverflow {
586 stream: stream.to_owned(),
587 }
588 })?;
589 if descriptor.ordinal != expected {
590 return Err(PersistenceError::InvalidMetadata {
591 path: self.path.clone(),
592 reason: format!(
593 "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
594 descriptor.ordinal
595 ),
596 });
597 }
598 declaration.chunks.push(descriptor);
599 commit_metadata(&self.root, &self.path, &candidate)?;
600 *current = candidate;
601 Ok(())
602 }
603
604 fn transition_terminal(
606 &self,
607 status: RecordingStatus,
608 finalized_at_utc: String,
609 active_duration_ns: u64,
610 terminal_metadata: Map<String, Value>,
611 ) -> Result<(), PersistenceError> {
612 let mut current = lock_metadata(&self.metadata);
613 let mut candidate = current.clone();
614 candidate.status = status;
615 candidate.timing.finalized_at_utc = Some(finalized_at_utc);
616 candidate.timing.active_duration_ns = candidate
617 .timing
618 .active_duration_ns
619 .checked_add(active_duration_ns)
620 .ok_or(PersistenceError::OperationalDurationOverflow)?;
621 candidate.terminal_metadata = terminal_metadata;
622 commit_metadata(&self.root, &self.path, &candidate)?;
623 *current = candidate;
624 Ok(())
625 }
626}
627
628struct RecordingLease {
633 directory: File,
634}
635
636impl RecordingLease {
637 fn acquire(root: &Path) -> Result<Self, PersistenceError> {
639 let directory = File::open(root).map_err(|source| PersistenceError::Io {
640 operation: "open output root for exclusive ownership",
641 path: root.to_path_buf(),
642 source,
643 })?;
644 match FileExt::try_lock_exclusive(&directory) {
645 Ok(()) => Ok(Self { directory }),
646 Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
647 Err(PersistenceError::RecordingDirectoryInUse {
648 path: root.to_path_buf(),
649 })
650 }
651 Err(source) => Err(PersistenceError::Io {
652 operation: "acquire exclusive output ownership",
653 path: root.to_path_buf(),
654 source,
655 }),
656 }
657 }
658}
659
660impl Drop for RecordingLease {
661 fn drop(&mut self) {
662 let _ = FileExt::unlock(&self.directory);
666 }
667}
668
669fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
671 metadata
672 .lock()
673 .unwrap_or_else(|poisoned| poisoned.into_inner())
674}
675
676fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
678 match root.try_exists() {
679 Ok(false) => Ok(()),
680 Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
681 path: root.to_path_buf(),
682 }),
683 Err(source) => Err(PersistenceError::Io {
684 operation: "inspect output root",
685 path: root.to_path_buf(),
686 source,
687 }),
688 }
689}
690
691fn create_root(root: &Path) -> Result<(), PersistenceError> {
693 if let Some(parent) = root.parent() {
694 fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
695 operation: "create recording parent directories",
696 path: parent.to_path_buf(),
697 source,
698 })?;
699 }
700 match fs::create_dir(root) {
701 Ok(()) => Ok(()),
702 Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
703 Err(PersistenceError::RecordingDirectoryExists {
704 path: root.to_path_buf(),
705 })
706 }
707 Err(source) => Err(PersistenceError::Io {
708 operation: "create output root",
709 path: root.to_path_buf(),
710 source,
711 }),
712 }
713}
714
715fn commit_metadata(
723 root: &Path,
724 metadata_path: &Path,
725 metadata: &RecordingMetadata,
726) -> Result<(), PersistenceError> {
727 metadata.validate(metadata_path)?;
728 let mut bytes =
729 serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
730 operation: "serialize metadata",
731 path: metadata_path.to_path_buf(),
732 source,
733 })?;
734 bytes.push(b'\n');
735
736 let temporary_path = root.join(METADATA_TEMP_FILE);
737 let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
738 if result.is_err() {
739 let _ = fs::remove_file(&temporary_path);
740 }
741 result
742}
743
744fn write_and_replace_metadata(
746 root: &Path,
747 metadata_path: &Path,
748 temporary_path: &Path,
749 bytes: &[u8],
750) -> Result<(), PersistenceError> {
751 let mut temporary = OpenOptions::new()
752 .write(true)
753 .create_new(true)
754 .open(temporary_path)
755 .map_err(|source| PersistenceError::Io {
756 operation: "create temporary metadata",
757 path: temporary_path.to_path_buf(),
758 source,
759 })?;
760 temporary
761 .write_all(bytes)
762 .map_err(|source| PersistenceError::Io {
763 operation: "write temporary metadata",
764 path: temporary_path.to_path_buf(),
765 source,
766 })?;
767 temporary
768 .sync_all()
769 .map_err(|source| PersistenceError::Io {
770 operation: "sync temporary metadata",
771 path: temporary_path.to_path_buf(),
772 source,
773 })?;
774 drop(temporary);
775
776 fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
777 operation: "publish metadata",
778 path: metadata_path.to_path_buf(),
779 source,
780 })?;
781
782 File::open(root)
783 .and_then(|directory| directory.sync_all())
784 .map_err(|source| PersistenceError::Io {
785 operation: "sync output root",
786 path: root.to_path_buf(),
787 source,
788 })
789}