Skip to main content

pnc_engine/
persist.rs

1use crate::value::Value;
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::PathBuf;
5
6#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
7pub struct Settings {
8    #[serde(default = "default_stack_soft_cap")]
9    pub stack_soft_cap: usize,
10    #[serde(default = "default_rational_digit_cap")]
11    pub rational_digit_cap: usize,
12    #[serde(default = "default_undo_depth")]
13    pub undo_depth: usize,
14}
15
16impl Default for Settings {
17    fn default() -> Self {
18        Self {
19            stack_soft_cap: default_stack_soft_cap(),
20            rational_digit_cap: default_rational_digit_cap(),
21            undo_depth: default_undo_depth(),
22        }
23    }
24}
25
26fn default_stack_soft_cap() -> usize {
27    10_000
28}
29
30fn default_rational_digit_cap() -> usize {
31    10_000
32}
33
34fn default_undo_depth() -> usize {
35    10
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize)]
39pub struct PersistedState {
40    #[serde(default = "default_schema_version")]
41    pub schema_version: u32,
42    #[serde(default, deserialize_with = "deserialize_stack")]
43    pub stack: Vec<Value>,
44    #[serde(default)]
45    pub settings: Settings,
46}
47
48fn default_schema_version() -> u32 {
49    1
50}
51
52impl Default for PersistedState {
53    fn default() -> Self {
54        Self {
55            schema_version: 1,
56            stack: Vec::new(),
57            settings: Settings::default(),
58        }
59    }
60}
61
62impl<'de> Deserialize<'de> for PersistedState {
63    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
64    where
65        D: serde::Deserializer<'de>,
66    {
67        #[derive(Deserialize)]
68        struct Raw {
69            #[serde(default = "default_schema_version")]
70            schema_version: u32,
71            #[serde(default)]
72            stack: Vec<toml::Value>,
73            #[serde(default)]
74            settings: Settings,
75        }
76
77        let raw = Raw::deserialize(deserializer)?;
78        let mut stack = Vec::new();
79        let mut skipped = 0usize;
80        for item in raw.stack {
81            use serde::de::IntoDeserializer;
82            match Value::deserialize(item.into_deserializer()) {
83                Ok(v) => stack.push(v),
84                Err(_) => {
85                    skipped += 1;
86                }
87            }
88        }
89        if skipped > 0 {
90            eprintln!(
91                "warning: skipped {} persisted value(s) with unknown kind",
92                skipped
93            );
94        }
95        Ok(PersistedState {
96            schema_version: raw.schema_version,
97            stack,
98            settings: raw.settings,
99        })
100    }
101}
102
103pub fn state_path() -> PathBuf {
104    directories::ProjectDirs::from("", "", "pnc")
105        .map(|p| p.data_dir().join("state.toml"))
106        .unwrap_or_else(|| PathBuf::from("state.toml"))
107}
108
109pub fn load() -> Result<PersistedState, crate::error::PncError> {
110    load_from(&state_path())
111}
112
113pub fn load_from(path: &std::path::Path) -> Result<PersistedState, crate::error::PncError> {
114    if !path.exists() {
115        return Ok(PersistedState::default());
116    }
117    let text = fs::read_to_string(path)?;
118    let state: PersistedState =
119        toml::from_str(&text).map_err(|e| crate::error::PncError::Parse(e.to_string()))?;
120    if state.schema_version > 1 {
121        return Err(crate::error::PncError::UnsupportedSchemaVersion);
122    }
123    Ok(state)
124}
125
126pub fn save(state: &PersistedState) -> Result<(), crate::error::PncError> {
127    save_to(state, &state_path())
128}
129
130pub fn lock_path() -> std::path::PathBuf {
131    state_path().with_file_name("pnc.lock")
132}
133
134pub fn acquire_lock() -> Result<std::fs::File, crate::error::PncError> {
135    let path = lock_path();
136    if let Some(parent) = path.parent() {
137        fs::create_dir_all(parent)?;
138    }
139    let file = fs::OpenOptions::new()
140        .create(true)
141        .write(true)
142        .truncate(false)
143        .open(&path)?;
144    use fs2::FileExt;
145    file.try_lock_exclusive().map_err(|_| {
146        crate::error::PncError::Io(std::io::Error::other("another pnc instance is running"))
147    })?;
148    Ok(file)
149}
150
151pub fn save_to(
152    state: &PersistedState,
153    path: &std::path::Path,
154) -> Result<(), crate::error::PncError> {
155    if let Some(parent) = path.parent() {
156        fs::create_dir_all(parent)?;
157    }
158    use std::io::Write;
159
160    let text =
161        toml::to_string_pretty(state).map_err(|e| crate::error::PncError::Parse(e.to_string()))?;
162    if path.exists() {
163        let backup = path.with_extension("bak");
164        let _ = fs::copy(path, &backup);
165    }
166    let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
167    fs::create_dir_all(parent)?;
168
169    // Retry the write once on failure before reporting an unrecoverable error.
170    let mut last_err = None;
171    for _ in 0..2 {
172        let mut tmp = match tempfile::NamedTempFile::new_in(parent) {
173            Ok(t) => t,
174            Err(e) => {
175                last_err = Some(crate::error::PncError::Io(e));
176                continue;
177            }
178        };
179        if tmp.write_all(text.as_bytes()).is_err()
180            || tmp.flush().is_err()
181            || tmp.as_file().sync_all().is_err()
182        {
183            last_err = Some(crate::error::PncError::Io(std::io::Error::other(
184                "failed to write state",
185            )));
186            continue;
187        }
188        match tmp.persist(path) {
189            Ok(_) => {
190                last_err = None;
191                break;
192            }
193            Err(e) => {
194                last_err = Some(crate::error::PncError::Io(e.error));
195                continue;
196            }
197        }
198    }
199    if let Some(e) = last_err {
200        return Err(e);
201    }
202    // Best-effort fsync of the containing directory.
203    if let Some(parent) = path.parent() {
204        if let Ok(dir) = fs::File::open(parent) {
205            let _ = dir.sync_all();
206        }
207    }
208    Ok(())
209}