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: "(named by the change-order numbering)",
83 function: "ecoNumber",
84 when: "creating a change order when change orders number by script; return the number or throw to refuse",
85 },
86 HookDoc {
87 file: REVISION_LABEL,
88 function: "revisionLabel",
89 when: "creating a revision; return the label or throw to refuse",
90 },
91 HookDoc {
92 file: BEFORE_RELEASE,
93 function: "beforeRelease",
94 when: "before a release commits; throw to refuse the release",
95 },
96 HookDoc {
97 file: AFTER_RELEASE,
98 function: "afterRelease",
99 when: "after a release commits; a throw is reported, the release stands",
100 },
101 HookDoc {
102 file: REVIEWERS,
103 function: "reviewers",
104 when: "submitting a revision or a change order (input.kind is eco) for review; return { reviewers, required_approvals, due } to change the round, or throw to refuse",
105 },
106 HookDoc {
107 file: REVIEW_EVENT,
108 function: "reviewEvent",
109 when: "after a review is opened, decided, withdrawn, changed or commented on, and a change order released or cancelled; for notifications — a throw is reported, the event stands",
110 },
111];
112
113#[derive(Debug, Clone, Serialize)]
115pub struct ScriptFile {
116 pub path: String,
117 pub size: u64,
118 pub modified: u64,
119}
120
121struct Cached {
122 modified: Option<SystemTime>,
123 len: u64,
124 text: Arc<str>,
125}
126
127pub struct Scripts {
129 dir: PathBuf,
130 cache: Mutex<HashMap<PathBuf, Cached>>,
131}
132
133impl Scripts {
134 pub fn new(dir: impl Into<PathBuf>) -> io::Result<Self> {
135 let dir = dir.into();
136 fs::create_dir_all(&dir)?;
137 Ok(Scripts { dir, cache: Mutex::new(HashMap::new()) })
138 }
139
140 pub fn dir(&self) -> &Path {
141 &self.dir
142 }
143
144 pub fn resolve(&self, relative: &str) -> Result<PathBuf, Error> {
148 let relative = relative.trim().trim_start_matches('/');
149 let mut path = self.dir.clone();
150 let refuse = || Error::bad_request(format!("'{relative}' is not a usable script path — letters, digits, '-', '_', '.', '/' and a .js name"));
151 if !relative.ends_with(".js") {
152 return Err(refuse());
153 }
154 for segment in relative.split('/') {
155 if segment.is_empty()
156 || segment.starts_with('.')
157 || !segment
158 .chars()
159 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
160 {
161 return Err(refuse());
162 }
163 path.push(segment);
164 }
165 Ok(path)
166 }
167
168 pub fn source(&self, relative: &str) -> Result<Option<Arc<str>>, Error> {
174 let path = self.resolve(relative)?;
175 let meta = match fs::metadata(&path) {
176 Ok(meta) if meta.is_file() => meta,
177 Ok(_) => return Ok(None),
178 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
179 Err(error) => return Err(Error::internal(error)),
180 };
181 let modified = meta.modified().ok();
182 let len = meta.len();
183 let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
184 if let Some(hit) = cache.get(&path) {
185 if hit.modified == modified && hit.len == len {
186 return Ok(Some(hit.text.clone()));
187 }
188 }
189 let text: Arc<str> = match fs::read_to_string(&path) {
190 Ok(text) => text.into(),
191 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
192 Err(error) => return Err(Error::internal(error)),
193 };
194 cache.insert(path, Cached { modified, len, text: text.clone() });
195 Ok(Some(text))
196 }
197
198 pub fn list(&self) -> Vec<ScriptFile> {
200 let mut out = Vec::new();
201 walk(&self.dir, &self.dir, &mut out);
202 out.sort_by(|a, b| a.path.cmp(&b.path));
203 out
204 }
205
206 pub fn write(&self, relative: &str, text: &str) -> Result<(), Error> {
208 let path = self.resolve(relative)?;
209 if let Some(parent) = path.parent() {
210 fs::create_dir_all(parent).map_err(Error::internal)?;
211 }
212 let temp = path.with_extension("js.tmp");
213 fs::write(&temp, text).map_err(Error::internal)?;
214 fs::rename(&temp, &path).map_err(Error::internal)?;
215 self.forget(&path);
216 Ok(())
217 }
218
219 pub fn delete(&self, relative: &str) -> Result<(), Error> {
220 let path = self.resolve(relative)?;
221 match fs::remove_file(&path) {
222 Ok(()) => {}
223 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
224 Err(error) => return Err(Error::internal(error)),
225 }
226 self.forget(&path);
227 Ok(())
228 }
229
230 fn forget(&self, path: &Path) {
231 self.cache
232 .lock()
233 .unwrap_or_else(|e| e.into_inner())
234 .remove(path);
235 }
236}
237
238fn walk(root: &Path, dir: &Path, out: &mut Vec<ScriptFile>) {
239 let Ok(entries) = fs::read_dir(dir) else { return };
240 for entry in entries.flatten() {
241 let path = entry.path();
242 let name = entry.file_name();
243 if name.to_string_lossy().starts_with('.') {
244 continue; }
246 let Ok(meta) = entry.metadata() else { continue };
247 if meta.is_dir() {
248 walk(root, &path, out);
249 } else if path.extension().is_some_and(|e| e == "js") {
250 let relative = path
251 .strip_prefix(root)
252 .map(|p| p.to_string_lossy().replace('\\', "/"))
253 .unwrap_or_default();
254 let modified = meta
255 .modified()
256 .ok()
257 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
258 .map(|d| d.as_secs())
259 .unwrap_or(0);
260 out.push(ScriptFile { path: relative, size: meta.len(), modified });
261 }
262 }
263}
264
265pub enum HookResult {
267 Absent,
270 Returned(engine::Success),
271 Refused(engine::Failure),
272}
273
274pub fn run(db: &Db, user: &User, relative: &str, function: &str, input: &Value) -> Result<HookResult, Error> {
280 let Some(source) = db.scripts().source(relative)? else {
281 return Ok(HookResult::Absent);
282 };
283 Ok(run_source(db, user, &source, relative, function, input))
284}
285
286pub fn run_source(db: &Db, user: &User, source: &str, name: &str, function: &str, input: &Value) -> HookResult {
288 let host = host::Host::new(db.clone(), user.clone());
289 match engine::call(source, name, function, input, &|context, _| host.install(context)) {
290 Ok(success) => HookResult::Returned(success),
291 Err(failure) => {
292 for line in &failure.logs {
293 eprintln!("brep-plm: script {name}: {line}");
294 }
295 eprintln!("brep-plm: script {name}: {function}() refused: {}", failure.message);
296 HookResult::Refused(failure)
297 }
298 }
299}
300
301pub fn user_json(user: &User) -> Value {
303 serde_json::json!({
304 "id": user.id,
305 "username": user.username,
306 "display_name": user.display_name,
307 "email": user.email,
308 "groups": user.groups,
309 })
310}
311
312pub fn string_answer(value: &Value, field: &str) -> Option<String> {
315 match value {
316 Value::String(text) => Some(text.clone()),
317 Value::Object(map) => map.get(field).and_then(|v| v.as_str()).map(str::to_string),
318 _ => None,
319 }
320}