1use std::collections::{HashMap, VecDeque};
4use std::io::{BufRead, BufReader, Read, Write};
5use std::path::{Path, PathBuf};
6use std::process::{Child, ChildStdin, Command, Stdio};
7use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
8use std::sync::{Arc, Mutex};
9use std::thread::JoinHandle;
10use std::time::{Duration, Instant};
11
12use brrrty_js::Value;
13use brrrty_js::runtime::{Decoded, FnHandle, JsError, JsResult, JsRuntime, RuntimeFailure};
14use serde_json::{Value as Json, json};
15
16use crate::decode::decode;
17use crate::find::NodeInfo;
18
19const WORKER_SOURCE: &str = concat!(
22 include_str!("worker/encode.mjs"),
23 "\n",
24 include_str!("worker/proxy.mjs"),
25 "\n",
26 include_str!("worker/main.mjs"),
27);
28
29const ELEVENTY_VERSION: &str = "3.1.8";
31
32const REPLY_STACK: usize = 32 * 1024 * 1024;
34
35const STDERR_TAIL: usize = 20;
37
38const STDERR_GRACE: Duration = Duration::from_millis(200);
41
42const POLL: Duration = Duration::from_millis(100);
44
45const FIRST_NOTE: Duration = Duration::from_secs(10);
47const NEXT_NOTE: Duration = Duration::from_secs(30);
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum RunMode {
52 Build,
53 Serve,
54}
55
56impl RunMode {
57 fn as_str(self) -> &'static str {
58 match self {
59 RunMode::Build => "build",
60 RunMode::Serve => "serve",
61 }
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct WorkerError(pub String);
68
69impl std::fmt::Display for WorkerError {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 f.write_str(&self.0)
72 }
73}
74
75type Reply = Result<Frame, String>;
78
79struct Frame {
80 head: Json,
82 ok: Option<Result<Decoded, String>>,
84}
85
86pub struct Worker {
89 child: Child,
90 stdin: Option<ChildStdin>,
91 replies: Receiver<Reply>,
92 stderr_tail: Arc<Mutex<VecDeque<String>>>,
93 stderr_thread: Option<JoinHandle<()>>,
94 root: PathBuf,
95 next_id: u64,
96 failed: Option<RuntimeFailure>,
98 last_loaded: HashMap<(bool, PathBuf), Decoded>,
100 earlier: Option<Decoded>,
102 notes: Box<dyn Fn(&str) + Send>,
104 note_times: (Duration, Duration),
106}
107
108impl Worker {
109 pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
112 let mut cmd = Command::new(&node.path);
113 cmd.args(["--input-type=module", "--eval", WORKER_SOURCE])
114 .current_dir(root)
115 .env("ELEVENTY_ROOT", root)
116 .env("ELEVENTY_SOURCE", "cli")
117 .env("ELEVENTY_RUN_MODE", run_mode.as_str())
118 .env("ELEVENTY_VERSION", ELEVENTY_VERSION)
119 .stdin(Stdio::piped());
120 let cannot =
121 |e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
122 let (mut child, frames, stderr) = spawn(cmd).map_err(cannot)?;
123 live(child.id(), true);
124 let (tx, replies) = mpsc::channel();
125 std::thread::Builder::new()
129 .name("brrrty-node-replies".into())
130 .stack_size(REPLY_STACK)
131 .spawn(move || read_frames(frames, tx))
132 .map_err(|e| {
133 let _ = child.kill();
134 let _ = child.wait();
135 WorkerError(format!("cannot read Node's replies: {e}"))
136 })?;
137 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
138 let tail = stderr_tail.clone();
139 let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
140 Ok(Worker {
141 stdin: child.stdin.take(),
142 child,
143 replies,
144 stderr_tail,
145 stderr_thread: Some(stderr_thread),
146 root: root.to_path_buf(),
147 next_id: 0,
148 failed: None,
149 last_loaded: HashMap::new(),
150 earlier: None,
151 notes: Box::new(|s| eprintln!("{s}")),
152 note_times: (FIRST_NOTE, NEXT_NOTE),
153 })
154 }
155
156 pub fn set_notes(
159 &mut self,
160 notes: impl Fn(&str) + Send + 'static,
161 first: Duration,
162 next: Duration,
163 ) {
164 self.notes = Box::new(notes);
165 self.note_times = (first, next);
166 }
167
168 pub fn pid(&self) -> u32 {
170 self.child.id()
171 }
172
173 pub fn root(&self) -> &Path {
175 &self.root
176 }
177
178 fn request(&mut self, mut req: Json, what: &str) -> JsResult<Decoded> {
181 if let Some(f) = &self.failed {
182 return JsResult::Failed(f.clone());
183 }
184 self.next_id += 1;
185 let id = self.next_id;
186 req["id"] = json!(id);
187 let mut line = req.to_string();
188 line.push('\n');
189 let sent = self
190 .stdin
191 .as_mut()
192 .map(|s| s.write_all(line.as_bytes()).and_then(|_| s.flush()));
193 if !matches!(sent, Some(Ok(()))) {
194 return JsResult::Failed(self.fail("Node stopped reading requests"));
195 }
196 let start = Instant::now();
197 let mut next_note = start + self.note_times.0;
198 let mut exited_at: Option<Instant> = None;
201 let reply = loop {
202 match self.replies.recv_timeout(POLL) {
203 Ok(r) => break r,
204 Err(RecvTimeoutError::Timeout) => {
205 let now = Instant::now();
206 if now >= next_note {
207 (self.notes)(&format!(
208 "note: still waiting on {what}, {} s",
209 start.elapsed().as_secs()
210 ));
211 next_note = now + self.note_times.1;
212 }
213 match exited_at {
214 Some(t) if now.duration_since(t) >= POLL => {
215 break Err("Node exited without replying".to_string());
216 }
217 Some(_) => {}
218 None => {
219 if matches!(self.child.try_wait(), Ok(Some(_))) {
220 exited_at = Some(now);
221 }
222 }
223 }
224 }
225 Err(RecvTimeoutError::Disconnected) => {
226 break Err("Node closed its output".to_string());
227 }
228 }
229 };
230 let Frame { head: reply, ok } = match reply {
231 Ok(r) => r,
232 Err(why) => return JsResult::Failed(self.fail(&why)),
233 };
234 if reply.get("id") != Some(&json!(id)) {
235 return JsResult::Failed(self.fail(&format!("a reply out of order: {reply}")));
236 }
237 if reply.get("changedArgument").is_some() {
238 return JsResult::Failed(self.fail(&format!(
239 "{what} changes the data 11ty hands it (the config's global data and `eleventy`), which 11ty then merges into every page's data; Brrrty can't follow that, so return the data instead"
240 )));
241 }
242 if let Some(p) = reply.get("protocol") {
243 return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
244 }
245 if let Some(t) = reply.get("thrown") {
246 return JsResult::Thrown(js_error(t, &self.root));
247 }
248 let earlier = self.earlier.take();
249 if reply.get("same").is_some() {
250 return match earlier {
251 Some(d) => JsResult::Ok(d),
252 None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
253 };
254 }
255 match ok {
256 Some(Ok(d)) => JsResult::Ok(d),
257 Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
258 None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
259 }
260 }
261
262 fn fail(&mut self, why: &str) -> RuntimeFailure {
265 drop(self.stdin.take());
266 let deadline = Instant::now() + Duration::from_secs(2);
267 let status = loop {
268 match self.child.try_wait() {
269 Ok(Some(s)) => break Some(s),
270 Ok(None) if Instant::now() < deadline => {
271 std::thread::sleep(Duration::from_millis(10))
272 }
273 _ => {
274 let _ = self.child.kill();
275 break self.child.wait().ok();
276 }
277 }
278 };
279 self.stop_group();
280 self.finish_stderr();
281 let message = match status {
282 Some(s) => match (s.code(), signal_of(&s)) {
283 (Some(code), _) => format!("Node exited with status {code} ({why})"),
284 (None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
285 _ => why.to_string(),
286 },
287 None => why.to_string(),
288 };
289 let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
290 let message = if stopped {
291 "Brrrty was stopped, and stopped Node with it".to_string()
292 } else {
293 message
294 };
295 let failure = RuntimeFailure {
296 stopped,
297 message,
298 stderr_tail: self
299 .stderr_tail
300 .lock()
301 .map(|t| t.iter().cloned().collect())
302 .unwrap_or_default(),
303 };
304 self.failed = Some(failure.clone());
305 failure
306 }
307
308 fn stop_group(&mut self) {
312 #[cfg(unix)]
313 kill_group(self.child.id());
314 live(self.child.id(), false);
315 }
316
317 fn finish_stderr(&mut self) {
320 if let Some(t) = self.stderr_thread.take() {
321 let deadline = Instant::now() + STDERR_GRACE;
322 while !t.is_finished() && Instant::now() < deadline {
323 std::thread::sleep(Duration::from_millis(5));
324 }
325 if t.is_finished() {
326 let _ = t.join();
327 }
328 }
329 }
330
331 fn shown(&self, file: &Path) -> String {
332 file.strip_prefix(&self.root)
333 .unwrap_or(file)
334 .display()
335 .to_string()
336 }
337}
338
339impl JsRuntime for Worker {
340 fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
341 match self.request(
342 json!({"op": "setArg", "value": encode(arg)}),
343 "the data argument",
344 ) {
345 JsResult::Ok(_) => JsResult::Ok(()),
346 JsResult::Thrown(e) => JsResult::Thrown(e),
347 JsResult::Failed(f) => JsResult::Failed(f),
348 }
349 }
350
351 fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
352 let what = self.shown(file);
353 let key = (call, file.to_path_buf());
354 self.earlier = self.last_loaded.get(&key).cloned();
358 let r = self.request(
359 json!({"op": "load", "path": file.to_string_lossy(), "call": call}),
360 &what,
361 );
362 if let JsResult::Ok(d) = &r {
363 self.last_loaded.insert(key, d.clone());
364 }
365 r
366 }
367
368 fn call(&mut self, f: FnHandle, args: &[Value]) -> JsResult<Decoded> {
369 let args: Vec<Json> = args.iter().map(encode).collect();
370 self.request(
371 json!({"op": "call", "handle": f.0, "args": args}),
372 "a data function",
373 )
374 }
375
376 fn vars_used(&mut self, f: FnHandle, data: &Value) -> JsResult<Vec<String>> {
377 let r = self.request(
378 json!({"op": "varsUsed", "handle": f.0, "data": encode(data)}),
379 "a computed data function",
380 );
381 match r {
382 JsResult::Ok(d) => match strings(&d.value) {
383 Some(list) => JsResult::Ok(list),
384 None => JsResult::Failed(self.fail(&format!("varsUsed gave {:?}", d.value))),
385 },
386 JsResult::Thrown(e) => JsResult::Thrown(e),
387 JsResult::Failed(f) => JsResult::Failed(f),
388 }
389 }
390
391 fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
392 match self.request(json!({"op": "reads"}), "the list of files read") {
393 JsResult::Ok(d) => match strings(&d.value) {
394 Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
395 None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
396 },
397 JsResult::Thrown(e) => JsResult::Thrown(e),
398 JsResult::Failed(f) => JsResult::Failed(f),
399 }
400 }
401}
402
403impl Drop for Worker {
404 fn drop(&mut self) {
405 if let Some(mut stdin) = self.stdin.take() {
406 let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
407 }
408 let deadline = Instant::now() + Duration::from_secs(2);
409 loop {
410 match self.child.try_wait() {
411 Ok(Some(_)) => break,
412 Ok(None) if Instant::now() < deadline => {
413 std::thread::sleep(Duration::from_millis(5))
414 }
415 _ => {
416 let _ = self.child.kill();
417 let _ = self.child.wait();
418 break;
419 }
420 }
421 }
422 self.stop_group();
423 self.finish_stderr();
424 }
425}
426
427static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
430
431static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
433
434fn live(pid: u32, running: bool) {
435 let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
436 l.retain(|p| *p != pid);
437 if running {
438 l.push(pid);
439 }
440}
441
442pub fn stop_all() {
445 STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
446 let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
447 #[cfg(unix)]
448 for pid in l.iter() {
449 kill_group(*pid);
450 }
451}
452
453#[cfg(unix)]
454fn kill_group(pid: u32) {
455 if let Ok(pid) = i32::try_from(pid) {
456 unsafe {
458 libc::killpg(pid, libc::SIGKILL);
459 }
460 }
461}
462
463#[cfg(unix)]
468fn spawn(mut cmd: Command) -> std::io::Result<(Child, std::io::PipeReader, std::io::PipeReader)> {
469 use std::os::fd::AsRawFd;
470 use std::os::unix::process::CommandExt;
471 let (frames_r, frames_w) = std::io::pipe()?;
472 let frames_w = frames_w.try_clone()?;
474 let (err_r, err_w) = std::io::pipe()?;
475 let fd = frames_w.as_raw_fd();
476 cmd.stdout(err_w.try_clone()?)
477 .stderr(err_w)
478 .env("BRRRTY_FRAMES_FD", fd.to_string())
479 .process_group(0);
481 unsafe {
484 cmd.pre_exec(move || {
485 if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
487 return Err(std::io::Error::last_os_error());
488 }
489 Ok(())
490 });
491 }
492 let child = cmd.spawn();
493 drop(cmd);
495 drop(frames_w);
496 Ok((child?, frames_r, err_r))
497}
498
499#[cfg(not(unix))]
501fn spawn(
502 mut cmd: Command,
503) -> std::io::Result<(Child, std::process::ChildStdout, std::process::ChildStderr)> {
504 let mut child = cmd
505 .stdout(Stdio::piped())
506 .stderr(Stdio::piped())
507 .env("BRRRTY_FRAMES_FD", "1")
508 .spawn()?;
509 let stdout = child.stdout.take().expect("piped stdout");
510 let stderr = child.stderr.take().expect("piped stderr");
511 Ok((child, stdout, stderr))
512}
513
514#[cfg(unix)]
515fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
516 use std::os::unix::process::ExitStatusExt;
517 s.signal()
518}
519
520#[cfg(not(unix))]
521fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
522 None
523}
524
525fn read_frames(stdout: impl Read, tx: mpsc::Sender<Reply>) {
528 let mut r = BufReader::new(stdout);
529 loop {
530 let mut header = Vec::new();
531 match r.read_until(b'\n', &mut header) {
532 Ok(0) => return,
533 Ok(_) => {}
534 Err(e) => {
535 let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
536 return;
537 }
538 }
539 let len = header
540 .strip_prefix(b"\x1eBRRRTY ")
541 .and_then(|h| h.strip_suffix(b"\n"))
542 .and_then(|n| std::str::from_utf8(n).ok())
543 .and_then(|n| n.parse::<usize>().ok());
544 let Some(len) = len else {
545 let shown = String::from_utf8_lossy(&header);
546 let _ = tx.send(Err(format!(
547 "something other than the worker wrote to its output: {:?}",
548 shown.chars().take(80).collect::<String>()
549 )));
550 return;
551 };
552 let mut body = vec![0; len];
553 if let Err(e) = r.read_exact(&mut body) {
554 let _ = tx.send(Err(format!("a cut-off reply: {e}")));
555 return;
556 }
557 let parsed = parse_reply(&body).map(|mut head| {
558 let ok = head
559 .as_object_mut()
560 .and_then(|o| o.remove("ok"))
561 .map(|v| decode(&v));
562 Frame { head, ok }
563 });
564 if tx.send(parsed).is_err() {
565 return;
566 }
567 }
568}
569
570fn strings(v: &Value) -> Option<Vec<String>> {
572 match v {
573 Value::Array(a) => a
574 .iter()
575 .map(|s| match s {
576 Value::String(s) => Some(s.to_string()),
577 _ => None,
578 })
579 .collect(),
580 _ => None,
581 }
582}
583
584fn parse_reply(body: &[u8]) -> Result<Json, String> {
586 let mut de = serde_json::Deserializer::from_slice(body);
587 de.disable_recursion_limit();
588 let v = serde::Deserialize::deserialize(&mut de)
589 .and_then(|v: Json| de.end().map(|()| v))
590 .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
591 Ok(v)
592}
593
594fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
597 let mut r = BufReader::new(stderr);
598 let mut line = Vec::new();
599 let mut err = std::io::stderr();
600 loop {
601 line.clear();
602 match r.read_until(b'\n', &mut line) {
603 Ok(0) | Err(_) => return,
604 Ok(_) => {
605 let _ = err.write_all(&line);
606 if let Ok(mut t) = tail.lock() {
607 if t.len() == STDERR_TAIL {
608 t.pop_front();
609 }
610 t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
611 }
612 }
613 }
614 }
615}
616
617fn js_error(t: &Json, root: &Path) -> JsError {
621 let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
622 let stack = s("stack");
623 let place = crate::stack::syntax_header(&s("inspect"))
624 .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
625 JsError {
626 name: s("name"),
627 message: s("message"),
628 file: place.as_ref().map(|p| p.file.clone()),
629 line: place.as_ref().map(|p| p.line),
630 column: place.and_then(|p| p.column),
631 stack,
632 }
633}
634
635pub fn encode(v: &Value) -> Json {
637 match v {
638 Value::Undefined => json!({"$u": 1}),
639 Value::Null => Json::Null,
640 Value::Bool(b) => Json::Bool(*b),
641 Value::Number(n) => {
642 if n.is_nan() {
643 json!({"$n": "NaN"})
644 } else if *n == f64::INFINITY {
645 json!({"$n": "Infinity"})
646 } else if *n == f64::NEG_INFINITY {
647 json!({"$n": "-Infinity"})
648 } else if *n == 0.0 && n.is_sign_negative() {
649 json!({"$n": "-0"})
650 } else {
651 serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
652 }
653 }
654 Value::String(s) => Json::String(s.to_string()),
655 Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
656 Value::Object(o) => {
657 json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
658 }
659 Value::Date(d) => json!({"$d": d.timestamp_millis()}),
660 }
661}