Skip to main content

brep_plm/scripting/
mod.rs

1//! Administrator scripts: the directory they live in, the hooks the server
2//! calls, and the test run the web editor offers.
3//!
4//! The operator's design:
5//!
6//! * Scripts are plain `.js` FILES in a directory on the server
7//!   (`--scripts`, default `<data>/scripts`). The directory is the source of
8//!   truth, so an administrator can keep it in git. The web editor writes the
9//!   same files. History is git's job.
10//! * A changed file takes effect on the NEXT call: [`Scripts::source`] re-reads
11//!   a file whenever its modification time or length differs from what it
12//!   cached. There is no watcher thread and no restart.
13//! * Scripts are FULLY TRUSTED — network, the PLM API, the file system and
14//!   child processes ([`host`]).
15//! * A script that throws, fails to parse or times out in a host call REFUSES
16//!   the operation it hooks. The one exception is [`AFTER_RELEASE`], which runs
17//!   after the release is committed and so can only report.
18//!
19//! # The hooks
20//!
21//! One file per hook, each defining one global function that takes one JSON
22//! argument:
23//!
24//! | File | Function | When |
25//! | --- | --- | --- |
26//! | the type's own file | `partNumber(input)` | creating a part of a Script-mode type |
27//! | [`REVISION_LABEL`] | `revisionLabel(input)` | creating any revision, when the file exists |
28//! | [`BEFORE_RELEASE`] | `beforeRelease(input)` | before a release commits, when the file exists |
29//! | [`AFTER_RELEASE`] | `afterRelease(input)` | after a release commits, when the file exists |
30//!
31//! A hook NEVER runs while the store lock is held: the store decides on a
32//! snapshot, runs the hook, and then re-checks everything the hook's answer
33//! depends on inside its one locked write (see [`crate::db`]).
34
35// The interpreter core lives in its own crate so the CAD app can build it,
36// wasm included (BREP_script_core); it keeps its old name here.
37pub use brep_script_core as engine;
38pub mod host;
39
40use std::collections::HashMap;
41use std::fs;
42use std::io;
43use std::path::{Path, PathBuf};
44use std::sync::{Arc, Mutex};
45use std::time::SystemTime;
46
47use serde::Serialize;
48use serde_json::Value;
49
50use crate::db::Db;
51use crate::model::User;
52use crate::Error;
53
54/// Suggests or validates the label of every new revision.
55pub const REVISION_LABEL: &str = "revision-label.js";
56/// May refuse a release.
57pub const BEFORE_RELEASE: &str = "before-release.js";
58/// Told about a release after it commits.
59pub const AFTER_RELEASE: &str = "after-release.js";
60/// Proposes a review round's reviewers when a revision is submitted.
61pub const REVIEWERS: &str = "reviewers.js";
62/// Told about every review event after it commits — the notification hook.
63pub const REVIEW_EVENT: &str = "review-event.js";
64/// The file a new Script-mode part type is offered by default.
65pub const DEFAULT_PART_NUMBER: &str = "part-number.js";
66
67/// The hooks, for the page: which file, which function, what it is for.
68#[derive(Debug, Clone, Serialize)]
69pub struct HookDoc {
70    pub file: &'static str,
71    pub function: &'static str,
72    pub when: &'static str,
73}
74
75pub const HOOKS: &[HookDoc] = &[
76    HookDoc {
77        file: "(named by the part type)",
78        function: "partNumber",
79        when: "creating a part of a Script-mode part type; return the number or throw to refuse",
80    },
81    HookDoc {
82        file: REVISION_LABEL,
83        function: "revisionLabel",
84        when: "creating a revision; return the label or throw to refuse",
85    },
86    HookDoc {
87        file: BEFORE_RELEASE,
88        function: "beforeRelease",
89        when: "before a release commits; throw to refuse the release",
90    },
91    HookDoc {
92        file: AFTER_RELEASE,
93        function: "afterRelease",
94        when: "after a release commits; a throw is reported, the release stands",
95    },
96    HookDoc {
97        file: REVIEWERS,
98        function: "reviewers",
99        when: "submitting a revision for review; return { reviewers, required_approvals, due } to change the round, or throw to refuse",
100    },
101    HookDoc {
102        file: REVIEW_EVENT,
103        function: "reviewEvent",
104        when: "after a review is opened, decided, withdrawn, changed or commented on; for notifications — a throw is reported, the event stands",
105    },
106];
107
108/// One file in the directory, as the page lists it.
109#[derive(Debug, Clone, Serialize)]
110pub struct ScriptFile {
111    pub path: String,
112    pub size: u64,
113    pub modified: u64,
114}
115
116struct Cached {
117    modified: Option<SystemTime>,
118    len: u64,
119    text: Arc<str>,
120}
121
122/// The scripts directory and a modification-time cache of its files.
123pub struct Scripts {
124    dir: PathBuf,
125    cache: Mutex<HashMap<PathBuf, Cached>>,
126}
127
128impl Scripts {
129    pub fn new(dir: impl Into<PathBuf>) -> io::Result<Self> {
130        let dir = dir.into();
131        fs::create_dir_all(&dir)?;
132        Ok(Scripts { dir, cache: Mutex::new(HashMap::new()) })
133    }
134
135    pub fn dir(&self) -> &Path {
136        &self.dir
137    }
138
139    /// The file `relative` names, refusing anything that could leave the
140    /// directory or is not a `.js` file. Scripts are fully trusted once they
141    /// run; the EDITOR route still should not write outside its directory.
142    pub fn resolve(&self, relative: &str) -> Result<PathBuf, Error> {
143        let relative = relative.trim().trim_start_matches('/');
144        let mut path = self.dir.clone();
145        let refuse = || Error::bad_request(format!("'{relative}' is not a usable script path — letters, digits, '-', '_', '.', '/' and a .js name"));
146        if !relative.ends_with(".js") {
147            return Err(refuse());
148        }
149        for segment in relative.split('/') {
150            if segment.is_empty()
151                || segment.starts_with('.')
152                || !segment
153                    .chars()
154                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
155            {
156                return Err(refuse());
157            }
158            path.push(segment);
159        }
160        Ok(path)
161    }
162
163    /// The current text of `relative`, or `None` when there is no such file.
164    ///
165    /// This is the reload rule: the cached text is used only while the file's
166    /// modification time AND length are what they were when it was read. A
167    /// `git pull`, an editor save or the web editor all change one of them.
168    pub fn source(&self, relative: &str) -> Result<Option<Arc<str>>, Error> {
169        let path = self.resolve(relative)?;
170        let meta = match fs::metadata(&path) {
171            Ok(meta) if meta.is_file() => meta,
172            Ok(_) => return Ok(None),
173            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
174            Err(error) => return Err(Error::internal(error)),
175        };
176        let modified = meta.modified().ok();
177        let len = meta.len();
178        let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
179        if let Some(hit) = cache.get(&path) {
180            if hit.modified == modified && hit.len == len {
181                return Ok(Some(hit.text.clone()));
182            }
183        }
184        let text: Arc<str> = match fs::read_to_string(&path) {
185            Ok(text) => text.into(),
186            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
187            Err(error) => return Err(Error::internal(error)),
188        };
189        cache.insert(path, Cached { modified, len, text: text.clone() });
190        Ok(Some(text))
191    }
192
193    /// Every `.js` file under the directory, sorted by path.
194    pub fn list(&self) -> Vec<ScriptFile> {
195        let mut out = Vec::new();
196        walk(&self.dir, &self.dir, &mut out);
197        out.sort_by(|a, b| a.path.cmp(&b.path));
198        out
199    }
200
201    /// Write a script through a temporary file and a rename, as the store does.
202    pub fn write(&self, relative: &str, text: &str) -> Result<(), Error> {
203        let path = self.resolve(relative)?;
204        if let Some(parent) = path.parent() {
205            fs::create_dir_all(parent).map_err(Error::internal)?;
206        }
207        crate::db::write_atomic(&path, text).map_err(Error::internal)?;
208        self.forget(&path);
209        Ok(())
210    }
211
212    pub fn delete(&self, relative: &str) -> Result<(), Error> {
213        let path = self.resolve(relative)?;
214        match fs::remove_file(&path) {
215            Ok(()) => {}
216            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
217            Err(error) => return Err(Error::internal(error)),
218        }
219        self.forget(&path);
220        Ok(())
221    }
222
223    fn forget(&self, path: &Path) {
224        self.cache
225            .lock()
226            .unwrap_or_else(|e| e.into_inner())
227            .remove(path);
228    }
229}
230
231fn walk(root: &Path, dir: &Path, out: &mut Vec<ScriptFile>) {
232    let Ok(entries) = fs::read_dir(dir) else { return };
233    for entry in entries.flatten() {
234        let path = entry.path();
235        let name = entry.file_name();
236        if name.to_string_lossy().starts_with('.') {
237            continue; // .git and editor droppings
238        }
239        let Ok(meta) = entry.metadata() else { continue };
240        if meta.is_dir() {
241            walk(root, &path, out);
242        } else if path.extension().is_some_and(|e| e == "js") {
243            let relative = path
244                .strip_prefix(root)
245                .map(|p| p.to_string_lossy().replace('\\', "/"))
246                .unwrap_or_default();
247            let modified = meta
248                .modified()
249                .ok()
250                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
251                .map(|d| d.as_secs())
252                .unwrap_or(0);
253            out.push(ScriptFile { path: relative, size: meta.len(), modified });
254        }
255    }
256}
257
258/// What a hook call produced, for the caller that runs it.
259pub enum HookResult {
260    /// The file does not exist. For an optional hook this means "do what the
261    /// server does without it".
262    Absent,
263    Returned(engine::Success),
264    Refused(engine::Failure),
265}
266
267/// Run `function` in the script `relative`, with the server's host bindings
268/// acting as `user`.
269///
270/// Call this OUTSIDE [`Db::mutate`] — it may block on the network or a child
271/// process, and the host's `plm` object takes the store lock itself.
272pub fn run(db: &Db, user: &User, relative: &str, function: &str, input: &Value) -> Result<HookResult, Error> {
273    let Some(source) = db.scripts().source(relative)? else {
274        return Ok(HookResult::Absent);
275    };
276    Ok(run_source(db, user, &source, relative, function, input))
277}
278
279/// Run unsaved `source` — the editor's test run of text not yet written.
280pub fn run_source(db: &Db, user: &User, source: &str, name: &str, function: &str, input: &Value) -> HookResult {
281    let host = host::Host::new(db.clone(), user.clone());
282    match engine::call(source, name, function, input, &|context, _| host.install(context)) {
283        Ok(success) => HookResult::Returned(success),
284        Err(failure) => {
285            for line in &failure.logs {
286                eprintln!("brep-plm: script {name}: {line}");
287            }
288            eprintln!("brep-plm: script {name}: {function}() refused: {}", failure.message);
289            HookResult::Refused(failure)
290        }
291    }
292}
293
294/// The user as a script sees it: identity and groups, never the verifier.
295pub fn user_json(user: &User) -> Value {
296    serde_json::json!({
297        "id": user.id,
298        "username": user.username,
299        "display_name": user.display_name,
300        "email": user.email,
301        "groups": user.groups,
302    })
303}
304
305/// Read a hook's answer as a string: either the string itself or the named
306/// field of a returned object (`"B"` or `{ label: "B" }`).
307pub fn string_answer(value: &Value, field: &str) -> Option<String> {
308    match value {
309        Value::String(text) => Some(text.clone()),
310        Value::Object(map) => map.get(field).and_then(|v| v.as_str()).map(str::to_string),
311        _ => None,
312    }
313}