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