Skip to main content

apimock_config/workspace/
snapshot.rs

1//! `Workspace::snapshot()` and the per-file view builders it composes.
2//!
3//! # Why this is a separate module
4//!
5//! Snapshot is read-only; it owns no mutating logic. Keeping it apart
6//! from the edit / save modules makes the read path easy to reason
7//! about — there's no chance a snapshot helper accidentally mutates
8//! the model because the `&self` receiver here can't.
9//!
10//! # Per-node validation runs here too
11//!
12//! `rule_set_file_view` calls into [`crate::workspace::validate`]
13//! to attach `NodeValidation` to each respond node. That means
14//! snapshot rendering and `validate()` walk the same checks; a node
15//! marked invalid in the snapshot will also appear in
16//! `ValidationReport::diagnostics`.
17
18use std::path::PathBuf;
19
20use apimock_routing::RuleSet;
21
22use crate::view::{
23    ConfigFileKind, ConfigFileView, ConfigNodeView, NodeKind, NodeValidation, WorkspaceSnapshot,
24};
25
26use super::Workspace;
27use super::id_index::NodeAddress;
28use super::path_helpers::file_basename;
29use super::validate::respond_node_validation;
30
31impl Workspace {
32    /// Build a snapshot for GUI rendering.
33    ///
34    /// # Allocation cost
35    ///
36    /// A snapshot fully owns its data (no borrows into the workspace)
37    /// so the GUI can serialise / send / store it without lifetime
38    /// gymnastics. This is O(total editable nodes) allocation per
39    /// call; the GUI should call it once per edit, not once per
40    /// render frame.
41    pub fn snapshot(&self) -> WorkspaceSnapshot {
42        let mut files: Vec<ConfigFileView> = Vec::new();
43
44        // Root file.
45        if let Some(root_nodes) = self.root_file_nodes() {
46            files.push(root_nodes);
47        }
48
49        // Rule-set files.
50        for (rs_idx, rule_set) in self.config.service.rule_sets.iter().enumerate() {
51            files.push(self.rule_set_file_view(rs_idx, rule_set));
52        }
53
54        // Middleware files. We don't introspect them beyond their path
55        // existence; the Rhai AST is a server-side concern.
56        if let Some(paths) = self.config.service.middlewares_file_paths.as_ref() {
57            for (mw_idx, mw_path) in paths.iter().enumerate() {
58                let abs = self.resolve_relative(mw_path);
59                let id = self
60                    .ids
61                    .id_for(NodeAddress::Middleware { middleware: mw_idx })
62                    .expect("middleware id seeded at load");
63                let node = ConfigNodeView {
64                    id,
65                    source_file: abs.clone(),
66                    toml_path: format!("service.middlewares[{}]", mw_idx),
67                    display_name: mw_path.clone(),
68                    kind: NodeKind::Script,
69                    validation: NodeValidation::ok(),
70                };
71                files.push(ConfigFileView {
72                    path: abs.clone(),
73                    display_name: file_basename(&abs),
74                    kind: ConfigFileKind::Middleware,
75                    nodes: vec![node],
76                });
77            }
78        }
79
80        // Route catalog — assemble from rule sets, fallback dir,
81        // file tree (depth-1 eager), and middleware script routes.
82        // Builders live in `apimock_routing::view::build`; the config
83        // crate just feeds them the data they need.
84        let fallback_dir = self.config.service.fallback_respond_dir.as_str();
85        let fallback_abs = self.resolve_relative(fallback_dir);
86        let filter = self
87            .config
88            .file_tree_view
89            .as_ref()
90            .map(|c| c.to_filter())
91            .unwrap_or_default();
92        let file_tree = apimock_routing::view::build::build_file_tree_with(&fallback_abs, &filter);
93
94        let script_routes: Vec<apimock_routing::view::ScriptRouteView> = self
95            .config
96            .service
97            .middlewares_file_paths
98            .as_ref()
99            .map(|paths| {
100                paths
101                    .iter()
102                    .enumerate()
103                    .map(|(idx, p)| apimock_routing::view::build::build_script_route_view(idx, p))
104                    .collect()
105            })
106            .unwrap_or_default();
107
108        let routes = apimock_routing::view::build::build_route_catalog(
109            &self.config.service.rule_sets,
110            Some(fallback_dir),
111            file_tree,
112            script_routes,
113        );
114
115        WorkspaceSnapshot {
116            files,
117            routes,
118            diagnostics: self.diagnostics.clone(),
119        }
120    }
121    /// Root config file as a `ConfigFileView`, if it can be rendered.
122    fn root_file_nodes(&self) -> Option<ConfigFileView> {
123        let mut nodes = Vec::new();
124
125        if let Some(root_id) = self.ids.id_for(NodeAddress::Root) {
126            nodes.push(ConfigNodeView {
127                id: root_id,
128                source_file: self.root_path.clone(),
129                toml_path: String::new(),
130                display_name: "apimock.toml".to_owned(),
131                kind: NodeKind::RootSetting,
132                validation: NodeValidation::ok(),
133            });
134        }
135
136        if let Some(fb_id) = self.ids.id_for(NodeAddress::FallbackRespondDir) {
137            nodes.push(ConfigNodeView {
138                id: fb_id,
139                source_file: self.root_path.clone(),
140                toml_path: "service.fallback_respond_dir".to_owned(),
141                display_name: self.config.service.fallback_respond_dir.clone(),
142                kind: NodeKind::FileNode,
143                validation: NodeValidation::ok(),
144            });
145        }
146
147        Some(ConfigFileView {
148            path: self.root_path.clone(),
149            display_name: file_basename(&self.root_path),
150            kind: ConfigFileKind::Root,
151            nodes,
152        })
153    }
154
155    fn rule_set_file_view(&self, rs_idx: usize, rule_set: &RuleSet) -> ConfigFileView {
156        let file_path = PathBuf::from(rule_set.file_path.as_str());
157        let mut nodes: Vec<ConfigNodeView> = Vec::new();
158
159        // Rule-set itself.
160        if let Some(rs_id) = self.ids.id_for(NodeAddress::RuleSet { rule_set: rs_idx }) {
161            nodes.push(ConfigNodeView {
162                id: rs_id,
163                source_file: file_path.clone(),
164                toml_path: String::new(),
165                display_name: file_basename(&file_path),
166                kind: NodeKind::RuleSet,
167                validation: NodeValidation::ok(),
168            });
169        }
170
171        // Rules inside.
172        for (rule_idx, rule) in rule_set.rules.iter().enumerate() {
173            if let Some(rule_id) = self.ids.id_for(NodeAddress::Rule {
174                rule_set: rs_idx,
175                rule: rule_idx,
176            }) {
177                let url_path_label = rule
178                    .when
179                    .request
180                    .url_path
181                    .as_ref()
182                    .map(|u| u.value.as_str())
183                    .unwrap_or_default();
184                let display = if url_path_label.is_empty() {
185                    format!("Rule #{}", rule_idx + 1)
186                } else {
187                    url_path_label.to_owned()
188                };
189                nodes.push(ConfigNodeView {
190                    id: rule_id,
191                    source_file: file_path.clone(),
192                    toml_path: format!("rules[{}]", rule_idx),
193                    display_name: display,
194                    kind: NodeKind::Rule,
195                    validation: NodeValidation::ok(),
196                });
197            }
198
199            if let Some(resp_id) = self.ids.id_for(NodeAddress::Respond {
200                rule_set: rs_idx,
201                rule: rule_idx,
202            }) {
203                nodes.push(ConfigNodeView {
204                    id: resp_id,
205                    source_file: file_path.clone(),
206                    toml_path: format!("rules[{}].respond", rule_idx),
207                    display_name: summarise_respond(&rule.respond),
208                    kind: NodeKind::Respond,
209                    validation: respond_node_validation(&rule.respond, rule_set, rule_idx, rs_idx),
210                });
211            }
212        }
213
214        ConfigFileView {
215            path: file_path.clone(),
216            display_name: file_basename(&file_path),
217            kind: ConfigFileKind::RuleSet,
218            nodes,
219        }
220    }
221}
222
223fn summarise_respond(respond: &apimock_routing::Respond) -> String {
224    if let Some(p) = respond.file_path.as_ref() {
225        return format!("file: {}", p);
226    }
227    if let Some(t) = respond.text.as_ref() {
228        const LIMIT: usize = 40;
229        if t.chars().count() > LIMIT {
230            let truncated: String = t.chars().take(LIMIT).collect();
231            return format!("text: {}…", truncated);
232        }
233        return format!("text: {}", t);
234    }
235    if let Some(s) = respond.status.as_ref() {
236        return format!("status: {}", s);
237    }
238    "(empty)".to_owned()
239}