Skip to main content

skenion_runtime/
preview_control_state.rs

1use std::{
2    fs, io,
3    path::{Path, PathBuf},
4    sync::atomic::{AtomicU64, Ordering},
5};
6
7use serde::{Deserialize, Serialize};
8
9use crate::{ControlMessage, ControlState, ControlValue, telemetry::unix_ms_timestamp};
10
11pub const PREVIEW_CONTROL_STATE_SCHEMA: &str = "skenion.preview.control-state";
12pub const PREVIEW_CONTROL_STATE_SCHEMA_VERSION: &str = "0.1.0";
13static PREVIEW_CONTROL_STATE_COUNTER: AtomicU64 = AtomicU64::new(0);
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16#[serde(rename_all = "camelCase")]
17pub struct PreviewControlStateSnapshot {
18    pub schema: String,
19    pub schema_version: String,
20    pub session_revision: u64,
21    pub control_revision: u64,
22    pub values: std::collections::BTreeMap<String, ControlValue>,
23    pub channels: std::collections::BTreeMap<String, ControlMessage>,
24    #[serde(default)]
25    pub operator_right: std::collections::BTreeMap<String, ControlValue>,
26    pub written_at: String,
27}
28
29impl PreviewControlStateSnapshot {
30    pub fn new(session_revision: u64, control_revision: u64, control_state: &ControlState) -> Self {
31        Self {
32            schema: PREVIEW_CONTROL_STATE_SCHEMA.to_owned(),
33            schema_version: PREVIEW_CONTROL_STATE_SCHEMA_VERSION.to_owned(),
34            session_revision,
35            control_revision,
36            values: control_state.values.clone(),
37            channels: control_state.channels.clone(),
38            operator_right: control_state.operator_right.clone(),
39            written_at: unix_ms_timestamp(),
40        }
41    }
42
43    pub fn control_state(&self) -> ControlState {
44        ControlState {
45            values: self.values.clone(),
46            channels: self.channels.clone(),
47            operator_right: self.operator_right.clone(),
48        }
49    }
50}
51
52pub fn preview_control_state_path(session_revision: u64) -> PathBuf {
53    let directory = std::env::temp_dir().join("skenion-runtime-preview");
54    let nonce = PREVIEW_CONTROL_STATE_COUNTER.fetch_add(1, Ordering::Relaxed);
55    directory.join(format!(
56        "preview-{}-{}-{}-control-state.json",
57        std::process::id(),
58        nonce,
59        session_revision
60    ))
61}
62
63pub fn read_preview_control_state_snapshot(
64    path: &Path,
65) -> Result<Option<PreviewControlStateSnapshot>, String> {
66    let Some(bytes) = read_preview_control_state_bytes(path).map_err(|error| error.to_string())?
67    else {
68        return Ok(None);
69    };
70
71    serde_json::from_slice(&bytes)
72        .map(Some)
73        .map_err(|error| error.to_string())
74}
75
76pub fn write_preview_control_state_snapshot(
77    path: &Path,
78    snapshot: &PreviewControlStateSnapshot,
79) -> Result<(), String> {
80    write_preview_control_state_snapshot_io(path, snapshot).map_err(|error| error.to_string())
81}
82
83fn read_preview_control_state_bytes(path: &Path) -> io::Result<Option<Vec<u8>>> {
84    if !path.exists() {
85        return Ok(None);
86    }
87
88    fs::read(path).map(Some)
89}
90
91fn write_preview_control_state_snapshot_io(
92    path: &Path,
93    snapshot: &PreviewControlStateSnapshot,
94) -> io::Result<()> {
95    path.parent()
96        .filter(|parent| !parent.as_os_str().is_empty())
97        .map(fs::create_dir_all)
98        .transpose()?;
99    let temp_path = path.with_extension("json.tmp");
100    let bytes =
101        serde_json::to_vec_pretty(snapshot).expect("preview control snapshot should serialize");
102    fs::write(&temp_path, bytes)?;
103    fs::rename(&temp_path, path)
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn preview_control_state_snapshot_round_trips() {
112        let mut control_state = ControlState::default();
113        control_state
114            .values
115            .insert("slider_1".to_owned(), ControlValue::float(0.75));
116        control_state.channels.insert(
117            "number.float:speed".to_owned(),
118            ControlMessage::from_value(ControlValue::float(0.75)),
119        );
120        control_state
121            .operator_right
122            .insert("mul_1".to_owned(), ControlValue::float(0.5));
123        let snapshot = PreviewControlStateSnapshot::new(12, 5, &control_state);
124        let bytes = serde_json::to_vec(&snapshot).expect("snapshot should serialize");
125        let decoded: PreviewControlStateSnapshot =
126            serde_json::from_slice(&bytes).expect("snapshot should deserialize");
127
128        assert_eq!(decoded.schema, PREVIEW_CONTROL_STATE_SCHEMA);
129        assert_eq!(decoded.schema_version, PREVIEW_CONTROL_STATE_SCHEMA_VERSION);
130        assert_eq!(decoded.session_revision, 12);
131        assert_eq!(decoded.control_revision, 5);
132        assert_eq!(decoded.control_state(), control_state);
133    }
134
135    #[test]
136    fn writes_and_reads_preview_control_state_atomically() {
137        let path = std::env::temp_dir().join(format!(
138            "skenion-preview-control-state-test-{}.json",
139            std::process::id()
140        ));
141        let mut control_state = ControlState::default();
142        control_state.channels.insert(
143            "boolean:enabled".to_owned(),
144            ControlMessage::from_value(ControlValue::bool(true)),
145        );
146        control_state
147            .operator_right
148            .insert("mul_1".to_owned(), ControlValue::float(0.5));
149        let snapshot = PreviewControlStateSnapshot::new(3, 2, &control_state);
150
151        write_preview_control_state_snapshot(&path, &snapshot).expect("snapshot should write");
152        let decoded = read_preview_control_state_snapshot(&path)
153            .expect("snapshot should read")
154            .expect("snapshot should exist");
155
156        assert_eq!(decoded, snapshot);
157        std::fs::remove_file(path).expect("snapshot should be removable");
158    }
159
160    #[test]
161    fn read_missing_preview_control_state_returns_none() {
162        let path = unique_temp_path("missing-control-state.json");
163
164        let snapshot =
165            read_preview_control_state_snapshot(&path).expect("missing snapshot should be ok");
166
167        assert_eq!(snapshot, None);
168    }
169
170    #[test]
171    fn read_invalid_preview_control_state_reports_error() {
172        let path = unique_temp_path("invalid-control-state.json");
173        fs::write(&path, b"{").expect("invalid snapshot should write");
174
175        let error =
176            read_preview_control_state_snapshot(&path).expect_err("invalid snapshot should fail");
177
178        assert!(error.contains("EOF") || error.contains("expected"));
179        fs::remove_file(path).expect("invalid snapshot should remove");
180    }
181
182    #[test]
183    fn read_preview_control_state_reports_read_errors() {
184        let directory = unique_temp_path("read-error");
185        fs::create_dir_all(&directory).expect("directory should create");
186
187        let error = read_preview_control_state_snapshot(&directory)
188            .expect_err("directory read should fail");
189
190        assert!(!error.is_empty());
191        fs::remove_dir_all(directory).expect("directory should remove");
192    }
193
194    #[test]
195    fn write_preview_control_state_reports_parent_create_error() {
196        let blocker = unique_temp_path("control-state-parent-blocker");
197        fs::write(&blocker, b"blocker").expect("blocker should write");
198        let snapshot = PreviewControlStateSnapshot::new(1, 1, &ControlState::default());
199
200        let error = write_preview_control_state_snapshot(&blocker.join("control.json"), &snapshot)
201            .expect_err("blocked parent should fail");
202
203        assert!(!error.is_empty());
204        fs::remove_file(blocker).expect("blocker should remove");
205    }
206
207    fn unique_temp_path(name: &str) -> PathBuf {
208        let nonce = PREVIEW_CONTROL_STATE_COUNTER.fetch_add(1, Ordering::Relaxed);
209        std::env::temp_dir().join(format!(
210            "skenion-preview-control-state-test-{}-{nonce}-{name}",
211            std::process::id()
212        ))
213    }
214}