pub use brep_script_core as engine;
pub mod host;
use std::collections::HashMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use serde::Serialize;
use serde_json::Value;
use crate::db::Db;
use crate::model::User;
use crate::Error;
pub const REVISION_LABEL: &str = "revision-label.js";
pub const BEFORE_RELEASE: &str = "before-release.js";
pub const AFTER_RELEASE: &str = "after-release.js";
pub const REVIEWERS: &str = "reviewers.js";
pub const REVIEW_EVENT: &str = "review-event.js";
pub const DEFAULT_PART_NUMBER: &str = "part-number.js";
#[derive(Debug, Clone, Serialize)]
pub struct HookDoc {
pub file: &'static str,
pub function: &'static str,
pub when: &'static str,
}
pub const HOOKS: &[HookDoc] = &[
HookDoc {
file: "(named by the part type)",
function: "partNumber",
when: "creating a part of a Script-mode part type; return the number or throw to refuse",
},
HookDoc {
file: REVISION_LABEL,
function: "revisionLabel",
when: "creating a revision; return the label or throw to refuse",
},
HookDoc {
file: BEFORE_RELEASE,
function: "beforeRelease",
when: "before a release commits; throw to refuse the release",
},
HookDoc {
file: AFTER_RELEASE,
function: "afterRelease",
when: "after a release commits; a throw is reported, the release stands",
},
HookDoc {
file: REVIEWERS,
function: "reviewers",
when: "submitting a revision for review; return { reviewers, required_approvals, due } to change the round, or throw to refuse",
},
HookDoc {
file: REVIEW_EVENT,
function: "reviewEvent",
when: "after a review is opened, decided, withdrawn, changed or commented on; for notifications — a throw is reported, the event stands",
},
];
#[derive(Debug, Clone, Serialize)]
pub struct ScriptFile {
pub path: String,
pub size: u64,
pub modified: u64,
}
struct Cached {
modified: Option<SystemTime>,
len: u64,
text: Arc<str>,
}
pub struct Scripts {
dir: PathBuf,
cache: Mutex<HashMap<PathBuf, Cached>>,
}
impl Scripts {
pub fn new(dir: impl Into<PathBuf>) -> io::Result<Self> {
let dir = dir.into();
fs::create_dir_all(&dir)?;
Ok(Scripts { dir, cache: Mutex::new(HashMap::new()) })
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn resolve(&self, relative: &str) -> Result<PathBuf, Error> {
let relative = relative.trim().trim_start_matches('/');
let mut path = self.dir.clone();
let refuse = || Error::bad_request(format!("'{relative}' is not a usable script path — letters, digits, '-', '_', '.', '/' and a .js name"));
if !relative.ends_with(".js") {
return Err(refuse());
}
for segment in relative.split('/') {
if segment.is_empty()
|| segment.starts_with('.')
|| !segment
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
{
return Err(refuse());
}
path.push(segment);
}
Ok(path)
}
pub fn source(&self, relative: &str) -> Result<Option<Arc<str>>, Error> {
let path = self.resolve(relative)?;
let meta = match fs::metadata(&path) {
Ok(meta) if meta.is_file() => meta,
Ok(_) => return Ok(None),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(Error::internal(error)),
};
let modified = meta.modified().ok();
let len = meta.len();
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(hit) = cache.get(&path) {
if hit.modified == modified && hit.len == len {
return Ok(Some(hit.text.clone()));
}
}
let text: Arc<str> = match fs::read_to_string(&path) {
Ok(text) => text.into(),
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(Error::internal(error)),
};
cache.insert(path, Cached { modified, len, text: text.clone() });
Ok(Some(text))
}
pub fn list(&self) -> Vec<ScriptFile> {
let mut out = Vec::new();
walk(&self.dir, &self.dir, &mut out);
out.sort_by(|a, b| a.path.cmp(&b.path));
out
}
pub fn write(&self, relative: &str, text: &str) -> Result<(), Error> {
let path = self.resolve(relative)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(Error::internal)?;
}
crate::db::write_atomic(&path, text).map_err(Error::internal)?;
self.forget(&path);
Ok(())
}
pub fn delete(&self, relative: &str) -> Result<(), Error> {
let path = self.resolve(relative)?;
match fs::remove_file(&path) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(Error::internal(error)),
}
self.forget(&path);
Ok(())
}
fn forget(&self, path: &Path) {
self.cache
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(path);
}
}
fn walk(root: &Path, dir: &Path, out: &mut Vec<ScriptFile>) {
let Ok(entries) = fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name();
if name.to_string_lossy().starts_with('.') {
continue; }
let Ok(meta) = entry.metadata() else { continue };
if meta.is_dir() {
walk(root, &path, out);
} else if path.extension().is_some_and(|e| e == "js") {
let relative = path
.strip_prefix(root)
.map(|p| p.to_string_lossy().replace('\\', "/"))
.unwrap_or_default();
let modified = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.unwrap_or(0);
out.push(ScriptFile { path: relative, size: meta.len(), modified });
}
}
}
pub enum HookResult {
Absent,
Returned(engine::Success),
Refused(engine::Failure),
}
pub fn run(db: &Db, user: &User, relative: &str, function: &str, input: &Value) -> Result<HookResult, Error> {
let Some(source) = db.scripts().source(relative)? else {
return Ok(HookResult::Absent);
};
Ok(run_source(db, user, &source, relative, function, input))
}
pub fn run_source(db: &Db, user: &User, source: &str, name: &str, function: &str, input: &Value) -> HookResult {
let host = host::Host::new(db.clone(), user.clone());
match engine::call(source, name, function, input, &|context, _| host.install(context)) {
Ok(success) => HookResult::Returned(success),
Err(failure) => {
for line in &failure.logs {
eprintln!("brep-plm: script {name}: {line}");
}
eprintln!("brep-plm: script {name}: {function}() refused: {}", failure.message);
HookResult::Refused(failure)
}
}
}
pub fn user_json(user: &User) -> Value {
serde_json::json!({
"id": user.id,
"username": user.username,
"display_name": user.display_name,
"email": user.email,
"groups": user.groups,
})
}
pub fn string_answer(value: &Value, field: &str) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Object(map) => map.get(field).and_then(|v| v.as_str()).map(str::to_string),
_ => None,
}
}