phytrace_sdk/core/
sequence.rs1use std::fs;
19use std::io::Write;
20use std::path::{Path, PathBuf};
21use std::sync::Mutex;
22
23use crate::error::{PhyTraceError, PhyTraceResult};
24
25pub const DEFAULT_RESERVATION: u64 = 1000;
27
28const STATE_KEY: &str = "next_sequence";
29
30#[derive(Debug)]
31struct State {
32 next: u64,
33 reserved_until: u64,
35}
36
37#[derive(Debug)]
39pub struct SequenceCounter {
40 path: Option<PathBuf>,
41 reserve: u64,
42 state: Mutex<State>,
43}
44
45impl SequenceCounter {
46 pub fn in_memory() -> Self {
48 Self {
49 path: None,
50 reserve: DEFAULT_RESERVATION,
51 state: Mutex::new(State {
52 next: 1,
53 reserved_until: 1,
54 }),
55 }
56 }
57
58 pub fn persistent(path: impl Into<PathBuf>, reserve: u64) -> PhyTraceResult<Self> {
64 if reserve == 0 {
65 return Err(PhyTraceError::Provenance(
66 "sequence reservation must be at least 1".to_string(),
67 ));
68 }
69 let path = path.into();
70 let next = load(&path)?;
71 Ok(Self {
72 path: Some(path),
73 reserve,
74 state: Mutex::new(State {
75 next,
76 reserved_until: next,
77 }),
78 })
79 }
80
81 pub fn is_persistent(&self) -> bool {
83 self.path.is_some()
84 }
85
86 pub fn current(&self) -> PhyTraceResult<u64> {
88 Ok(self.lock()?.next.saturating_sub(1))
89 }
90
91 pub fn next(&self) -> PhyTraceResult<u64> {
93 let mut state = self.lock()?;
94 if let Some(path) = &self.path {
95 if state.next >= state.reserved_until {
96 let reserved_until = checked_add(state.next, self.reserve)?;
97 store(path, reserved_until)?;
98 state.reserved_until = reserved_until;
99 }
100 }
101 let value = state.next;
102 state.next = checked_add(value, 1)?;
103 Ok(value)
104 }
105
106 pub fn close(&self) -> PhyTraceResult<()> {
108 let mut state = self.lock()?;
109 if let Some(path) = &self.path {
110 store(path, state.next)?;
111 state.reserved_until = state.next;
112 }
113 Ok(())
114 }
115
116 fn lock(&self) -> PhyTraceResult<std::sync::MutexGuard<'_, State>> {
117 self.state
118 .lock()
119 .map_err(|e| PhyTraceError::Provenance(format!("sequence counter lock poisoned: {e}")))
120 }
121}
122
123fn checked_add(a: u64, b: u64) -> PhyTraceResult<u64> {
124 a.checked_add(b)
125 .ok_or_else(|| PhyTraceError::Provenance("sequence counter exhausted".to_string()))
126}
127
128fn load(path: &Path) -> PhyTraceResult<u64> {
129 let text = match fs::read_to_string(path) {
130 Ok(text) => text,
131 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(1),
132 Err(e) => {
133 return Err(PhyTraceError::Provenance(format!(
134 "Cannot read sequence state {}: {e}",
135 path.display()
136 )))
137 }
138 };
139 let corrupt = |detail: String| {
140 PhyTraceError::Provenance(format!(
141 "Corrupt sequence state {}: {detail}",
142 path.display()
143 ))
144 };
145 let value: serde_json::Value =
146 serde_json::from_str(&text).map_err(|e| corrupt(e.to_string()))?;
147 match value.get(STATE_KEY).and_then(serde_json::Value::as_u64) {
148 Some(next) if next >= 1 => Ok(next),
149 _ => Err(corrupt(format!(
150 "{STATE_KEY} missing or not a positive integer"
151 ))),
152 }
153}
154
155fn store(path: &Path, next_sequence: u64) -> PhyTraceResult<()> {
157 let dir = path.parent().filter(|d| !d.as_os_str().is_empty());
158 if let Some(dir) = dir {
159 fs::create_dir_all(dir)?;
160 }
161 let name = path
162 .file_name()
163 .map(|n| n.to_string_lossy().into_owned())
164 .unwrap_or_default();
165 let tmp = path.with_file_name(format!(".{name}.{}.tmp", std::process::id()));
166 let result = (|| -> std::io::Result<()> {
167 let mut file = fs::File::create(&tmp)?;
168 file.write_all(format!("{{\"{STATE_KEY}\": {next_sequence}}}").as_bytes())?;
169 file.sync_all()?;
170 fs::rename(&tmp, path)
171 })();
172 if let Err(e) = result {
173 if let Err(remove_err) = fs::remove_file(&tmp) {
175 tracing::debug!("could not remove {}: {remove_err}", tmp.display());
176 }
177 return Err(PhyTraceError::Provenance(format!(
178 "Cannot write sequence state {}: {e}",
179 path.display()
180 )));
181 }
182 if let Some(dir) = dir {
185 if let Ok(d) = fs::File::open(dir) {
186 if let Err(e) = d.sync_all() {
187 tracing::debug!("could not sync {}: {e}", dir.display());
188 }
189 }
190 }
191 Ok(())
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn in_memory_counter_starts_at_one() {
200 let counter = SequenceCounter::in_memory();
201 assert!(!counter.is_persistent());
202 assert_eq!(counter.next().unwrap(), 1);
203 assert_eq!(counter.next().unwrap(), 2);
204 assert_eq!(counter.current().unwrap(), 2);
205 }
206
207 #[test]
208 fn clean_restart_continues_without_gap() {
209 let dir = tempfile::tempdir().unwrap();
210 let path = dir.path().join("seq.json");
211 let counter = SequenceCounter::persistent(&path, DEFAULT_RESERVATION).unwrap();
212 for expected in 1..=5 {
213 assert_eq!(counter.next().unwrap(), expected);
214 }
215 counter.close().unwrap();
216
217 let restarted = SequenceCounter::persistent(&path, DEFAULT_RESERVATION).unwrap();
218 assert_eq!(restarted.next().unwrap(), 6);
219 }
220
221 #[test]
222 fn crash_never_reuses_a_number() {
223 let dir = tempfile::tempdir().unwrap();
224 let path = dir.path().join("seq.json");
225 let counter = SequenceCounter::persistent(&path, 10).unwrap();
226 let mut last = 0;
227 for _ in 0..13 {
228 last = counter.next().unwrap();
229 }
230 drop(counter);
232 let first = SequenceCounter::persistent(&path, 10)
233 .unwrap()
234 .next()
235 .unwrap();
236 assert!(first > last && first <= last + 10, "{first} after {last}");
237 }
238
239 #[test]
240 fn reads_the_python_sdk_state_format() {
241 let dir = tempfile::tempdir().unwrap();
242 let path = dir.path().join("seq.json");
243 fs::write(&path, r#"{"next_sequence": 42}"#).unwrap();
244 let counter = SequenceCounter::persistent(&path, DEFAULT_RESERVATION).unwrap();
245 assert_eq!(counter.next().unwrap(), 42);
246 }
247
248 #[test]
249 fn creates_missing_directories() {
250 let dir = tempfile::tempdir().unwrap();
251 let path = dir.path().join("a").join("b").join("seq.json");
252 SequenceCounter::persistent(&path, DEFAULT_RESERVATION)
253 .unwrap()
254 .next()
255 .unwrap();
256 assert!(path.exists());
257 }
258
259 #[test]
260 fn corrupt_state_refuses_to_start() {
261 let dir = tempfile::tempdir().unwrap();
262 let path = dir.path().join("seq.json");
263 for content in [
264 "",
265 "not json",
266 "[]",
267 r#"{"other": 3}"#,
268 r#"{"next_sequence": 0}"#,
269 r#"{"next_sequence": "5"}"#,
270 r#"{"next_sequence": -1}"#,
271 ] {
272 fs::write(&path, content).unwrap();
273 let err = SequenceCounter::persistent(&path, DEFAULT_RESERVATION).unwrap_err();
274 assert!(err.to_string().contains("Corrupt"), "{content}: {err}");
275 }
276 }
277}