Skip to main content

optimization_job_api/
storage.rs

1//! Durable primitives extracted from route_search and route_archive (3ef2673).
2use serde::de::DeserializeOwned;
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use std::fs::{self, File, OpenOptions};
6use std::io::{self, BufRead, BufReader, BufWriter, Write};
7use std::path::{Path, PathBuf};
8static TEMP_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
9/// Appends `value` as one JSON line and syncs the file. A torn final line is
10/// ended first, so the new record never joins it.
11///
12/// # Errors
13///
14/// Returns an I/O or serialization error.
15pub fn append_jsonl<T: Serialize>(path: &Path, value: &T) -> Result<(), io::Error> {
16    let mut file = OpenOptions::new()
17        .create(true)
18        .read(true)
19        .append(true)
20        .open(path)?;
21    seal_tail(&mut file)?;
22    let mut writer = BufWriter::new(file);
23    serde_json::to_writer(&mut writer, value)?;
24    writer.write_all(b"\n")?;
25    writer.flush()?;
26    writer.get_ref().sync_data()?;
27    Ok(())
28}
29
30/// Ends a file whose last line lacks its newline (an append that was cut
31/// short) the way readers see it: a valid JSON tail is a record and gets its
32/// newline, anything else is dropped. Appending after an unsealed tail would
33/// join it with the next record into one invalid line, making every earlier
34/// record unreadable.
35fn seal_tail(file: &mut File) -> io::Result<()> {
36    use std::io::{Read, Seek, SeekFrom};
37    let len = file.metadata()?.len();
38    if len == 0 {
39        return Ok(());
40    }
41    let mut last = [0u8];
42    file.seek(SeekFrom::Start(len - 1))?;
43    file.read_exact(&mut last)?;
44    if last[0] == b'\n' {
45        return Ok(());
46    }
47    let mut data = Vec::new();
48    file.seek(SeekFrom::Start(0))?;
49    file.read_to_end(&mut data)?;
50    let start = data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
51    if serde_json::from_slice::<serde_json::Value>(&data[start..]).is_ok() {
52        file.write_all(b"\n")?;
53    } else {
54        file.set_len(start as u64)?;
55    }
56    file.sync_data()
57}
58
59/// Reads JSONL while ignoring only an incomplete final record.
60///
61/// A malformed newline-terminated record or corruption before the final line
62/// remains fatal.
63///
64/// # Errors
65///
66/// Returns an error for I/O or non-final JSON corruption.
67pub fn read_jsonl_resilient<T: DeserializeOwned>(path: &Path) -> Result<Vec<T>, io::Error> {
68    let file = File::open(path)?;
69    let mut reader = BufReader::new(file);
70    let mut records = Vec::new();
71    let mut line = Vec::new();
72    loop {
73        line.clear();
74        let bytes = reader.read_until(b'\n', &mut line)?;
75        if bytes == 0 {
76            break;
77        }
78        let terminated = line.last() == Some(&b'\n');
79        if terminated {
80            line.pop();
81            if line.last() == Some(&b'\r') {
82                line.pop();
83            }
84        }
85        if line.iter().all(u8::is_ascii_whitespace) {
86            continue;
87        }
88        match serde_json::from_slice(&line) {
89            Ok(record) => records.push(record),
90            Err(_) if !terminated => break,
91            Err(error) => return Err(io::Error::other(error)),
92        }
93    }
94    Ok(records)
95}
96
97/// Writes a JSON snapshot to a sibling temporary file and atomically renames
98/// it over the target.
99///
100/// # Errors
101///
102/// Returns an I/O or serialization error.
103pub fn write_atomic_json<T: Serialize>(path: &Path, value: &T) -> Result<(), io::Error> {
104    let parent = path.parent().unwrap_or_else(|| Path::new("."));
105    fs::create_dir_all(parent)?;
106    let filename = path
107        .file_name()
108        .and_then(|name| name.to_str())
109        .ok_or_else(|| io::Error::other("snapshot path has no file name".to_owned()))?;
110    let temporary = temporary_path(parent, filename);
111    let result = (|| {
112        let file = OpenOptions::new()
113            .create_new(true)
114            .write(true)
115            .open(&temporary)?;
116        let mut writer = BufWriter::new(file);
117        serde_json::to_writer_pretty(&mut writer, value)?;
118        writer.write_all(b"\n")?;
119        writer.flush()?;
120        writer.get_ref().sync_all()?;
121        fs::rename(&temporary, path)?;
122        File::open(parent)?.sync_all()?;
123        Ok::<(), io::Error>(())
124    })();
125    if result.is_err() {
126        let _ = fs::remove_file(&temporary);
127    }
128    result
129}
130
131fn temporary_path(parent: &Path, filename: &str) -> PathBuf {
132    parent.join(format!(
133        ".{filename}.{}.{}.tmp",
134        std::process::id(),
135        TEMP_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
136    ))
137}
138
139/// Route archive v2 framing, kept byte compatible.
140#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct Envelope {
143    /// The version of the record format in `payload_json`.
144    pub schema_version: u32,
145    /// The lowercase hexadecimal SHA-256 of the `payload_json` bytes.
146    pub checksum: String,
147    /// The record as JSON text.
148    pub payload_json: String,
149}
150/// The lowercase hexadecimal SHA-256 of `bytes`.
151pub fn digest(bytes: &[u8]) -> String {
152    format!("{:x}", Sha256::digest(bytes))
153}
154/// Appends `value` as a checked record of `version`: an [`Envelope`] line
155/// with the checksum of its JSON, written by [`append_jsonl`].
156pub fn append_checked<T: Serialize>(path: &Path, version: u32, value: &T) -> io::Result<()> {
157    let payload_json = serde_json::to_string(value)?;
158    append_jsonl(
159        path,
160        &Envelope {
161            schema_version: version,
162            checksum: digest(payload_json.as_bytes()),
163            payload_json,
164        },
165    )
166}
167/// The checked records of `version` in `path`. An incomplete final line is
168/// ignored; a wrong version, a wrong checksum or earlier corruption is an
169/// error.
170pub fn read_checked<T: DeserializeOwned>(path: &Path, version: u32) -> io::Result<Vec<T>> {
171    let lines: Vec<Envelope> = read_jsonl_resilient(path)?;
172    lines
173        .into_iter()
174        .map(|line| {
175            if line.schema_version != version
176                || line.checksum != digest(line.payload_json.as_bytes())
177            {
178                return Err(io::Error::other("checksum or schema mismatch"));
179            }
180            Ok(serde_json::from_str(&line.payload_json)?)
181        })
182        .collect()
183}
184/// Repair only after verified replay, under exclusive job ownership.
185/// A valid unterminated record is retained and receives its newline.
186pub fn repair_tail<T: DeserializeOwned>(path: &Path, version: u32) -> io::Result<Vec<T>> {
187    let records = read_checked(path, version)?;
188    let data = fs::read(path)?;
189    if !data.is_empty() && !data.ends_with(b"\n") {
190        let start = data.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
191        let mut file = OpenOptions::new().append(true).open(path)?;
192        if serde_json::from_slice::<Envelope>(&data[start..]).is_ok() {
193            file.write_all(b"\n")?;
194        } else {
195            file.set_len(start as u64)?;
196        }
197        file.sync_all()?;
198    }
199    Ok(records)
200}
201/// Liveness probe for a lock that a process holds for its whole lifetime.
202///
203/// The kernel releases `flock` locks when their holder exits, however it
204/// exits, so a free lock proves the holder is gone. Returns `Ok(true)` when
205/// the lock is free or the file does not exist, `Ok(false)` when another open
206/// file description holds it. The probe takes the lock only momentarily.
207///
208/// # Errors
209///
210/// Returns an error when the lock state cannot be determined.
211pub fn lock_is_free(path: &Path) -> io::Result<bool> {
212    let file = match OpenOptions::new().read(true).write(true).open(path) {
213        Ok(file) => file,
214        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(true),
215        Err(e) => return Err(e),
216    };
217    match fs2::FileExt::try_lock_exclusive(&file) {
218        Ok(()) => Ok(true),
219        Err(e) if e.raw_os_error() == fs2::lock_contended_error().raw_os_error() => Ok(false),
220        Err(e) => Err(e),
221    }
222}
223/// Stable inode lock. Never unlink it; atomic replacement is for data only.
224pub fn lock(path: &Path) -> io::Result<File> {
225    let file = OpenOptions::new()
226        .create(true)
227        .truncate(false)
228        .read(true)
229        .write(true)
230        .open(path)?;
231    fs2::FileExt::lock_exclusive(&file)?;
232    Ok(file)
233}