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    // clippy: WorkspaceError is a public error type (RFC 030 §6 escalation
112    // trigger); boxing its large variant would change that type's shape.
113    // See ESCALATION-002 in the RFC 030 review-request package.
114    #[allow(clippy::result_large_err)]
115    pub fn load(root: PathBuf) -> Result<Self, WorkspaceError> {
116        let resolved = resolve_root(&root)?;
117
118        // Re-use `Config::new` so rule-set loading + validation go
119        // through the same path as the running server. This is
120        // important — the spec's "GUI doesn't break running server
121        // behaviour" invariant (§13) is easiest to guarantee if both
122        // paths share the same loader.
123        let config_path_string = resolved.to_string_lossy().into_owned();
124        let config = Config::new(Some(&config_path_string), None).map_err(WorkspaceError::from)?;
125
126        // Snapshot every TOML file's rendered shape so save() can
127        // tell which files actually have unsaved edits.
128        //
129        // # Why "rendered model" rather than "on-disk text"
130        //
131        // A naive baseline would store the literal on-disk text. But
132        // our writer (`toml_writer`) produces canonicalised TOML —
133        // sorted keys, no comments, double-quoted strings, etc. —
134        // which almost never byte-matches a hand-edited file. With
135        // "on-disk" baseline, `has_unsaved_changes` would return
136        // `true` right after a load with no edits, and the first
137        // save would unconditionally rewrite every file.
138        //
139        // Storing the *rendered* baseline solves this: a freshly
140        // loaded workspace has rendered == baseline by construction,
141        // so `has_unsaved_changes` is false. Edits flip it to true,
142        // and only the files that diverge get rewritten on save.
143        // The user's hand-formatting on never-edited files survives
144        // untouched.
145        let mut baseline_files: HashMap<PathBuf, String> = HashMap::new();
146        baseline_files.insert(
147            resolved.clone(),
148            crate::toml_writer::render_apimock_toml(&config),
149        );
150        for rule_set in config.service.rule_sets.iter() {
151            let path = PathBuf::from(rule_set.file_path.as_str());
152            baseline_files.insert(path, crate::toml_writer::render_rule_set_toml(rule_set));
153        }
154
155        // Snapshot file metadata for external-change detection (RFC 024).
156        let mut file_metas: HashMap<PathBuf, FileMeta> = HashMap::new();
157        for path in baseline_files.keys() {
158            if let Ok(meta) = std::fs::metadata(path)
159                && let Ok(modified) = meta.modified()
160            {
161                file_metas.insert(
162                    path.clone(),
163                    FileMeta {
164                        modified,
165                        len: meta.len(),
166                    },
167                );
168            }
169        }
170
171        let mut workspace = Self {
172            root_path: resolved,
173            config,
174            ids: IdIndex::default(),
175            diagnostics: Vec::new(),
176            baseline_files,
177            file_metas,
178        };
179        workspace.seed_ids();
180        Ok(workspace)
181    }
182
183    // ── RFC 024: external-change detection ───────────────────────────────
184
185    /// Returns `true` if any tracked config file has been modified on disk
186    /// since the last `load()` or `save()`.
187    ///
188    /// Polls file metadata (mtime + size). Returns `false` on stat errors
189    /// to avoid spurious "changed" signals from transient temp-file churn.
190    ///
191    /// # Usage
192    ///
193    /// Call periodically from the GUI and re-render when `true`:
194    ///
195    /// ```rust,no_run
196    /// # use apimock_config::Workspace;
197    /// # let mut ws = Workspace::load("apimock.toml".into()).unwrap();
198    /// if ws.has_external_changes() {
199    ///     ws.sync_from_disk().unwrap();
200    /// }
201    /// ```
202    pub fn has_external_changes(&self) -> bool {
203        for (path, recorded) in &self.file_metas {
204            if let Ok(meta) = std::fs::metadata(path) {
205                let changed_size = meta.len() != recorded.len;
206                let changed_mtime = meta
207                    .modified()
208                    .map(|m| m != recorded.modified)
209                    .unwrap_or(false);
210                if changed_size || changed_mtime {
211                    return true;
212                }
213            }
214            // Stat error (file deleted, permission) → treat as unchanged.
215        }
216        false
217    }
218
219    /// Reload all config files from disk, replacing the in-memory model.
220    ///
221    /// NodeIds for unchanged addresses (same rule-set path, same rule
222    /// index) are preserved across the reload. NodeIds for addresses that
223    /// no longer exist are dropped; new addresses get fresh IDs.
224    ///
225    /// On parse error, the workspace is left unchanged and the error is
226    /// returned. The GUI can surface the error and retry.
227    ///
228    /// After a successful sync, `has_external_changes()` returns `false`
229    /// until the next external modification.
230    // clippy: WorkspaceError is a public error type (RFC 030 §6 escalation
231    // trigger); boxing its large variant would change that type's shape.
232    // See ESCALATION-002 in the RFC 030 review-request package.
233    #[allow(clippy::result_large_err)]
234    pub fn sync_from_disk(&mut self) -> Result<(), WorkspaceError> {
235        let fresh = Self::load(self.root_path.clone())?;
236        // Replace the entire workspace state. NodeIDs are re-seeded from
237        // scratch; GUI callers should treat a sync like a fresh load and
238        // re-query all NodeIds from the new snapshot.
239        *self = fresh;
240        Ok(())
241    }
242
243    /// Assign a fresh NodeId to every editable address in `config`.
244    /// Called from `load` and from any `apply()` path that might
245    /// change the address of existing nodes.
246    ///
247    /// # Why we rebuild rather than patch
248    ///
249    /// `NodeAddress` carries positional indices (`rule_set: usize`).
250    /// When a rule is deleted from the middle of a list, every rule
251    /// after it gets a new index, so its `NodeAddress` changes. The
252    /// GUI's NodeId must *not* change — that's the whole point of
253    /// UUIDs — so this function preserves the existing
254    /// address_to_id mapping where addresses still exist and only
255    /// mints new IDs for genuinely new addresses.
256    ///
257    /// For Step 1 there's nothing to preserve: load is a from-scratch
258    /// operation. Step 2 will call a more careful `reseed_after_edit`.
259    fn seed_ids(&mut self) {
260        // Root is always present.
261        self.ids.insert(NodeAddress::Root);
262
263        // Fallback respond dir is always present — even if the user
264        // hasn't set it, it has a default value.
265        self.ids.insert(NodeAddress::FallbackRespondDir);
266
267        // Rule sets + their rules + respond blocks.
268        for (rs_idx, rule_set) in self.config.service.rule_sets.iter().enumerate() {
269            self.ids.insert(NodeAddress::RuleSet { rule_set: rs_idx });
270            for (rule_idx, _rule) in rule_set.rules.iter().enumerate() {
271                self.ids.insert(NodeAddress::Rule {
272                    rule_set: rs_idx,
273                    rule: rule_idx,
274                });
275                self.ids.insert(NodeAddress::Respond {
276                    rule_set: rs_idx,
277                    rule: rule_idx,
278                });
279            }
280        }
281
282        // Middleware references.
283        if let Some(paths) = self.config.service.middlewares_file_paths.as_ref() {
284            for mw_idx in 0..paths.len() {
285                self.ids
286                    .insert(NodeAddress::Middleware { middleware: mw_idx });
287            }
288        }
289    }
290
291    /// Resolve a relative path against the config file's parent dir.
292    /// Used by snapshot rendering and by `cmd_add_rule_set`.
293    // clippy: ConfigError is a public error type (RFC 030 §6 escalation
294    // trigger); boxing its large variant would change that type's shape.
295    // See ESCALATION-002 in the RFC 030 review-request package.
296    #[allow(clippy::result_large_err)]
297    pub(super) fn config_relative_dir(&self) -> Result<String, ConfigError> {
298        self.config.current_dir_to_parent_dir_relative_path()
299    }
300
301    /// Joins a relative TOML path string against the config's parent
302    /// directory. Used by snapshot rendering when materialising
303    /// middleware / fallback dir paths for display.
304    pub(super) fn resolve_relative(&self, rel: &str) -> PathBuf {
305        match self.config.current_dir_to_parent_dir_relative_path() {
306            Ok(dir) => Path::new(&dir).join(rel),
307            Err(_) => PathBuf::from(rel),
308        }
309    }
310
311    /// Access the underlying `Config`. Intended for embedders that
312    /// need to build a running `Server` from the same workspace. Edit
313    /// via `apply()` instead of touching `Config` directly — changes
314    /// made through this reference are invisible to the ID index.
315    pub fn config(&self) -> &Config {
316        &self.config
317    }
318
319    /// Access the root path. Primarily for diagnostics.
320    pub fn root_path(&self) -> &Path {
321        &self.root_path
322    }
323
324    /// Expand a directory in the file tree on demand.
325    ///
326    /// # When the GUI calls this
327    ///
328    /// `Workspace::snapshot()` returns a `FileTreeView` populated with
329    /// just the top-level entries of the fallback respond dir. Each
330    /// directory entry carries `children: Some(Vec::new())` to flag it
331    /// as expandable. When a user clicks to expand one of those nodes,
332    /// the GUI calls `list_directory(&entry.path)` and gets back the
333    /// next depth's entries (still not recursed past that depth — the
334    /// same lazy contract holds).
335    ///
336    /// # Why path-based and not NodeId-based
337    ///
338    /// File-tree entries don't carry NodeIds (see `FileNodeView`). The
339    /// reason is lifecycle: the editable node space (rules, rule sets,
340    /// respond blocks) is small, stable, and survives `apply()` calls
341    /// — perfect for UUID-keyed state. The file tree is large,
342    /// transient, and reflects the filesystem rather than the model;
343    /// keying it by path keeps the API simple and avoids mixing two
344    /// kinds of identity.
345    pub fn list_directory(&self, path: &Path) -> Vec<apimock_routing::view::FileNodeView> {
346        let filter = self
347            .config
348            .file_tree_view
349            .as_ref()
350            .map(|c| c.to_filter())
351            .unwrap_or_default();
352        apimock_routing::view::build::list_directory_with(path, &filter)
353    }
354}