1pub 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
54pub const REVISION_LABEL: &str = "revision-label.js";
56pub const BEFORE_RELEASE: &str = "before-release.js";
58pub const AFTER_RELEASE: &str = "after-release.js";
60pub const REVIEWERS: &str = "reviewers.js";
62pub const REVIEW_EVENT: &str = "review-event.js";
64pub const DEFAULT_PART_NUMBER: &str = "part-number.js";
66
67#[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#[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
122pub 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 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 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 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 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 let temp = path.with_extension("js.tmp");
208 fs::write(&temp, text).map_err(Error::internal)?;
209 fs::rename(&temp, &path).map_err(Error::internal)?;
210 self.forget(&path);
211 Ok(())
212 }
213
214 pub fn delete(&self, relative: &str) -> Result<(), Error> {
215 let path = self.resolve(relative)?;
216 match fs::remove_file(&path) {
217 Ok(()) => {}
218 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
219 Err(error) => return Err(Error::internal(error)),
220 }
221 self.forget(&path);
222 Ok(())
223 }
224
225 fn forget(&self, path: &Path) {
226 self.cache
227 .lock()
228 .unwrap_or_else(|e| e.into_inner())
229 .remove(path);
230 }
231}
232
233fn walk(root: &Path, dir: &Path, out: &mut Vec<ScriptFile>) {
234 let Ok(entries) = fs::read_dir(dir) else { return };
235 for entry in entries.flatten() {
236 let path = entry.path();
237 let name = entry.file_name();
238 if name.to_string_lossy().starts_with('.') {
239 continue; }
241 let Ok(meta) = entry.metadata() else { continue };
242 if meta.is_dir() {
243 walk(root, &path, out);
244 } else if path.extension().is_some_and(|e| e == "js") {
245 let relative = path
246 .strip_prefix(root)
247 .map(|p| p.to_string_lossy().replace('\\', "/"))
248 .unwrap_or_default();
249 let modified = meta
250 .modified()
251 .ok()
252 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
253 .map(|d| d.as_secs())
254 .unwrap_or(0);
255 out.push(ScriptFile { path: relative, size: meta.len(), modified });
256 }
257 }
258}
259
260pub enum HookResult {
262 Absent,
265 Returned(engine::Success),
266 Refused(engine::Failure),
267}
268
269pub fn run(db: &Db, user: &User, relative: &str, function: &str, input: &Value) -> Result<HookResult, Error> {
275 let Some(source) = db.scripts().source(relative)? else {
276 return Ok(HookResult::Absent);
277 };
278 Ok(run_source(db, user, &source, relative, function, input))
279}
280
281pub fn run_source(db: &Db, user: &User, source: &str, name: &str, function: &str, input: &Value) -> HookResult {
283 let host = host::Host::new(db.clone(), user.clone());
284 match engine::call(source, name, function, input, &|context, _| host.install(context)) {
285 Ok(success) => HookResult::Returned(success),
286 Err(failure) => {
287 for line in &failure.logs {
288 eprintln!("brep-plm: script {name}: {line}");
289 }
290 eprintln!("brep-plm: script {name}: {function}() refused: {}", failure.message);
291 HookResult::Refused(failure)
292 }
293 }
294}
295
296pub fn user_json(user: &User) -> Value {
298 serde_json::json!({
299 "id": user.id,
300 "username": user.username,
301 "display_name": user.display_name,
302 "email": user.email,
303 "groups": user.groups,
304 })
305}
306
307pub fn string_answer(value: &Value, field: &str) -> Option<String> {
310 match value {
311 Value::String(text) => Some(text.clone()),
312 Value::Object(map) => map.get(field).and_then(|v| v.as_str()).map(str::to_string),
313 _ => None,
314 }
315}