Skip to main content

taskfast_cli/
state_store.rs

1// SPDX-License-Identifier: MIT
2//! Unified local state and secret persistence for `.taskfast/` directory.
3//!
4//! Encapsulates path resolution, directory permissions (0700 on Unix for `.taskfast`),
5//! automatic `.gitignore` provisioning, atomic file writes with 0600 permissions from
6//! creation, and an ephemeral adapter for test execution with `/dev/null`.
7
8use std::collections::VecDeque;
9use std::fs;
10use std::io::{self, Write};
11use std::path::{Path, PathBuf};
12
13use crate::config::DEFAULT_CONFIG_PATH;
14
15/// Typed assets managed within the local `.taskfast/` state directory.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum StateAsset {
18    /// CLI configuration (`config.json`).
19    Config,
20    /// Event stream pagination cursor (`events.cursor`).
21    EventsCursor,
22    /// Deduplication cache for received event IDs (`events.seen`).
23    EventsSeen,
24    /// Pending submission fee retry transaction hashes (`fee_retries.json`).
25    FeeRetries,
26}
27
28impl StateAsset {
29    /// Return the standard file name for this state asset.
30    pub const fn filename(self) -> &'static str {
31        match self {
32            Self::Config => "config.json",
33            Self::EventsCursor => "events.cursor",
34            Self::EventsSeen => "events.seen",
35            Self::FeeRetries => "fee_retries.json",
36        }
37    }
38}
39
40/// Unified state store for `.taskfast/` local files.
41#[derive(Debug, Clone)]
42pub struct StateStore {
43    root_dir: Option<PathBuf>,
44}
45
46impl StateStore {
47    /// Construct a store from a config path.
48    ///
49    /// When `config_path` is `/dev/null` or within `/dev/`, creates an ephemeral
50    /// store that never touches the filesystem. Otherwise, creates a disk-backed
51    /// store rooted at the parent directory of `config_path`.
52    pub fn from_config_path(config_path: &Path) -> Self {
53        if config_path == Path::new("/dev/null") || config_path.parent() == Some(Path::new("/dev"))
54        {
55            return Self::ephemeral();
56        }
57
58        let root_dir = config_path
59            .parent()
60            .filter(|p| !p.as_os_str().is_empty())
61            .unwrap_or_else(|| Path::new("."))
62            .to_path_buf();
63
64        Self {
65            root_dir: Some(root_dir),
66        }
67    }
68
69    /// Construct an ephemeral store with no on-disk persistence.
70    pub fn ephemeral() -> Self {
71        Self { root_dir: None }
72    }
73
74    /// Return true if this store is ephemeral (no on-disk persistence).
75    pub fn is_ephemeral(&self) -> bool {
76        self.root_dir.is_none()
77    }
78
79    /// Return the root directory if disk-backed.
80    pub fn root_dir(&self) -> Option<&Path> {
81        self.root_dir.as_deref()
82    }
83
84    /// Return the resolved path on disk for a state asset, or None if ephemeral.
85    pub fn path_for(&self, asset: StateAsset) -> Option<PathBuf> {
86        self.root_dir.as_ref().map(|dir| dir.join(asset.filename()))
87    }
88
89    /// Ensure the root directory exists with 0700 permissions and automatic `.gitignore`.
90    pub fn ensure_dir(&self) -> io::Result<()> {
91        if let Some(dir) = &self.root_dir {
92            Self::ensure_dir_path(dir)?;
93        }
94        Ok(())
95    }
96
97    /// Ensure a directory exists. When the directory is named `.taskfast`, tightens
98    /// permissions to 0700 on Unix and provisions `.gitignore`.
99    pub fn ensure_dir_path(dir: &Path) -> io::Result<()> {
100        if dir.as_os_str().is_empty() || dir == Path::new(".") {
101            return Ok(());
102        }
103        fs::create_dir_all(dir)?;
104
105        let is_taskfast_dir = Path::new(DEFAULT_CONFIG_PATH)
106            .parent()
107            .and_then(Path::file_name)
108            .is_some_and(|expected| dir.file_name() == Some(expected));
109
110        if is_taskfast_dir {
111            #[cfg(unix)]
112            {
113                use std::os::unix::fs::PermissionsExt;
114                fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
115            }
116            ensure_dir_gitignore(dir);
117        }
118        Ok(())
119    }
120
121    /// Atomic file write: writes to sibling `.tmp`, 0600 on Unix from creation, flushes, renames.
122    ///
123    /// Cleans up the temporary file if write or rename fails. Does not chmod the parent directory.
124    pub fn atomic_write_file(path: &Path, contents: &[u8]) -> io::Result<()> {
125        if let Some(parent) = path.parent() {
126            if !parent.as_os_str().is_empty() {
127                fs::create_dir_all(parent)?;
128            }
129        }
130
131        let tmp_name = format!(
132            "{}.tmp.{}",
133            path.file_name().and_then(|n| n.to_str()).unwrap_or("file"),
134            uuid::Uuid::new_v4().simple()
135        );
136        let tmp = path.with_file_name(tmp_name);
137
138        let write_res = (|| -> io::Result<()> {
139            #[cfg(unix)]
140            let create = {
141                use std::os::unix::fs::OpenOptionsExt;
142                fs::OpenOptions::new()
143                    .write(true)
144                    .create(true)
145                    .truncate(true)
146                    .mode(0o600)
147                    .open(&tmp)
148            };
149            #[cfg(not(unix))]
150            let create = fs::File::create(&tmp);
151
152            let mut f = create?;
153            f.write_all(contents)?;
154            f.flush()?;
155            drop(f);
156            fs::rename(&tmp, path)?;
157            Ok(())
158        })();
159
160        if write_res.is_err() {
161            let _ = fs::remove_file(&tmp);
162        }
163        write_res
164    }
165
166    /// Read the pagination cursor if present and non-empty.
167    pub fn read_cursor(&self) -> Option<String> {
168        let path = self.path_for(StateAsset::EventsCursor)?;
169        let raw = fs::read_to_string(path).ok()?;
170        let trimmed = raw.trim().to_string();
171        if trimmed.is_empty() {
172            None
173        } else {
174            Some(trimmed)
175        }
176    }
177
178    /// Write pagination cursor. A `None` cursor leaves the existing cursor untouched.
179    pub fn write_cursor(&self, next_cursor: Option<&str>) -> io::Result<()> {
180        let Some(payload) = next_cursor else {
181            return Ok(());
182        };
183        let Some(path) = self.path_for(StateAsset::EventsCursor) else {
184            return Ok(());
185        };
186        Self::atomic_write_file(&path, payload.as_bytes())
187    }
188
189    /// Load seen event IDs from `events.seen`.
190    pub fn load_seen_lines(&self) -> io::Result<Vec<String>> {
191        let Some(path) = self.path_for(StateAsset::EventsSeen) else {
192            return Ok(Vec::new());
193        };
194        match fs::read_to_string(path) {
195            Ok(raw) => Ok(raw
196                .lines()
197                .filter(|l| !l.is_empty())
198                .map(str::to_string)
199                .collect()),
200            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
201            Err(e) => Err(e),
202        }
203    }
204
205    /// Append a single seen ID to `events.seen`.
206    pub fn append_seen_line(&self, id: &str) -> io::Result<()> {
207        let Some(path) = self.path_for(StateAsset::EventsSeen) else {
208            return Ok(());
209        };
210
211        let open_append = || {
212            #[cfg(unix)]
213            {
214                use std::os::unix::fs::OpenOptionsExt;
215                fs::OpenOptions::new()
216                    .create(true)
217                    .append(true)
218                    .mode(0o600)
219                    .open(&path)
220            }
221            #[cfg(not(unix))]
222            {
223                fs::OpenOptions::new().create(true).append(true).open(&path)
224            }
225        };
226
227        let mut f = match open_append() {
228            Ok(file) => file,
229            Err(e) if e.kind() == io::ErrorKind::NotFound => {
230                self.ensure_dir()?;
231                open_append()?
232            }
233            Err(e) => return Err(e),
234        };
235
236        writeln!(f, "{id}")?;
237        Ok(())
238    }
239
240    /// Rewrite `events.seen` with the given IDs, separated by newlines.
241    pub fn rewrite_seen_lines(&self, ids: &VecDeque<String>) -> io::Result<()> {
242        let Some(path) = self.path_for(StateAsset::EventsSeen) else {
243            return Ok(());
244        };
245        let mut body = String::new();
246        for id in ids {
247            body.push_str(id);
248            body.push('\n');
249        }
250        Self::atomic_write_file(&path, body.as_bytes())
251    }
252
253    /// Read any pending fee retry transaction hash for `task_id`.
254    pub fn get_pending_fee_retry(&self, task_id: &uuid::Uuid) -> Option<String> {
255        let path = self.path_for(StateAsset::FeeRetries)?;
256        let raw = fs::read_to_string(path).ok()?;
257        let map: std::collections::HashMap<String, String> = serde_json::from_str(&raw).ok()?;
258        map.get(&task_id.to_string()).cloned()
259    }
260
261    /// Record a pending fee retry transaction hash for `task_id`.
262    pub fn record_pending_fee_retry(&self, task_id: &uuid::Uuid, tx_hash: &str) -> io::Result<()> {
263        let Some(path) = self.path_for(StateAsset::FeeRetries) else {
264            return Ok(());
265        };
266        let mut map: std::collections::HashMap<String, String> = if path.exists() {
267            fs::read_to_string(&path)
268                .ok()
269                .and_then(|raw| serde_json::from_str(&raw).ok())
270                .unwrap_or_default()
271        } else {
272            std::collections::HashMap::new()
273        };
274        map.insert(task_id.to_string(), tx_hash.to_string());
275        let body = serde_json::to_vec_pretty(&map)
276            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
277        Self::atomic_write_file(&path, &body)
278    }
279
280    /// Clear any pending fee retry transaction hash for `task_id`.
281    pub fn clear_pending_fee_retry(&self, task_id: &uuid::Uuid) -> io::Result<()> {
282        let Some(path) = self.path_for(StateAsset::FeeRetries) else {
283            return Ok(());
284        };
285        if !path.exists() {
286            return Ok(());
287        }
288        let raw = fs::read_to_string(&path)?;
289        let mut map: std::collections::HashMap<String, String> =
290            serde_json::from_str(&raw).unwrap_or_default();
291        if map.remove(&task_id.to_string()).is_some() {
292            let body = serde_json::to_vec_pretty(&map)
293                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
294            Self::atomic_write_file(&path, &body)?;
295        }
296        Ok(())
297    }
298}
299
300fn ensure_dir_gitignore(dir: &Path) {
301    let gitignore = dir.join(".gitignore");
302    match fs::OpenOptions::new()
303        .write(true)
304        .create_new(true)
305        .open(&gitignore)
306    {
307        Ok(mut f) => {
308            if let Err(e) = f.write_all(b"*\n") {
309                tracing::warn!(path = %gitignore.display(), error = %e, "could not write .taskfast/.gitignore");
310            }
311        }
312        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
313        Err(e) => {
314            tracing::warn!(path = %gitignore.display(), error = %e, "could not create .taskfast/.gitignore");
315        }
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use tempfile::TempDir;
323
324    #[test]
325    fn ephemeral_mode_skips_disk() {
326        let store = StateStore::from_config_path(Path::new("/dev/null"));
327        assert!(store.is_ephemeral());
328        assert_eq!(store.root_dir(), None);
329        assert_eq!(store.path_for(StateAsset::Config), None);
330
331        assert!(store.write_cursor(Some("cur1")).is_ok());
332        assert_eq!(store.read_cursor(), None);
333    }
334
335    #[test]
336    fn disk_mode_creates_0700_dir_and_gitignore() {
337        let tmp = TempDir::new().unwrap();
338        let config_path = tmp.path().join(".taskfast").join("config.json");
339        let store = StateStore::from_config_path(&config_path);
340        assert!(!store.is_ephemeral());
341
342        store.ensure_dir().unwrap();
343        let root = store.root_dir().unwrap();
344        assert!(root.exists());
345
346        #[cfg(unix)]
347        {
348            use std::os::unix::fs::PermissionsExt;
349            let mode = fs::metadata(root).unwrap().permissions().mode() & 0o777;
350            assert_eq!(mode, 0o700, "directory mode must be 0700");
351        }
352
353        let gitignore = root.join(".gitignore");
354        assert!(
355            gitignore.exists(),
356            ".gitignore must be created for .taskfast"
357        );
358        let content = fs::read_to_string(gitignore).unwrap();
359        assert_eq!(content, "*\n");
360    }
361
362    #[test]
363    fn atomic_write_file_sets_0600_from_creation_without_chmod_parent() {
364        let tmp = TempDir::new().unwrap();
365        let parent = tmp.path().join("sub");
366        let target = parent.join("secret.file");
367        StateStore::atomic_write_file(&target, b"secret-data").unwrap();
368
369        assert_eq!(fs::read(&target).unwrap(), b"secret-data");
370        #[cfg(unix)]
371        {
372            use std::os::unix::fs::PermissionsExt;
373            let file_mode = fs::metadata(&target).unwrap().permissions().mode() & 0o777;
374            assert_eq!(file_mode, 0o600, "file mode must be 0600");
375
376            // Parent directory must not be chmod'd to 0700 when writing arbitrary file
377            let parent_mode = fs::metadata(&parent).unwrap().permissions().mode() & 0o777;
378            assert_ne!(parent_mode, 0o700, "parent directory must not be 0700");
379        }
380    }
381
382    #[test]
383    fn cursor_and_seen_roundtrip() {
384        let tmp = TempDir::new().unwrap();
385        let config_path = tmp.path().join("config.json");
386        let store = StateStore::from_config_path(&config_path);
387
388        assert_eq!(store.read_cursor(), None);
389        store.write_cursor(Some("c1")).unwrap();
390        assert_eq!(store.read_cursor(), Some("c1".into()));
391        store.write_cursor(None).unwrap();
392        assert_eq!(store.read_cursor(), Some("c1".into()));
393
394        assert!(store.load_seen_lines().unwrap().is_empty());
395        store.append_seen_line("evt_1").unwrap();
396        store.append_seen_line("evt_2").unwrap();
397        assert_eq!(store.load_seen_lines().unwrap(), vec!["evt_1", "evt_2"]);
398
399        let mut queue = std::collections::VecDeque::new();
400        queue.push_back("evt_3".to_string());
401        store.rewrite_seen_lines(&queue).unwrap();
402        assert_eq!(store.load_seen_lines().unwrap(), vec!["evt_3"]);
403    }
404
405    #[test]
406    fn pending_fee_retry_roundtrip() {
407        let tmp = TempDir::new().unwrap();
408        let config_path = tmp.path().join("config.json");
409        let store = StateStore::from_config_path(&config_path);
410        let task_id = uuid::Uuid::new_v4();
411
412        assert_eq!(store.get_pending_fee_retry(&task_id), None);
413        store
414            .record_pending_fee_retry(&task_id, "0xabcdef123456")
415            .unwrap();
416        assert_eq!(
417            store.get_pending_fee_retry(&task_id),
418            Some("0xabcdef123456".into())
419        );
420
421        store.clear_pending_fee_retry(&task_id).unwrap();
422        assert_eq!(store.get_pending_fee_retry(&task_id), None);
423    }
424}