Skip to main content

brep_plm/scripting/
host.rs

1//! The server's host bindings: what a fully trusted script can reach.
2//!
3//! The operator's call: scripts are written by
4//! administrators and are trusted with EVERYTHING — the network, the PLM, the
5//! server's file system and child processes. There is no allowlist. These
6//! bindings are server-only; the interpreter core in [`super::engine`] does not
7//! depend on them, so the CAD app can later embed the core with its own host.
8//!
9//! | Global | Function | Returns |
10//! | --- | --- | --- |
11//! | `http` | `request(url or { url, method, headers, body, timeoutMs })` | `{ status, headers, body, json }` |
12//! | `fs` | `readFile(path)`, `writeFile(path, text)`, `exists(path)`, `listDir(path)` | text / nothing / bool / names |
13//! | `process` | `run(command, args?, { cwd, stdin }?)` | `{ status, stdout, stderr }` |
14//! | `plm` | `user`, `part(idOrNumber)`, `findParts(query)`, `partTypes()`, `readDocument(part, revision)`, `updatePart(part, fields)`, `manufacturers()`, `suppliers()`, `addManufacturerPart(part, fields)`, `addOffer(part, mpId, fields)`, `bom(part, revision, { levels, flat })`, `whereUsed(part, revision?, levels?)`, `attachments(part, revision?)` | JSON |
15//!
16//! Every call is synchronous — a Boa host function cannot await. An HTTP call
17//! carries its own timeout (default [`HTTP_TIMEOUT_MS`]) because nothing else
18//! bounds it; a child process is bounded by nothing but itself. A relative
19//! file path, and a child's default working directory, is the scripts
20//! directory.
21//!
22//! `plm.*` goes through the ordinary [`Db`] methods, each taking the store lock
23//! itself for its own moment. That is safe only because hooks never run while
24//! the lock is held (see [`crate::db`]); a binding here must never be called
25//! from inside [`Db::mutate`].
26
27use std::io::Write;
28use base64::Engine;
29use std::path::PathBuf;
30use std::process::{Command, Stdio};
31use std::time::Duration;
32
33use boa_engine::object::ObjectInitializer;
34use boa_engine::property::Attribute;
35use boa_engine::{js_string, Context, JsError, JsNativeError, JsResult, JsValue, NativeFunction};
36use serde_json::{json, Value};
37
38use crate::db::Db;
39use crate::model::User;
40
41/// How long an `http.request` waits when the script does not say.
42pub const HTTP_TIMEOUT_MS: u64 = 30_000;
43
44/// The bindings for one hook call: the store, and who the call acts for.
45#[derive(Clone)]
46pub struct Host {
47    db: Db,
48    user: User,
49}
50
51type Binding = fn(&Host, &[JsValue], &mut Context) -> JsResult<JsValue>;
52
53impl Host {
54    pub fn new(db: Db, user: User) -> Self {
55        Host { db, user }
56    }
57
58    fn function(&self, body: Binding) -> NativeFunction {
59        let host = self.clone();
60        // SAFETY: the closure captures a `Host` — an `Arc`-backed store handle
61        // and a plain user record — and a function pointer. None of it holds a
62        // garbage-collected value, so the collector has nothing in it to trace.
63        unsafe { NativeFunction::from_closure(move |_, args, context| body(&host, args, context)) }
64    }
65
66    /// Define `http`, `fs`, `process` and `plm` on the global object.
67    pub fn install(&self, context: &mut Context) -> JsResult<()> {
68        let http = ObjectInitializer::new(context)
69            .function(self.function(http_request), js_string!("request"), 1)
70            .build();
71        context.register_global_property(js_string!("http"), http, Attribute::all())?;
72
73        let files = ObjectInitializer::new(context)
74            .function(self.function(fs_read), js_string!("readFile"), 1)
75            .function(self.function(fs_read_base64), js_string!("readBase64"), 1)
76            .function(self.function(fs_write), js_string!("writeFile"), 2)
77            .function(self.function(fs_exists), js_string!("exists"), 1)
78            .function(self.function(fs_list), js_string!("listDir"), 1)
79            .build();
80        context.register_global_property(js_string!("fs"), files, Attribute::all())?;
81
82        let process = ObjectInitializer::new(context)
83            .function(self.function(process_run), js_string!("run"), 1)
84            .build();
85        context.register_global_property(js_string!("process"), process, Attribute::all())?;
86
87        let user = JsValue::from_json(&super::user_json(&self.user), context)?;
88        let plm = ObjectInitializer::new(context)
89            .property(js_string!("user"), user, Attribute::all())
90            .function(self.function(plm_part), js_string!("part"), 1)
91            .function(self.function(plm_find), js_string!("findParts"), 1)
92            .function(self.function(plm_types), js_string!("partTypes"), 0)
93            .function(self.function(plm_read_document), js_string!("readDocument"), 2)
94            .function(self.function(plm_update_part), js_string!("updatePart"), 2)
95            .function(self.function(plm_manufacturers), js_string!("manufacturers"), 0)
96            .function(self.function(plm_suppliers), js_string!("suppliers"), 0)
97            .function(self.function(plm_add_manufacturer_part), js_string!("addManufacturerPart"), 2)
98            .function(self.function(plm_add_offer), js_string!("addOffer"), 3)
99            .function(self.function(plm_bom), js_string!("bom"), 3)
100            .function(self.function(plm_where_used), js_string!("whereUsed"), 3)
101            .function(self.function(plm_attachments), js_string!("attachments"), 2)
102            .build();
103        context.register_global_property(js_string!("plm"), plm, Attribute::all())?;
104        Ok(())
105    }
106
107    fn path(&self, text: &str) -> PathBuf {
108        let path = PathBuf::from(text);
109        if path.is_absolute() {
110            path
111        } else {
112            self.db.scripts().dir().join(path)
113        }
114    }
115}
116
117// ---------------------------------------------------------------- helpers
118
119fn throw(message: impl Into<String>) -> JsError {
120    JsNativeError::error().with_message(message.into()).into()
121}
122
123fn arg_json(args: &[JsValue], index: usize, context: &mut Context) -> JsResult<Value> {
124    match args.get(index) {
125        None => Ok(Value::Null),
126        Some(value) => Ok(value.to_json(context)?.unwrap_or(Value::Null)),
127    }
128}
129
130fn arg_string(args: &[JsValue], index: usize, what: &str, context: &mut Context) -> JsResult<String> {
131    match args.get(index) {
132        Some(value) if !value.is_undefined() && !value.is_null() => {
133            Ok(value.to_string(context)?.to_std_string_escaped())
134        }
135        _ => Err(throw(format!("{what} is required"))),
136    }
137}
138
139fn to_js(value: &Value, context: &mut Context) -> JsResult<JsValue> {
140    JsValue::from_json(value, context)
141}
142
143fn plm_error(error: crate::Error) -> JsError {
144    throw(error.message)
145}
146
147// ------------------------------------------------------------------ http
148
149fn http_request(_: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
150    let options = match arg_json(args, 0, context)? {
151        Value::String(url) => json!({ "url": url }),
152        Value::Object(map) => Value::Object(map),
153        _ => return Err(throw("http.request needs a URL or { url, method, headers, body, timeoutMs }")),
154    };
155    let url = options["url"].as_str().ok_or_else(|| throw("http.request: url is required"))?.to_string();
156    let method = options["method"].as_str().unwrap_or("GET").to_ascii_uppercase();
157    let timeout = options["timeoutMs"].as_u64().unwrap_or(HTTP_TIMEOUT_MS);
158
159    let agent = ureq::AgentBuilder::new()
160        .timeout(Duration::from_millis(timeout))
161        .build();
162    let mut request = agent.request(&method, &url);
163    let mut has_content_type = false;
164    if let Some(headers) = options["headers"].as_object() {
165        for (name, value) in headers {
166            let value = value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string());
167            has_content_type |= name.eq_ignore_ascii_case("content-type");
168            request = request.set(name, &value);
169        }
170    }
171    let result = if let Some(encoded) = options.get("body_base64") {
172        if !options["body"].is_null() { return Err(throw("choose body or body_base64, not both")); }
173        let bytes = base64::engine::general_purpose::STANDARD.decode(encoded.as_str().ok_or_else(||throw("body_base64 must be a string"))?)
174            .map_err(|_|throw("body_base64 is not valid base64"))?;
175        request.send_bytes(&bytes)
176    } else { match &options["body"] {
177        Value::Null => request.call(),
178        Value::String(text) => request.send_string(text),
179        other => {
180            if !has_content_type {
181                request = request.set("Content-Type", "application/json");
182            }
183            request.send_string(&other.to_string())
184        }
185    }
186    };
187    let response = match result {
188        Ok(response) => response,
189        // A non-2xx answer is still an answer: the script decides what 404
190        // means. Only a transport failure throws.
191        Err(ureq::Error::Status(_, response)) => response,
192        Err(error) => return Err(throw(format!("{method} {url}: {error}"))),
193    };
194    let status = response.status();
195    let mut headers = serde_json::Map::new();
196    for name in response.headers_names() {
197        if let Some(value) = response.header(&name) {
198            headers.insert(name.to_ascii_lowercase(), Value::String(value.to_string()));
199        }
200    }
201    let body = response
202        .into_string()
203        .map_err(|e| throw(format!("{method} {url}: reading the body failed: {e}")))?;
204    let parsed = serde_json::from_str::<Value>(&body).unwrap_or(Value::Null);
205    to_js(&json!({ "status": status, "headers": headers, "body": body, "json": parsed }), context)
206}
207
208// -------------------------------------------------------------------- fs
209
210fn fs_read_base64(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
211    let path = host.path(&arg_string(args, 0, "fs.readBase64: path", context)?);
212    let bytes = std::fs::read(&path).map_err(|e| throw(format!("fs.readBase64 {}: {e}", path.display())))?;
213    Ok(JsValue::from(js_string!(base64::engine::general_purpose::STANDARD.encode(bytes))))
214}
215
216fn fs_read(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
217    let path = host.path(&arg_string(args, 0, "fs.readFile: path", context)?);
218    let text = std::fs::read_to_string(&path).map_err(|e| throw(format!("fs.readFile {}: {e}", path.display())))?;
219    Ok(JsValue::from(boa_engine::JsString::from(text)))
220}
221
222fn fs_write(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
223    let path = host.path(&arg_string(args, 0, "fs.writeFile: path", context)?);
224    let text = arg_string(args, 1, "fs.writeFile: text", context)?;
225    if let Some(parent) = path.parent() {
226        std::fs::create_dir_all(parent).map_err(|e| throw(format!("fs.writeFile {}: {e}", path.display())))?;
227    }
228    std::fs::write(&path, text).map_err(|e| throw(format!("fs.writeFile {}: {e}", path.display())))?;
229    Ok(JsValue::undefined())
230}
231
232fn fs_exists(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
233    let path = host.path(&arg_string(args, 0, "fs.exists: path", context)?);
234    Ok(JsValue::from(path.exists()))
235}
236
237fn fs_list(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
238    let path = host.path(&arg_string(args, 0, "fs.listDir: path", context)?);
239    let mut names: Vec<String> = std::fs::read_dir(&path)
240        .map_err(|e| throw(format!("fs.listDir {}: {e}", path.display())))?
241        .flatten()
242        .map(|entry| entry.file_name().to_string_lossy().into_owned())
243        .collect();
244    names.sort();
245    to_js(&json!(names), context)
246}
247
248// --------------------------------------------------------------- process
249
250fn process_run(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
251    let program = arg_string(args, 0, "process.run: command", context)?;
252    let arguments: Vec<String> = match arg_json(args, 1, context)? {
253        Value::Array(items) => items
254            .into_iter()
255            .map(|v| v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string()))
256            .collect(),
257        Value::Null => Vec::new(),
258        _ => return Err(throw("process.run: args must be an array of strings")),
259    };
260    let options = arg_json(args, 2, context)?;
261    let cwd = options["cwd"]
262        .as_str()
263        .map(|c| host.path(c))
264        .unwrap_or_else(|| host.db.scripts().dir().to_path_buf());
265    let stdin = options["stdin"].as_str().map(str::to_string);
266
267    let mut command = Command::new(&program);
268    command
269        .args(&arguments)
270        .current_dir(&cwd)
271        .stdout(Stdio::piped())
272        .stderr(Stdio::piped())
273        .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() });
274    let mut child = command.spawn().map_err(|e| throw(format!("process.run {program}: {e}")))?;
275    if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
276        // Written on its own thread so a child that fills its stdout before
277        // reading all of stdin cannot deadlock against us.
278        std::thread::spawn(move || {
279            let _ = pipe.write_all(text.as_bytes());
280        });
281    }
282    let output = child
283        .wait_with_output()
284        .map_err(|e| throw(format!("process.run {program}: {e}")))?;
285    to_js(
286        &json!({
287            "status": output.status.code(),
288            "stdout": String::from_utf8_lossy(&output.stdout),
289            "stderr": String::from_utf8_lossy(&output.stderr),
290        }),
291        context,
292    )
293}
294
295// ------------------------------------------------------------------- plm
296
297fn plm_part(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
298    let key = arg_string(args, 0, "plm.part: id or number", context)?;
299    let part = host.db.read(|state| state.part_by_id_or_number(&key).cloned());
300    match part {
301        Some(part) => to_js(&serde_json::to_value(part).map_err(|e| throw(e.to_string()))?, context),
302        None => Ok(JsValue::null()),
303    }
304}
305
306fn plm_find(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
307    let query = match args.first() {
308        Some(value) if !value.is_undefined() && !value.is_null() => value.to_string(context)?.to_std_string_escaped(),
309        _ => String::new(),
310    };
311    let rows = host.db.search_parts(&query);
312    let rows: Vec<Value> = rows
313        .iter()
314        .map(|part| {
315            let latest = part.latest();
316            json!({
317                "id": part.id,
318                "number": part.number,
319                "name": part.name,
320                "part_type": part.part_type,
321                "category": part.category,
322                "tags": part.tags,
323                "attributes": part.attributes,
324                "mpns": part.sourcing.iter().map(|mp| mp.mpn.clone()).collect::<Vec<_>>(),
325                "external_ref": part.external_ref,
326                "document_class": part.document_class,
327                "latest_label": latest.map(|r| r.label.clone()),
328                "latest_state": latest.map(|r| r.lifecycle.as_str()),
329            })
330        })
331        .collect();
332    to_js(&Value::Array(rows), context)
333}
334
335fn plm_types(host: &Host, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
336    let types = host.db.read(|state| serde_json::to_value(&state.part_types));
337    to_js(&types.map_err(|e| throw(e.to_string()))?, context)
338}
339
340fn plm_read_document(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
341    let key = arg_string(args, 0, "plm.readDocument: part", context)?;
342    let revision = arg_string(args, 1, "plm.readDocument: revision label or id", context)?;
343    let document_key = host
344        .db
345        .read(|state| {
346            let part = state.part_by_id_or_number(&key)?;
347            let rev = part
348                .revision(&revision)
349                .or_else(|| part.revision_by_label(&revision))?;
350            Some(rev.document_key(&part.id))
351        })
352        .ok_or_else(|| throw(format!("plm.readDocument: no revision '{revision}' of '{key}'")))?;
353    match host.db.read_document(&document_key).map_err(plm_error)? {
354        Some(text) => Ok(JsValue::from(boa_engine::JsString::from(text))),
355        None => Ok(JsValue::null()),
356    }
357}
358
359fn plm_update_part(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
360    let key = arg_string(args, 0, "plm.updatePart: part", context)?;
361    let fields = arg_json(args, 1, context)?;
362    let part = host.db.update_part(&key, &fields).map_err(plm_error)?;
363    to_js(&serde_json::to_value(part).map_err(|e| throw(e.to_string()))?, context)
364}
365
366fn plm_companies(host: &Host, which: crate::sourcing::Companies, context: &mut Context) -> JsResult<JsValue> {
367    let list = host.db.read(|state| serde_json::to_value(which.list(state)));
368    to_js(&list.map_err(|e| throw(e.to_string()))?, context)
369}
370
371fn plm_manufacturers(host: &Host, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
372    plm_companies(host, crate::sourcing::Companies::Manufacturers, context)
373}
374
375fn plm_suppliers(host: &Host, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
376    plm_companies(host, crate::sourcing::Companies::Suppliers, context)
377}
378
379fn plm_add_manufacturer_part(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
380    let key = arg_string(args, 0, "plm.addManufacturerPart: part", context)?;
381    let fields = arg_json(args, 1, context)?;
382    let mp = host.db.add_manufacturer_part(&key, &fields).map_err(plm_error)?;
383    to_js(&serde_json::to_value(mp).map_err(|e| throw(e.to_string()))?, context)
384}
385
386fn plm_add_offer(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
387    let key = arg_string(args, 0, "plm.addOffer: part", context)?;
388    let mp = arg_string(args, 1, "plm.addOffer: manufacturer part id", context)?;
389    let fields = arg_json(args, 2, context)?;
390    let offer = host.db.add_offer(&key, &mp, &fields).map_err(plm_error)?;
391    to_js(&serde_json::to_value(offer).map_err(|e| throw(e.to_string()))?, context)
392}
393
394fn plm_bom(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
395    let key = arg_string(args, 0, "plm.bom: part", context)?;
396    let revision = arg_string(args, 1, "plm.bom: revision label or id", context)?;
397    let options = arg_json(args, 2, context)?;
398    let levels = options.get("levels").and_then(Value::as_u64).unwrap_or(0) as usize;
399    let flat = options.get("flat").and_then(Value::as_bool).unwrap_or(false);
400    let bom = host.db.read(|state| {
401        let part = state.part_by_id_or_number(&key)?;
402        let rev = crate::bom::find_revision(part, &revision)?;
403        Some(crate::bom::bom(state, part, rev, levels, flat))
404    });
405    let bom = bom.ok_or_else(|| throw(format!("plm.bom: no revision '{revision}' of '{key}'")))?;
406    to_js(&serde_json::to_value(bom).map_err(|e| throw(e.to_string()))?, context)
407}
408
409fn plm_where_used(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
410    let key = arg_string(args, 0, "plm.whereUsed: part", context)?;
411    let revision = match args.get(1) {
412        Some(value) if !value.is_undefined() && !value.is_null() => value.to_string(context)?.to_std_string_escaped(),
413        _ => String::new(),
414    };
415    let levels = arg_json(args, 2, context)?.as_u64().unwrap_or(0) as usize;
416    let answer = host.db.read(|state| {
417        let part = state.part_by_id_or_number(&key).ok_or_else(|| format!("plm.whereUsed: no part '{key}'"))?;
418        let rev = match revision.trim() {
419            "" => None,
420            label => Some(
421                crate::bom::find_revision(part, label)
422                    .ok_or_else(|| format!("plm.whereUsed: no revision '{label}' of '{key}'"))?,
423            ),
424        };
425        Ok::<_, String>(crate::bom::where_used(state, part, rev, levels))
426    });
427    let answer = answer.map_err(throw)?;
428    to_js(&serde_json::to_value(answer).map_err(|e| throw(e.to_string()))?, context)
429}
430
431/// A part's attachments, or one revision's: each record with `path`, the
432/// blob's absolute path, so a (fully trusted) script can read the bytes with
433/// `fs.readFile` or hand them to `process.run`.
434fn plm_attachments(host: &Host, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
435    let key = arg_string(args, 0, "plm.attachments: part", context)?;
436    let revision = match args.get(1) {
437        Some(value) if !value.is_undefined() && !value.is_null() => value.to_string(context)?.to_std_string_escaped(),
438        _ => String::new(),
439    };
440    let list = host.db.read(|state| {
441        let part = state.part_by_id_or_number(&key).ok_or_else(|| format!("plm.attachments: no part '{key}'"))?;
442        let files = match revision.trim() {
443            "" => part.attachments.clone(),
444            label => crate::bom::find_revision(part, label)
445                .ok_or_else(|| format!("plm.attachments: no revision '{label}' of '{key}'"))?
446                .attachments
447                .clone(),
448        };
449        Ok::<_, String>(files)
450    });
451    let list = list.map_err(throw)?;
452    let with_paths: Vec<serde_json::Value> = list
453        .iter()
454        .map(|a| {
455            let mut v = serde_json::to_value(a).unwrap_or_default();
456            v["path"] = serde_json::json!(host.db.blob_path(&a.sha256).display().to_string());
457            v
458        })
459        .collect();
460    to_js(&serde_json::Value::Array(with_paths), context)
461}