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 fs4::FileExt;
61use serde::{Deserialize, Serialize};
62use serde_json::{Map, Value};
63
64use super::operational_time::{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)]
151#[serde(rename_all = "snake_case")]
152pub(crate) enum SamplingInterval {
153 Iterations(NonZeroU64),
155 InitialAndFinal(bool),
157}
158
159#[derive(Deserialize)]
160#[serde(untagged, deny_unknown_fields)]
161enum SamplingIntervalInput {
162 Tagged {
164 iterations: NonZeroU64,
165 },
166 Boundaries {
167 initial_and_final: bool,
168 },
169}
170
171impl<'de> Deserialize<'de> for SamplingInterval {
172 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
173 where
174 D: serde::Deserializer<'de>,
175 {
176 match SamplingIntervalInput::deserialize(deserializer)? {
177 SamplingIntervalInput::Tagged {
178 iterations: interval,
179 } => Ok(Self::Iterations(interval)),
180 SamplingIntervalInput::Boundaries {
181 initial_and_final: true,
182 } => Ok(Self::InitialAndFinal(true)),
183 SamplingIntervalInput::Boundaries {
184 initial_and_final: false,
185 } => Err(serde::de::Error::custom("initial_and_final must be true")),
186 }
187 }
188}
189
190impl SamplingInterval {
191 pub(crate) const fn iterations(interval: u64) -> Option<Self> {
193 match NonZeroU64::new(interval) {
194 Some(interval) => Some(Self::Iterations(interval)),
195 None => None,
196 }
197 }
198}
199
200#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
202#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
203pub(crate) enum StateStreamLayout {
204 Chunked {
206 target_bytes: NonZeroU64,
208 },
209 IndividualFiles,
211}
212
213#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
215#[serde(deny_unknown_fields)]
216pub(crate) struct StateStreamStorage {
217 layout: StateStreamLayout,
218 storage_queue_bytes: NonZeroU64,
219}
220
221impl StateStreamStorage {
222 pub(crate) const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
224 Self {
225 layout: StateStreamLayout::Chunked { target_bytes },
226 storage_queue_bytes,
227 }
228 }
229
230 pub(crate) const fn layout(self) -> StateStreamLayout {
232 self.layout
233 }
234
235 pub(crate) const fn storage_queue_bytes(self) -> NonZeroU64 {
237 self.storage_queue_bytes
238 }
239}
240
241pub(crate) struct SystemStateWriter {
248 manifest: Arc<RecordingManifest>,
249 session: ObservationSession,
250 writer: Option<StateWriterWorker>,
251 session_started: Instant,
252 _lease: RecordingLease,
255}
256
257impl SystemStateWriter {
258 pub(crate) fn create(
260 root: PathBuf,
261 descriptor: BoundObservationPlan,
262 user_metadata: Map<String, Value>,
263 storage: StateStreamStorage,
264 ) -> Result<Self, PersistenceError> {
265 ensure_absent(&root)?;
266 let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
267 create_root(&prepared.root)?;
268 let lease = RecordingLease::acquire(&prepared.root)?;
269 for stream in &prepared.streams {
270 stream.create_directory()?;
271 }
272 commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
273 let manifest = Arc::new(RecordingManifest::new(
274 prepared.root.clone(),
275 prepared.metadata_path,
276 prepared.metadata,
277 ));
278 Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
279 }
280
281 pub(crate) fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
295 let observations = self
296 .session
297 .observe(state)
298 .map_err(|source| PersistenceError::Observation { source })?;
299 let writer = self
300 .writer
301 .as_ref()
302 .expect("an active recording owns its writer worker");
303 submit_observations(writer, observations)?;
304 Ok(())
305 }
306
307 #[cfg(test)]
315 pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
316 self.complete_recording_with_terminal_metadata(Map::new())
317 }
318
319 pub(crate) fn complete_recording_with_terminal_metadata(
325 mut self,
326 terminal_metadata: Map<String, Value>,
327 ) -> Result<(), PersistenceError> {
328 if let Err(error) = self.finish_writer() {
329 let _ = self.transition_terminal(
330 RecordingStatus::Failed {
331 message: error.to_string(),
332 },
333 Map::new(),
334 );
335 return Err(error);
336 }
337 self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
338 }
339
340 pub(crate) fn complete_recording_with_final_state(
347 mut self,
348 state: &SystemState,
349 terminal_metadata: Map<String, Value>,
350 ) -> Result<(), PersistenceError> {
351 if let Err(error) = self.record_final_state(state) {
352 let _ = self.mark_recording_failed(error.to_string());
353 return Err(error);
354 }
355 self.complete_recording_with_terminal_metadata(terminal_metadata)
356 }
357
358 pub(crate) fn record_final_state(
360 &mut self,
361 state: &SystemState,
362 ) -> Result<(), PersistenceError> {
363 let observations = self
364 .session
365 .observe_final(state)
366 .map_err(|source| PersistenceError::Observation { source })?;
367 let writer = self
368 .writer
369 .as_ref()
370 .expect("an active recording owns its writer worker");
371 submit_observations(writer, observations)?;
372 Ok(())
373 }
374
375 pub(crate) fn mark_recording_failed(
387 self,
388 message: impl Into<String>,
389 ) -> Result<(), PersistenceError> {
390 self.mark_recording_failed_with_terminal_metadata(message, Map::new())
391 }
392
393 pub(crate) fn mark_recording_failed_with_terminal_metadata(
395 mut self,
396 message: impl Into<String>,
397 terminal_metadata: Map<String, Value>,
398 ) -> Result<(), PersistenceError> {
399 let message = message.into();
400 if message.trim().is_empty() {
401 return Err(PersistenceError::InvalidConfiguration {
402 setting: "failure_message",
403 reason: "failed run message must not be empty".to_owned(),
404 });
405 }
406
407 if let Err(error) = self.finish_writer() {
408 let _ = self.transition_terminal(
409 RecordingStatus::Failed {
410 message: error.to_string(),
411 },
412 Map::new(),
413 );
414 return Err(error);
415 }
416 self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
417 }
418
419 fn start_new_prepared(
421 descriptor: BoundObservationPlan,
422 streams: Vec<StateStreamStorageConfig>,
423 manifest: Arc<RecordingManifest>,
424 lease: RecordingLease,
425 ) -> Result<Self, PersistenceError> {
426 let mut configs = Vec::with_capacity(streams.len());
427 configs.extend(streams);
428 let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
429 Ok(Self {
430 manifest,
431 session: ObservationSession::new(descriptor),
432 writer: Some(writer),
433 session_started: Instant::now(),
434 _lease: lease,
435 })
436 }
437
438 fn finish_writer(&mut self) -> Result<(), PersistenceError> {
440 let Some(writer) = self.writer.take() else {
441 return Ok(());
442 };
443 writer.finish_recording()
444 }
445
446 fn transition_terminal(
448 &self,
449 status: RecordingStatus,
450 terminal_metadata: Map<String, Value>,
451 ) -> Result<(), PersistenceError> {
452 let finalized_at_utc =
453 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
454 operation: "finalize recording",
455 source,
456 })?;
457 let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
458 .ok_or(PersistenceError::OperationalDurationOverflow)?;
459 self.manifest.transition_terminal(
460 status,
461 finalized_at_utc,
462 active_duration_ns,
463 terminal_metadata,
464 )
465 }
466}
467
468struct PreparedRecording {
470 root: PathBuf,
471 metadata_path: PathBuf,
472 descriptor: BoundObservationPlan,
473 metadata: RecordingMetadata,
474 streams: Vec<StateStreamStorageConfig>,
475}
476
477impl PreparedRecording {
478 fn new(
480 root: PathBuf,
481 descriptor: BoundObservationPlan,
482 user_metadata: Map<String, Value>,
483 storage: StateStreamStorage,
484 ) -> Result<Self, PersistenceError> {
485 let metadata_path = root.join(METADATA_FILE);
486 let stored_time = StoredTimeAxis {
487 iteration_name: "iteration".to_owned(),
488 iteration_unit: descriptor.iteration_unit().map(str::to_owned),
489 physical_time_name: Some("physical_time".to_owned()),
490 physical_time_unit: descriptor.physical_time_unit().map(str::to_owned),
491 };
492 let mut streams = Vec::with_capacity(descriptor.streams().len());
493 let mut declarations = Vec::with_capacity(descriptor.streams().len());
494
495 for (index, stream) in descriptor.streams().iter().enumerate() {
496 let stream: &BoundObservationStream = stream;
497 let directory = format!("stream_{index:04}");
498 let sampling_interval = stream
499 .every_iterations()
500 .map_or(SamplingInterval::InitialAndFinal(true), |n| {
501 SamplingInterval::iterations(n).expect("positive bound interval")
502 });
503 let fields = stream
504 .fields()
505 .iter()
506 .map(|field| StateFieldMetadata {
507 name: field.name().to_owned(),
508 description: field.description().map(str::to_owned),
509 })
510 .collect::<Vec<_>>();
511 declarations.push(StateStreamMetadata {
512 name: stream.name().to_owned(),
513 directory: directory.clone(),
514 sampling_interval,
515 fields,
516 storage,
517 chunks: Vec::new(),
518 });
519 streams.push(StateStreamStorageConfig::new(
520 stream.name(),
521 root.join(&directory),
522 storage,
523 )?);
524 }
525
526 let created_at_utc =
527 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
528 operation: "create recording",
529 source,
530 })?;
531 let metadata =
532 RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
533 metadata.validate(&metadata_path)?;
534 Ok(Self {
535 root,
536 metadata_path,
537 descriptor,
538 metadata,
539 streams,
540 })
541 }
542}
543
544fn submit_observations(
545 writer: &StateWriterWorker,
546 observations: Vec<EncodedObservation>,
547) -> Result<(), PersistenceError> {
548 for observation in observations {
549 let (stream, time, bytes) = observation.into_parts();
550 writer.submit_record(stream, EncodedStateRecord::new(time, bytes))?;
551 }
552 Ok(())
553}
554
555pub(crate) struct RecordingManifest {
561 root: PathBuf,
562 path: PathBuf,
563 metadata: Mutex<RecordingMetadata>,
564}
565
566impl RecordingManifest {
567 fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
569 Self {
570 root,
571 path,
572 metadata: Mutex::new(metadata),
573 }
574 }
575
576 pub(crate) fn prepare_chunk(
578 &self,
579 stream: &str,
580 descriptor: jsonl_format::ChunkMetadata,
581 ) -> Result<(), PersistenceError> {
582 let mut current = lock_metadata(&self.metadata);
583 if !matches!(current.status, RecordingStatus::Running) {
584 return Err(PersistenceError::RecordingFinished);
585 }
586 let mut candidate = current.clone();
587 let declaration =
588 candidate
589 .stream_mut(stream)
590 .ok_or_else(|| PersistenceError::UnknownStateStream {
591 stream: stream.to_owned(),
592 })?;
593 let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
594 PersistenceError::ByteCountOverflow {
595 stream: stream.to_owned(),
596 }
597 })?;
598 if descriptor.ordinal != expected {
599 return Err(PersistenceError::InvalidMetadata {
600 path: self.path.clone(),
601 reason: format!(
602 "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
603 descriptor.ordinal
604 ),
605 });
606 }
607 declaration.chunks.push(descriptor);
608 commit_metadata(&self.root, &self.path, &candidate)?;
609 *current = candidate;
610 Ok(())
611 }
612
613 fn transition_terminal(
615 &self,
616 status: RecordingStatus,
617 finalized_at_utc: String,
618 active_duration_ns: u64,
619 terminal_metadata: Map<String, Value>,
620 ) -> Result<(), PersistenceError> {
621 let mut current = lock_metadata(&self.metadata);
622 if !matches!(current.status, RecordingStatus::Running) {
623 return Err(PersistenceError::RecordingFinished);
624 }
625 let mut candidate = current.clone();
626 candidate.status = status;
627 candidate.timing.finalized_at_utc = Some(finalized_at_utc);
628 candidate.timing.active_duration_ns = candidate
629 .timing
630 .active_duration_ns
631 .checked_add(active_duration_ns)
632 .ok_or(PersistenceError::OperationalDurationOverflow)?;
633 candidate.terminal_metadata = terminal_metadata;
634 commit_metadata(&self.root, &self.path, &candidate)?;
635 *current = candidate;
636 Ok(())
637 }
638}
639
640struct RecordingLease {
645 directory: File,
646}
647
648impl RecordingLease {
649 fn acquire(root: &Path) -> Result<Self, PersistenceError> {
651 let directory = File::open(root).map_err(|source| PersistenceError::Io {
652 operation: "open output root for exclusive ownership",
653 path: root.to_path_buf(),
654 source,
655 })?;
656 match FileExt::try_lock(&directory) {
657 Ok(()) => Ok(Self { directory }),
658 Err(fs4::TryLockError::WouldBlock) => Err(PersistenceError::RecordingDirectoryInUse {
659 path: root.to_path_buf(),
660 }),
661 Err(source) => Err(PersistenceError::Io {
662 operation: "acquire exclusive output ownership",
663 path: root.to_path_buf(),
664 source: source.into(),
665 }),
666 }
667 }
668}
669
670impl Drop for RecordingLease {
671 fn drop(&mut self) {
672 let _ = FileExt::unlock(&self.directory);
676 }
677}
678
679fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
681 metadata
682 .lock()
683 .unwrap_or_else(|poisoned| poisoned.into_inner())
684}
685
686fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
688 match root.try_exists() {
689 Ok(false) => Ok(()),
690 Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
691 path: root.to_path_buf(),
692 }),
693 Err(source) => Err(PersistenceError::Io {
694 operation: "inspect output root",
695 path: root.to_path_buf(),
696 source,
697 }),
698 }
699}
700
701fn create_root(root: &Path) -> Result<(), PersistenceError> {
703 if let Some(parent) = root.parent() {
704 fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
705 operation: "create recording parent directories",
706 path: parent.to_path_buf(),
707 source,
708 })?;
709 }
710 match fs::create_dir(root) {
711 Ok(()) => Ok(()),
712 Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
713 Err(PersistenceError::RecordingDirectoryExists {
714 path: root.to_path_buf(),
715 })
716 }
717 Err(source) => Err(PersistenceError::Io {
718 operation: "create output root",
719 path: root.to_path_buf(),
720 source,
721 }),
722 }
723}
724
725fn commit_metadata(
733 root: &Path,
734 metadata_path: &Path,
735 metadata: &RecordingMetadata,
736) -> Result<(), PersistenceError> {
737 metadata.validate(metadata_path)?;
738 let mut bytes =
739 serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
740 operation: "serialize metadata",
741 path: metadata_path.to_path_buf(),
742 source,
743 })?;
744 bytes.push(b'\n');
745
746 let temporary_path = root.join(METADATA_TEMP_FILE);
747 let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
748 if result.is_err() {
749 let _ = fs::remove_file(&temporary_path);
750 }
751 result
752}
753
754fn write_and_replace_metadata(
756 root: &Path,
757 metadata_path: &Path,
758 temporary_path: &Path,
759 bytes: &[u8],
760) -> Result<(), PersistenceError> {
761 let mut temporary = OpenOptions::new()
762 .write(true)
763 .create_new(true)
764 .open(temporary_path)
765 .map_err(|source| PersistenceError::Io {
766 operation: "create temporary metadata",
767 path: temporary_path.to_path_buf(),
768 source,
769 })?;
770 temporary
771 .write_all(bytes)
772 .map_err(|source| PersistenceError::Io {
773 operation: "write temporary metadata",
774 path: temporary_path.to_path_buf(),
775 source,
776 })?;
777 temporary
778 .sync_all()
779 .map_err(|source| PersistenceError::Io {
780 operation: "sync temporary metadata",
781 path: temporary_path.to_path_buf(),
782 source,
783 })?;
784 drop(temporary);
785
786 fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
787 operation: "publish metadata",
788 path: metadata_path.to_path_buf(),
789 source,
790 })?;
791
792 File::open(root)
793 .and_then(|directory| directory.sync_all())
794 .map_err(|source| PersistenceError::Io {
795 operation: "sync output root",
796 path: root.to_path_buf(),
797 source,
798 })
799}