Skip to main content

apimock_config/
workspace.rs

1//! The editable workspace: loaded TOML + stable node IDs + edit API.
2//!
3//! # Role in the design
4//!
5//! A GUI never touches `Config` or `RuleSet` directly. It holds a
6//! `Workspace` value, calls `snapshot()` to get a read-only view for
7//! rendering, and `apply(EditCommand)` to mutate. Later, `save()`
8//! writes changes back to disk.
9//!
10//! # Module layout
11//!
12//! `Workspace` is large enough that its impl is split across several
13//! sibling modules under `workspace/`:
14//!
15//! - `id_index` — `NodeAddress` + `IdIndex` machinery
16//! - `snapshot` — `Workspace::snapshot()` and per-file view builders
17//! - `edit` — `Workspace::apply()` and the eight `EditCommand`
18//!   handlers (with the `id_shift` and `payload` submodules)
19//! - `validate` — `Workspace::validate()` and the per-node walker
20//! - `save` — `Workspace::save()`, `has_unsaved_changes()`, and
21//!   the atomic-write helper
22//! - `diff` — `compute_diff_summary()` and per-rule comparison
23//! - `path_helpers` — small filesystem utilities reused by the
24//!   submodules above
25//!
26//! Each submodule is private — the public surface remains
27//! `apimock_config::Workspace` and the methods it exposes.
28//!
29//! This file holds the `Workspace` struct itself, the `load` /
30//! `seed_ids` lifecycle, plus the small accessor methods that don't
31//! belong in any of the larger groupings.
32//!
33//! # IDs
34//!
35//! Every editable node gets a v4 UUID at load time. IDs are stable
36//! across `apply()` calls within one `Workspace` instance, so GUI
37//! selection survives edits that reorder or rename surrounding nodes.
38//! IDs are *not* stable across fresh `load()` calls — a reload
39//! regenerates the table, which matches the spec §10 "Workspace は
40//! メモリ上に独立インスタンスを持つ" stance.
41
42use std::{
43    collections::HashMap,
44    path::{Path, PathBuf},
45};
46
47use crate::{
48    Config,
49    error::{ConfigError, WorkspaceError},
50    view::Diagnostic,
51};
52
53mod diff;
54mod edit;
55mod id_index;
56mod path_helpers;
57mod save;
58mod snapshot;
59mod validate;
60
61#[cfg(test)]
62mod tests;
63
64use id_index::{IdIndex, NodeAddress};
65use path_helpers::resolve_root;
66
67/// Editable view of an apimock workspace.
68///
69/// # Internal layout
70///
71/// The `Workspace` holds the loaded TOML model (as a `Config`) plus
72/// two index maps:
73///
74/// - `id_to_address`: NodeId → where the node lives in `config`.
75/// - `address_to_id`: reverse — used when rebuilding snapshots.
76///
77/// On every `apply()` that could move nodes around (Add / Remove /
78/// Move), these tables are partially rebuilt. Reloading the config
79/// discards them and re-seeds with fresh IDs.
80pub struct Workspace {
81    /// Path this workspace was loaded from.
82    pub(super) root_path: PathBuf,
83    /// Loaded TOML model.
84    pub(super) config: Config,
85    /// ID index.
86    pub(super) ids: IdIndex,
87    /// Workspace-scope diagnostics.
88    pub(super) diagnostics: Vec<Diagnostic>,
89    /// Rendered baseline for save/diff detection.
90    pub(super) baseline_files: HashMap<PathBuf, String>,
91    /// Modification-time + size snapshot of every loaded file,
92    /// captured at `load()` and refreshed after each `save()`.
93    /// Used by `has_external_changes()` and `sync_from_disk()`.
94    pub(super) file_metas: HashMap<PathBuf, FileMeta>,
95}
96
97/// Snapshot of one file's modification-time and size.
98#[derive(Clone, Debug)]
99pub(super) struct FileMeta {
100    pub modified: std::time::SystemTime,
101    pub len: u64,
102}
103
104impl Workspace {
105    /// Load a workspace rooted at the given `apimock.toml`-like path.
106    ///
107    /// Accepts either a direct path to the config file or the
108    /// directory containing one; a missing file-path is searched for
109    /// as `apimock.toml` inside `root`. Mirrors the CLI's existing
110    /// resolution rules.
111    pub fn load(root: PathBuf) -> Result<Self, WorkspaceError> {
112        let resolved = resolve_root(&root)?;
113
114        // Re-use `Config::new` so rule-set loading + validation go
115        // through the same path as the running server. This is
116        // important — the spec's "GUI doesn't break running server
117        // behaviour" invariant (§13) is easiest to guarantee if both
118        // paths share the same loader.
119        let config_path_string = resolved.to_string_lossy().into_owned();
120        let config = Config::new(Some(&config_path_string), None).map_err(WorkspaceError::from)?;
121
122        // Snapshot every TOML file's rendered shape so save() can
123        // tell which files actually have unsaved edits.
124        //
125        // # Why "rendered model" rather than "on-disk text"
126        //
127        // A naive baseline would store the literal on-disk text. But
128        // our writer (`toml_writer`) produces canonicalised TOML —
129        // sorted keys, no comments, double-quoted strings, etc. —
130        // which almost never byte-matches a hand-edited file. With
131        // "on-disk" baseline, `has_unsaved_changes` would return
132        // `true` right after a load with no edits, and the first
133        // save would unconditionally rewrite every file.
134        //
135        // Storing the *rendered* baseline solves this: a freshly
136        // loaded workspace has rendered == baseline by construction,
137        // so `has_unsaved_changes` is false. Edits flip it to true,
138        // and only the files that diverge get rewritten on save.
139        // The user's hand-formatting on never-edited files survives
140        // untouched.
141        let mut baseline_files: HashMap<PathBuf, String> = HashMap::new();
142        baseline_files.insert(
143            resolved.clone(),
144            crate::toml_writer::render_apimock_toml(&config),
145        );
146        for rule_set in config.service.rule_sets.iter() {
147            let path = PathBuf::from(rule_set.file_path.as_str());
148            baseline_files.insert(
149                path,
150                crate::toml_writer::render_rule_set_toml(rule_set),
151            );
152        }
153
154        // Snapshot file metadata for external-change detection (RFC 024).
155        let mut file_metas: HashMap<PathBuf, FileMeta> = HashMap::new();
156        for path in baseline_files.keys() {
157            if let Ok(meta) = std::fs::metadata(path) {
158                if let Ok(modified) = meta.modified() {
159                    file_metas.insert(path.clone(), FileMeta { modified, len: meta.len() });
160                }
161            }
162        }
163
164        let mut workspace = Self {
165            root_path: resolved,
166            config,
167            ids: IdIndex::default(),
168            diagnostics: Vec::new(),
169            baseline_files,
170            file_metas,
171        };
172        workspace.seed_ids();
173        Ok(workspace)
174    }
175
176    // ── RFC 024: external-change detection ───────────────────────────────
177
178    /// Returns `true` if any tracked config file has been modified on disk
179    /// since the last `load()` or `save()`.
180    ///
181    /// Polls file metadata (mtime + size). Returns `false` on stat errors
182    /// to avoid spurious "changed" signals from transient temp-file churn.
183    ///
184    /// # Usage
185    ///
186    /// Call periodically from the GUI and re-render when `true`:
187    ///
188    /// ```rust,no_run
189    /// # use apimock_config::Workspace;
190    /// # let mut ws = Workspace::load("apimock.toml".into()).unwrap();
191    /// if ws.has_external_changes() {
192    ///     ws.sync_from_disk().unwrap();
193    /// }
194    /// ```
195    pub fn has_external_changes(&self) -> bool {
196        for (path, recorded) in &self.file_metas {
197            if let Ok(meta) = std::fs::metadata(path) {
198                let changed_size = meta.len() != recorded.len;
199                let changed_mtime = meta.modified()
200                    .map(|m| m != recorded.modified)
201                    .unwrap_or(false);
202                if changed_size || changed_mtime {
203                    return true;
204                }
205            }
206            // Stat error (file deleted, permission) → treat as unchanged.
207        }
208        false
209    }
210
211    /// Reload all config files from disk, replacing the in-memory model.
212    ///
213    /// NodeIds for unchanged addresses (same rule-set path, same rule
214    /// index) are preserved across the reload. NodeIds for addresses that
215    /// no longer exist are dropped; new addresses get fresh IDs.
216    ///
217    /// On parse error, the workspace is left unchanged and the error is
218    /// returned. The GUI can surface the error and retry.
219    ///
220    /// After a successful sync, `has_external_changes()` returns `false`
221    /// until the next external modification.
222    pub fn sync_from_disk(&mut self) -> Result<(), WorkspaceError> {
223        let fresh = Self::load(self.root_path.clone())?;
224        // Replace the entire workspace state. NodeIDs are re-seeded from
225        // scratch; GUI callers should treat a sync like a fresh load and
226        // re-query all NodeIds from the new snapshot.
227        *self = fresh;
228        Ok(())
229    }
230
231    /// Assign a fresh NodeId to every editable address in `config`.
232    /// Called from `load` and from any `apply()` path that might
233    /// change the address of existing nodes.
234    ///
235    /// # Why we rebuild rather than patch
236    ///
237    /// `NodeAddress` carries positional indices (`rule_set: usize`).
238    /// When a rule is deleted from the middle of a list, every rule
239    /// after it gets a new index, so its `NodeAddress` changes. The
240    /// GUI's NodeId must *not* change — that's the whole point of
241    /// UUIDs — so this function preserves the existing
242    /// address_to_id mapping where addresses still exist and only
243    /// mints new IDs for genuinely new addresses.
244    ///
245    /// For Step 1 there's nothing to preserve: load is a from-scratch
246    /// operation. Step 2 will call a more careful `reseed_after_edit`.
247    fn seed_ids(&mut self) {
248        // Root is always present.
249        self.ids.insert(NodeAddress::Root);
250
251        // Fallback respond dir is always present — even if the user
252        // hasn't set it, it has a default value.
253        self.ids.insert(NodeAddress::FallbackRespondDir);
254
255        // Rule sets + their rules + respond blocks.
256        for (rs_idx, rule_set) in self.config.service.rule_sets.iter().enumerate() {
257            self.ids.insert(NodeAddress::RuleSet { rule_set: rs_idx });
258            for (rule_idx, _rule) in rule_set.rules.iter().enumerate() {
259                self.ids.insert(NodeAddress::Rule {
260                    rule_set: rs_idx,
261                    rule: rule_idx,
262                });
263                self.ids.insert(NodeAddress::Respond {
264                    rule_set: rs_idx,
265                    rule: rule_idx,
266                });
267            }
268        }
269
270        // Middleware references.
271        if let Some(paths) = self.config.service.middlewares_file_paths.as_ref() {
272            for mw_idx in 0..paths.len() {
273                self.ids
274                    .insert(NodeAddress::Middleware { middleware: mw_idx });
275            }
276        }
277    }
278
279    /// Resolve a relative path against the config file's parent dir.
280    /// Used by snapshot rendering and by `cmd_add_rule_set`.
281    pub(super) fn config_relative_dir(&self) -> Result<String, ConfigError> {
282        self.config.current_dir_to_parent_dir_relative_path()
283    }
284
285    /// Joins a relative TOML path string against the config's parent
286    /// directory. Used by snapshot rendering when materialising
287    /// middleware / fallback dir paths for display.
288    pub(super) fn resolve_relative(&self, rel: &str) -> PathBuf {
289        match self.config.current_dir_to_parent_dir_relative_path() {
290            Ok(dir) => Path::new(&dir).join(rel),
291            Err(_) => PathBuf::from(rel),
292        }
293    }
294
295    /// Access the underlying `Config`. Intended for embedders that
296    /// need to build a running `Server` from the same workspace. Edit
297    /// via `apply()` instead of touching `Config` directly — changes
298    /// made through this reference are invisible to the ID index.
299    pub fn config(&self) -> &Config {
300        &self.config
301    }
302
303    /// Access the root path. Primarily for diagnostics.
304    pub fn root_path(&self) -> &Path {
305        &self.root_path
306    }
307
308    /// Expand a directory in the file tree on demand.
309    ///
310    /// # When the GUI calls this
311    ///
312    /// `Workspace::snapshot()` returns a `FileTreeView` populated with
313    /// just the top-level entries of the fallback respond dir. Each
314    /// directory entry carries `children: Some(Vec::new())` to flag it
315    /// as expandable. When a user clicks to expand one of those nodes,
316    /// the GUI calls `list_directory(&entry.path)` and gets back the
317    /// next depth's entries (still not recursed past that depth — the
318    /// same lazy contract holds).
319    ///
320    /// # Why path-based and not NodeId-based
321    ///
322    /// File-tree entries don't carry NodeIds (see `FileNodeView`). The
323    /// reason is lifecycle: the editable node space (rules, rule sets,
324    /// respond blocks) is small, stable, and survives `apply()` calls
325    /// — perfect for UUID-keyed state. The file tree is large,
326    /// transient, and reflects the filesystem rather than the model;
327    /// keying it by path keeps the API simple and avoids mixing two
328    /// kinds of identity.
329    pub fn list_directory(&self, path: &Path) -> Vec<apimock_routing::view::FileNodeView> {
330        let filter = self
331            .config
332            .file_tree_view
333            .as_ref()
334            .map(|c| c.to_filter())
335            .unwrap_or_default();
336        apimock_routing::view::build::list_directory_with(path, &filter)
337    }
338}