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::{
66 BoundObservationPlan, BoundObservationStream, EncodedObservation, ObservationSession,
67};
68use crate::state::SystemState;
69
70mod error;
71mod json_payload_decoder;
72mod jsonl_format;
73mod queued_state_writer;
74mod stored_state_series_reader;
75
76pub use error::PersistenceError;
77pub use json_payload_decoder::{JsonPayloadDecoder, JsonPayloadDecoderRegistry};
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}
103
104impl RecordingTiming {
105 fn from_stored(
107 timing: &jsonl_format::RecordingTiming,
108 metadata_path: &Path,
109 ) -> Result<Self, PersistenceError> {
110 let finalized_at_utc =
111 timing
112 .finalized_at_utc
113 .clone()
114 .ok_or_else(|| PersistenceError::InvalidMetadata {
115 path: metadata_path.to_path_buf(),
116 reason: "completed recording lacks finalized timestamp".to_owned(),
117 })?;
118 Ok(Self {
119 created_at_utc: timing.created_at_utc.clone(),
120 finalized_at_utc,
121 active_duration_ns: timing.active_duration_ns,
122 })
123 }
124
125 pub fn created_at_utc(&self) -> &str {
127 &self.created_at_utc
128 }
129
130 pub fn finalized_at_utc(&self) -> &str {
132 &self.finalized_at_utc
133 }
134
135 pub fn active_duration(&self) -> Duration {
137 Duration::from_nanos(self.active_duration_ns)
138 }
139}
140
141#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
152#[serde(rename_all = "snake_case")]
153pub(crate) enum SamplingInterval {
154 Iterations(NonZeroU64),
156}
157
158#[derive(Deserialize)]
159#[serde(untagged)]
160enum SamplingIntervalInput {
161 Iterations(NonZeroU64),
163 Tagged { iterations: NonZeroU64 },
165}
166
167impl<'de> Deserialize<'de> for SamplingInterval {
168 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
169 where
170 D: serde::Deserializer<'de>,
171 {
172 match SamplingIntervalInput::deserialize(deserializer)? {
173 SamplingIntervalInput::Iterations(interval)
174 | SamplingIntervalInput::Tagged {
175 iterations: interval,
176 } => Ok(Self::Iterations(interval)),
177 }
178 }
179}
180
181impl SamplingInterval {
182 pub(crate) const fn iterations(interval: u64) -> Option<Self> {
184 match NonZeroU64::new(interval) {
185 Some(interval) => Some(Self::Iterations(interval)),
186 None => None,
187 }
188 }
189}
190
191#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
193#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
194pub(crate) enum StateStreamLayout {
195 Chunked {
197 target_bytes: NonZeroU64,
199 },
200 IndividualFiles,
202}
203
204#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
206#[serde(deny_unknown_fields)]
207pub(crate) struct StateStreamStorage {
208 layout: StateStreamLayout,
209 storage_queue_bytes: NonZeroU64,
210}
211
212impl StateStreamStorage {
213 pub(crate) const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
215 Self {
216 layout: StateStreamLayout::Chunked { target_bytes },
217 storage_queue_bytes,
218 }
219 }
220
221 pub(crate) const fn layout(self) -> StateStreamLayout {
223 self.layout
224 }
225
226 pub(crate) const fn storage_queue_bytes(self) -> NonZeroU64 {
228 self.storage_queue_bytes
229 }
230}
231
232pub(crate) struct SystemStateWriter {
239 manifest: Arc<RecordingManifest>,
240 session: ObservationSession,
241 writer: Option<StateWriterWorker>,
242 session_started: Instant,
243 _lease: RecordingLease,
246}
247
248impl SystemStateWriter {
249 pub(crate) fn create(
251 root: PathBuf,
252 descriptor: BoundObservationPlan,
253 user_metadata: Map<String, Value>,
254 storage: StateStreamStorage,
255 ) -> Result<Self, PersistenceError> {
256 ensure_absent(&root)?;
257 let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
258 create_root(&prepared.root)?;
259 let lease = RecordingLease::acquire(&prepared.root)?;
260 for stream in &prepared.streams {
261 stream.create_directory()?;
262 }
263 commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
264 let manifest = Arc::new(RecordingManifest::new(
265 prepared.root.clone(),
266 prepared.metadata_path,
267 prepared.metadata,
268 ));
269 Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
270 }
271
272 pub(crate) fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
286 let observations = self
287 .session
288 .observe(state)
289 .map_err(|source| PersistenceError::Observation { source })?;
290 let writer = self
291 .writer
292 .as_ref()
293 .expect("an active recording owns its writer worker");
294 submit_observations(writer, observations)?;
295 Ok(())
296 }
297
298 #[cfg(test)]
306 pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
307 self.complete_recording_with_terminal_metadata(Map::new())
308 }
309
310 pub(crate) fn complete_recording_with_terminal_metadata(
316 mut self,
317 terminal_metadata: Map<String, Value>,
318 ) -> Result<(), PersistenceError> {
319 if let Err(error) = self.finish_writer() {
320 let _ = self.transition_terminal(
321 RecordingStatus::Failed {
322 message: error.to_string(),
323 },
324 Map::new(),
325 );
326 return Err(error);
327 }
328 self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
329 }
330
331 pub(crate) fn complete_recording_with_final_state(
338 mut self,
339 state: &SystemState,
340 terminal_metadata: Map<String, Value>,
341 ) -> Result<(), PersistenceError> {
342 if let Err(error) = self.record_final_state(state) {
343 let _ = self.mark_recording_failed(error.to_string());
344 return Err(error);
345 }
346 self.complete_recording_with_terminal_metadata(terminal_metadata)
347 }
348
349 pub(crate) fn record_final_state(
351 &mut self,
352 state: &SystemState,
353 ) -> Result<(), PersistenceError> {
354 let observations = self
355 .session
356 .observe_final(state)
357 .map_err(|source| PersistenceError::Observation { source })?;
358 let writer = self
359 .writer
360 .as_ref()
361 .expect("an active recording owns its writer worker");
362 submit_observations(writer, observations)?;
363 Ok(())
364 }
365
366 pub(crate) fn mark_recording_failed(
378 self,
379 message: impl Into<String>,
380 ) -> Result<(), PersistenceError> {
381 self.mark_recording_failed_with_terminal_metadata(message, Map::new())
382 }
383
384 pub(crate) fn mark_recording_failed_with_terminal_metadata(
386 mut self,
387 message: impl Into<String>,
388 terminal_metadata: Map<String, Value>,
389 ) -> Result<(), PersistenceError> {
390 let message = message.into();
391 if message.trim().is_empty() {
392 return Err(PersistenceError::InvalidConfiguration {
393 setting: "failure_message",
394 reason: "failed run message must not be empty".to_owned(),
395 });
396 }
397
398 if let Err(error) = self.finish_writer() {
399 let _ = self.transition_terminal(
400 RecordingStatus::Failed {
401 message: error.to_string(),
402 },
403 Map::new(),
404 );
405 return Err(error);
406 }
407 self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
408 }
409
410 fn start_new_prepared(
412 descriptor: BoundObservationPlan,
413 streams: Vec<StateStreamStorageConfig>,
414 manifest: Arc<RecordingManifest>,
415 lease: RecordingLease,
416 ) -> Result<Self, PersistenceError> {
417 let mut configs = Vec::with_capacity(streams.len());
418 configs.extend(streams);
419 let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
420 Ok(Self {
421 manifest,
422 session: ObservationSession::new(descriptor),
423 writer: Some(writer),
424 session_started: Instant::now(),
425 _lease: lease,
426 })
427 }
428
429 fn finish_writer(&mut self) -> Result<(), PersistenceError> {
431 let Some(writer) = self.writer.take() else {
432 return Ok(());
433 };
434 writer.finish_recording()
435 }
436
437 fn transition_terminal(
439 &self,
440 status: RecordingStatus,
441 terminal_metadata: Map<String, Value>,
442 ) -> Result<(), PersistenceError> {
443 let finalized_at_utc =
444 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
445 operation: "finalize recording",
446 source,
447 })?;
448 let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
449 .ok_or(PersistenceError::OperationalDurationOverflow)?;
450 self.manifest.transition_terminal(
451 status,
452 finalized_at_utc,
453 active_duration_ns,
454 terminal_metadata,
455 )
456 }
457}
458
459struct PreparedRecording {
461 root: PathBuf,
462 metadata_path: PathBuf,
463 descriptor: BoundObservationPlan,
464 metadata: RecordingMetadata,
465 streams: Vec<StateStreamStorageConfig>,
466}
467
468impl PreparedRecording {
469 fn new(
471 root: PathBuf,
472 descriptor: BoundObservationPlan,
473 user_metadata: Map<String, Value>,
474 storage: StateStreamStorage,
475 ) -> Result<Self, PersistenceError> {
476 let metadata_path = root.join(METADATA_FILE);
477 let stored_time = StoredTimeAxis {
478 iteration_name: "iteration".to_owned(),
479 iteration_unit: descriptor.iteration_unit().map(str::to_owned),
480 physical_time_name: Some("physical_time".to_owned()),
481 physical_time_unit: descriptor.physical_time_unit().map(str::to_owned),
482 };
483 let mut streams = Vec::with_capacity(descriptor.streams().len());
484 let mut declarations = Vec::with_capacity(descriptor.streams().len());
485
486 for (index, stream) in descriptor.streams().iter().enumerate() {
487 let stream: &BoundObservationStream = stream;
488 let directory = format!("stream_{index:04}");
489 let sampling_interval = SamplingInterval::iterations(stream.every_iterations())
490 .expect("bound observation streams contain positive sampling intervals");
491 let fields = stream
492 .fields()
493 .iter()
494 .map(|field| StateFieldMetadata {
495 name: field.name().to_owned(),
496 description: field.description().map(str::to_owned),
497 })
498 .collect::<Vec<_>>();
499 declarations.push(StateStreamMetadata {
500 name: stream.name().to_owned(),
501 directory: directory.clone(),
502 sampling_interval,
503 fields,
504 storage,
505 chunks: Vec::new(),
506 });
507 streams.push(StateStreamStorageConfig::new(
508 stream.name(),
509 root.join(&directory),
510 storage,
511 )?);
512 }
513
514 let created_at_utc =
515 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
516 operation: "create recording",
517 source,
518 })?;
519 let metadata =
520 RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
521 metadata.validate(&metadata_path)?;
522 Ok(Self {
523 root,
524 metadata_path,
525 descriptor,
526 metadata,
527 streams,
528 })
529 }
530}
531
532fn submit_observations(
533 writer: &StateWriterWorker,
534 observations: Vec<EncodedObservation>,
535) -> Result<(), PersistenceError> {
536 for observation in observations {
537 let (stream, time, bytes) = observation.into_parts();
538 writer.submit_record(stream, EncodedStateRecord::new(time, bytes))?;
539 }
540 Ok(())
541}
542
543pub(crate) struct RecordingManifest {
549 root: PathBuf,
550 path: PathBuf,
551 metadata: Mutex<RecordingMetadata>,
552}
553
554impl RecordingManifest {
555 fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
557 Self {
558 root,
559 path,
560 metadata: Mutex::new(metadata),
561 }
562 }
563
564 pub(crate) fn prepare_chunk(
566 &self,
567 stream: &str,
568 descriptor: jsonl_format::ChunkMetadata,
569 ) -> Result<(), PersistenceError> {
570 let mut current = lock_metadata(&self.metadata);
571 if !matches!(current.status, RecordingStatus::Running) {
572 return Err(PersistenceError::RecordingFinished);
573 }
574 let mut candidate = current.clone();
575 let declaration =
576 candidate
577 .stream_mut(stream)
578 .ok_or_else(|| PersistenceError::UnknownStateStream {
579 stream: stream.to_owned(),
580 })?;
581 let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
582 PersistenceError::ByteCountOverflow {
583 stream: stream.to_owned(),
584 }
585 })?;
586 if descriptor.ordinal != expected {
587 return Err(PersistenceError::InvalidMetadata {
588 path: self.path.clone(),
589 reason: format!(
590 "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
591 descriptor.ordinal
592 ),
593 });
594 }
595 declaration.chunks.push(descriptor);
596 commit_metadata(&self.root, &self.path, &candidate)?;
597 *current = candidate;
598 Ok(())
599 }
600
601 fn transition_terminal(
603 &self,
604 status: RecordingStatus,
605 finalized_at_utc: String,
606 active_duration_ns: u64,
607 terminal_metadata: Map<String, Value>,
608 ) -> Result<(), PersistenceError> {
609 let mut current = lock_metadata(&self.metadata);
610 let mut candidate = current.clone();
611 candidate.status = status;
612 candidate.timing.finalized_at_utc = Some(finalized_at_utc);
613 candidate.timing.active_duration_ns = candidate
614 .timing
615 .active_duration_ns
616 .checked_add(active_duration_ns)
617 .ok_or(PersistenceError::OperationalDurationOverflow)?;
618 candidate.terminal_metadata = terminal_metadata;
619 commit_metadata(&self.root, &self.path, &candidate)?;
620 *current = candidate;
621 Ok(())
622 }
623}
624
625struct RecordingLease {
630 directory: File,
631}
632
633impl RecordingLease {
634 fn acquire(root: &Path) -> Result<Self, PersistenceError> {
636 let directory = File::open(root).map_err(|source| PersistenceError::Io {
637 operation: "open output root for exclusive ownership",
638 path: root.to_path_buf(),
639 source,
640 })?;
641 match FileExt::try_lock_exclusive(&directory) {
642 Ok(()) => Ok(Self { directory }),
643 Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
644 Err(PersistenceError::RecordingDirectoryInUse {
645 path: root.to_path_buf(),
646 })
647 }
648 Err(source) => Err(PersistenceError::Io {
649 operation: "acquire exclusive output ownership",
650 path: root.to_path_buf(),
651 source,
652 }),
653 }
654 }
655}
656
657impl Drop for RecordingLease {
658 fn drop(&mut self) {
659 let _ = FileExt::unlock(&self.directory);
663 }
664}
665
666fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
668 metadata
669 .lock()
670 .unwrap_or_else(|poisoned| poisoned.into_inner())
671}
672
673fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
675 match root.try_exists() {
676 Ok(false) => Ok(()),
677 Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
678 path: root.to_path_buf(),
679 }),
680 Err(source) => Err(PersistenceError::Io {
681 operation: "inspect output root",
682 path: root.to_path_buf(),
683 source,
684 }),
685 }
686}
687
688fn create_root(root: &Path) -> Result<(), PersistenceError> {
690 if let Some(parent) = root.parent() {
691 fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
692 operation: "create recording parent directories",
693 path: parent.to_path_buf(),
694 source,
695 })?;
696 }
697 match fs::create_dir(root) {
698 Ok(()) => Ok(()),
699 Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
700 Err(PersistenceError::RecordingDirectoryExists {
701 path: root.to_path_buf(),
702 })
703 }
704 Err(source) => Err(PersistenceError::Io {
705 operation: "create output root",
706 path: root.to_path_buf(),
707 source,
708 }),
709 }
710}
711
712fn commit_metadata(
720 root: &Path,
721 metadata_path: &Path,
722 metadata: &RecordingMetadata,
723) -> Result<(), PersistenceError> {
724 metadata.validate(metadata_path)?;
725 let mut bytes =
726 serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
727 operation: "serialize metadata",
728 path: metadata_path.to_path_buf(),
729 source,
730 })?;
731 bytes.push(b'\n');
732
733 let temporary_path = root.join(METADATA_TEMP_FILE);
734 let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
735 if result.is_err() {
736 let _ = fs::remove_file(&temporary_path);
737 }
738 result
739}
740
741fn write_and_replace_metadata(
743 root: &Path,
744 metadata_path: &Path,
745 temporary_path: &Path,
746 bytes: &[u8],
747) -> Result<(), PersistenceError> {
748 let mut temporary = OpenOptions::new()
749 .write(true)
750 .create_new(true)
751 .open(temporary_path)
752 .map_err(|source| PersistenceError::Io {
753 operation: "create temporary metadata",
754 path: temporary_path.to_path_buf(),
755 source,
756 })?;
757 temporary
758 .write_all(bytes)
759 .map_err(|source| PersistenceError::Io {
760 operation: "write temporary metadata",
761 path: temporary_path.to_path_buf(),
762 source,
763 })?;
764 temporary
765 .sync_all()
766 .map_err(|source| PersistenceError::Io {
767 operation: "sync temporary metadata",
768 path: temporary_path.to_path_buf(),
769 source,
770 })?;
771 drop(temporary);
772
773 fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
774 operation: "publish metadata",
775 path: metadata_path.to_path_buf(),
776 source,
777 })?;
778
779 File::open(root)
780 .and_then(|directory| directory.sync_all())
781 .map_err(|source| PersistenceError::Io {
782 operation: "sync output root",
783 path: root.to_path_buf(),
784 source,
785 })
786}