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 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; }
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
258pub enum HookResult {
260 Absent,
263 Returned(engine::Success),
264 Refused(engine::Failure),
265}
266
267pub 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
279pub 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
294pub 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
305pub 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}