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::{
66 BoundObservationPlan, BoundObservationStream, EncodedObservation, ObservationSession,
67};
68use crate::state::advanced::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::{
78 JsonPayloadDecoder, JsonPayloadDecoderRegistry, JsonStringDecoder, JsonVecF64Decoder,
79};
80pub use stored_state_series_reader::StoredStateSeriesReader;
81
82use jsonl_format::{
83 EncodedStateRecord, RecordingMetadata, RecordingStatus, StateFieldMetadata,
84 StateStreamMetadata, TimeAxisMetadata as StoredTimeAxis,
85};
86use queued_state_writer::{StateStreamStorageConfig, StateWriterWorker};
87
88const METADATA_FILE: &str = "metadata.json";
90
91const METADATA_TEMP_FILE: &str = ".metadata.json.tmp";
93
94#[derive(Clone, Debug, Eq, PartialEq)]
100pub struct RecordingTiming {
101 created_at_utc: String,
102 finalized_at_utc: String,
103 active_duration_ns: u64,
104 continuation_count: u64,
105}
106
107impl RecordingTiming {
108 fn from_stored(
110 timing: &jsonl_format::RecordingTiming,
111 metadata_path: &Path,
112 ) -> Result<Self, PersistenceError> {
113 let finalized_at_utc =
114 timing
115 .finalized_at_utc
116 .clone()
117 .ok_or_else(|| PersistenceError::InvalidMetadata {
118 path: metadata_path.to_path_buf(),
119 reason: "completed recording lacks finalized timestamp".to_owned(),
120 })?;
121 Ok(Self {
122 created_at_utc: timing.created_at_utc.clone(),
123 finalized_at_utc,
124 active_duration_ns: timing.active_duration_ns,
125 continuation_count: timing.continuation_count,
126 })
127 }
128
129 pub fn created_at_utc(&self) -> &str {
131 &self.created_at_utc
132 }
133
134 pub fn finalized_at_utc(&self) -> &str {
136 &self.finalized_at_utc
137 }
138
139 pub fn active_duration_ns(&self) -> u64 {
141 self.active_duration_ns
142 }
143
144 pub fn active_duration(&self) -> Duration {
146 Duration::from_nanos(self.active_duration_ns)
147 }
148
149 pub fn continuation_count(&self) -> u64 {
154 self.continuation_count
155 }
156}
157
158#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
169#[serde(rename_all = "snake_case")]
170pub(crate) enum SamplingInterval {
171 Iterations(NonZeroU64),
173}
174
175#[derive(Deserialize)]
176#[serde(untagged)]
177enum SamplingIntervalInput {
178 Iterations(NonZeroU64),
180 Tagged { iterations: NonZeroU64 },
182}
183
184impl<'de> Deserialize<'de> for SamplingInterval {
185 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
186 where
187 D: serde::Deserializer<'de>,
188 {
189 match SamplingIntervalInput::deserialize(deserializer)? {
190 SamplingIntervalInput::Iterations(interval)
191 | SamplingIntervalInput::Tagged {
192 iterations: interval,
193 } => Ok(Self::Iterations(interval)),
194 }
195 }
196}
197
198impl SamplingInterval {
199 pub(crate) const fn iterations(interval: u64) -> Option<Self> {
201 match NonZeroU64::new(interval) {
202 Some(interval) => Some(Self::Iterations(interval)),
203 None => None,
204 }
205 }
206}
207
208#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
210#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
211pub(crate) enum StateStreamLayout {
212 Chunked {
214 target_bytes: NonZeroU64,
216 },
217 IndividualFiles,
219}
220
221#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
223#[serde(deny_unknown_fields)]
224pub(crate) struct StateStreamStorage {
225 layout: StateStreamLayout,
226 storage_queue_bytes: NonZeroU64,
227}
228
229impl StateStreamStorage {
230 pub(crate) const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
232 Self {
233 layout: StateStreamLayout::Chunked { target_bytes },
234 storage_queue_bytes,
235 }
236 }
237
238 pub(crate) const fn layout(self) -> StateStreamLayout {
240 self.layout
241 }
242
243 pub(crate) const fn storage_queue_bytes(self) -> NonZeroU64 {
245 self.storage_queue_bytes
246 }
247}
248
249pub(crate) struct SystemStateWriter {
256 manifest: Arc<RecordingManifest>,
257 session: ObservationSession,
258 writer: Option<StateWriterWorker>,
259 session_started: Instant,
260 _lease: RecordingLease,
263}
264
265impl SystemStateWriter {
266 pub(crate) fn create(
268 root: PathBuf,
269 descriptor: BoundObservationPlan,
270 user_metadata: Map<String, Value>,
271 storage: StateStreamStorage,
272 ) -> Result<Self, PersistenceError> {
273 ensure_absent(&root)?;
274 let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
275 create_root(&prepared.root)?;
276 let lease = RecordingLease::acquire(&prepared.root)?;
277 for stream in &prepared.streams {
278 stream.create_directory()?;
279 }
280 commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
281 let manifest = Arc::new(RecordingManifest::new(
282 prepared.root.clone(),
283 prepared.metadata_path,
284 prepared.metadata,
285 ));
286 Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
287 }
288
289 pub(crate) fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
303 let observations = self
304 .session
305 .observe(state)
306 .map_err(|source| PersistenceError::Observation { source })?;
307 let writer = self
308 .writer
309 .as_ref()
310 .expect("an active recording owns its writer worker");
311 submit_observations(writer, observations)?;
312 Ok(())
313 }
314
315 pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
323 self.complete_recording_with_terminal_metadata(Map::new())
324 }
325
326 pub(crate) fn complete_recording_with_terminal_metadata(
332 mut self,
333 terminal_metadata: Map<String, Value>,
334 ) -> Result<(), PersistenceError> {
335 if let Err(error) = self.finish_writer() {
336 let _ = self.transition_terminal(
337 RecordingStatus::Failed {
338 message: error.to_string(),
339 },
340 Map::new(),
341 );
342 return Err(error);
343 }
344 self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
345 }
346
347 pub(crate) fn complete_recording_with_final_state(
354 mut self,
355 state: &SystemState,
356 ) -> Result<(), PersistenceError> {
357 if let Err(error) = self.record_final_state(state) {
358 let _ = self.mark_recording_failed(error.to_string());
359 return Err(error);
360 }
361 self.complete_recording()
362 }
363
364 pub(crate) fn record_final_state(
366 &mut self,
367 state: &SystemState,
368 ) -> Result<(), PersistenceError> {
369 let observations = self
370 .session
371 .observe_final(state)
372 .map_err(|source| PersistenceError::Observation { source })?;
373 let writer = self
374 .writer
375 .as_ref()
376 .expect("an active recording owns its writer worker");
377 submit_observations(writer, observations)?;
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 stream: &BoundObservationStream = stream;
503 let directory = format!("stream_{index:04}");
504 let sampling_interval = SamplingInterval::iterations(stream.every_iterations())
505 .expect("bound observation streams contain positive sampling intervals");
506 let fields = stream
507 .fields()
508 .iter()
509 .map(|field| StateFieldMetadata {
510 name: field.name().to_owned(),
511 description: field.description().map(str::to_owned),
512 })
513 .collect::<Vec<_>>();
514 declarations.push(StateStreamMetadata {
515 name: stream.name().to_owned(),
516 directory: directory.clone(),
517 sampling_interval,
518 fields,
519 storage,
520 chunks: Vec::new(),
521 });
522 streams.push(StateStreamStorageConfig::new(
523 stream.name(),
524 root.join(&directory),
525 storage,
526 )?);
527 }
528
529 let created_at_utc =
530 utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
531 operation: "create recording",
532 source,
533 })?;
534 let metadata =
535 RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
536 metadata.validate(&metadata_path)?;
537 Ok(Self {
538 root,
539 metadata_path,
540 descriptor,
541 metadata,
542 streams,
543 })
544 }
545}
546
547fn submit_observations(
548 writer: &StateWriterWorker,
549 observations: Vec<EncodedObservation>,
550) -> Result<(), PersistenceError> {
551 for observation in observations {
552 let (stream, time, bytes) = observation.into_parts();
553 writer.submit_record(stream, EncodedStateRecord::new(time, bytes))?;
554 }
555 Ok(())
556}
557
558pub(crate) struct RecordingManifest {
564 root: PathBuf,
565 path: PathBuf,
566 metadata: Mutex<RecordingMetadata>,
567}
568
569impl RecordingManifest {
570 fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
572 Self {
573 root,
574 path,
575 metadata: Mutex::new(metadata),
576 }
577 }
578
579 pub(crate) fn prepare_chunk(
581 &self,
582 stream: &str,
583 descriptor: jsonl_format::ChunkMetadata,
584 ) -> Result<(), PersistenceError> {
585 let mut current = lock_metadata(&self.metadata);
586 if !matches!(current.status, RecordingStatus::Running) {
587 return Err(PersistenceError::RecordingFinished);
588 }
589 let mut candidate = current.clone();
590 let declaration =
591 candidate
592 .stream_mut(stream)
593 .ok_or_else(|| PersistenceError::UnknownStateStream {
594 stream: stream.to_owned(),
595 })?;
596 let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
597 PersistenceError::ByteCountOverflow {
598 stream: stream.to_owned(),
599 }
600 })?;
601 if descriptor.ordinal != expected {
602 return Err(PersistenceError::InvalidMetadata {
603 path: self.path.clone(),
604 reason: format!(
605 "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
606 descriptor.ordinal
607 ),
608 });
609 }
610 declaration.chunks.push(descriptor);
611 commit_metadata(&self.root, &self.path, &candidate)?;
612 *current = candidate;
613 Ok(())
614 }
615
616 fn transition_terminal(
618 &self,
619 status: RecordingStatus,
620 finalized_at_utc: String,
621 active_duration_ns: u64,
622 terminal_metadata: Map<String, Value>,
623 ) -> Result<(), PersistenceError> {
624 let mut current = lock_metadata(&self.metadata);
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_exclusive(&directory) {
657 Ok(()) => Ok(Self { directory }),
658 Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
659 Err(PersistenceError::RecordingDirectoryInUse {
660 path: root.to_path_buf(),
661 })
662 }
663 Err(source) => Err(PersistenceError::Io {
664 operation: "acquire exclusive output ownership",
665 path: root.to_path_buf(),
666 source,
667 }),
668 }
669 }
670}
671
672impl Drop for RecordingLease {
673 fn drop(&mut self) {
674 let _ = FileExt::unlock(&self.directory);
678 }
679}
680
681fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
683 metadata
684 .lock()
685 .unwrap_or_else(|poisoned| poisoned.into_inner())
686}
687
688fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
690 match root.try_exists() {
691 Ok(false) => Ok(()),
692 Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
693 path: root.to_path_buf(),
694 }),
695 Err(source) => Err(PersistenceError::Io {
696 operation: "inspect output root",
697 path: root.to_path_buf(),
698 source,
699 }),
700 }
701}
702
703fn create_root(root: &Path) -> Result<(), PersistenceError> {
705 if let Some(parent) = root.parent() {
706 fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
707 operation: "create recording parent directories",
708 path: parent.to_path_buf(),
709 source,
710 })?;
711 }
712 match fs::create_dir(root) {
713 Ok(()) => Ok(()),
714 Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
715 Err(PersistenceError::RecordingDirectoryExists {
716 path: root.to_path_buf(),
717 })
718 }
719 Err(source) => Err(PersistenceError::Io {
720 operation: "create output root",
721 path: root.to_path_buf(),
722 source,
723 }),
724 }
725}
726
727fn commit_metadata(
735 root: &Path,
736 metadata_path: &Path,
737 metadata: &RecordingMetadata,
738) -> Result<(), PersistenceError> {
739 metadata.validate(metadata_path)?;
740 let mut bytes =
741 serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
742 operation: "serialize metadata",
743 path: metadata_path.to_path_buf(),
744 source,
745 })?;
746 bytes.push(b'\n');
747
748 let temporary_path = root.join(METADATA_TEMP_FILE);
749 let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
750 if result.is_err() {
751 let _ = fs::remove_file(&temporary_path);
752 }
753 result
754}
755
756fn write_and_replace_metadata(
758 root: &Path,
759 metadata_path: &Path,
760 temporary_path: &Path,
761 bytes: &[u8],
762) -> Result<(), PersistenceError> {
763 let mut temporary = OpenOptions::new()
764 .write(true)
765 .create_new(true)
766 .open(temporary_path)
767 .map_err(|source| PersistenceError::Io {
768 operation: "create temporary metadata",
769 path: temporary_path.to_path_buf(),
770 source,
771 })?;
772 temporary
773 .write_all(bytes)
774 .map_err(|source| PersistenceError::Io {
775 operation: "write temporary metadata",
776 path: temporary_path.to_path_buf(),
777 source,
778 })?;
779 temporary
780 .sync_all()
781 .map_err(|source| PersistenceError::Io {
782 operation: "sync temporary metadata",
783 path: temporary_path.to_path_buf(),
784 source,
785 })?;
786 drop(temporary);
787
788 fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
789 operation: "publish metadata",
790 path: metadata_path.to_path_buf(),
791 source,
792 })?;
793
794 File::open(root)
795 .and_then(|directory| directory.sync_all())
796 .map_err(|source| PersistenceError::Io {
797 operation: "sync output root",
798 path: root.to_path_buf(),
799 source,
800 })
801}