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::{
14 Decoded, FnHandle, JsError, JsResult, JsRuntime, PageId, PathPart, Refusal, RuntimeFailure,
15 Settle, This,
16};
17use serde_json::{Value as Json, json};
18
19use crate::decode::decode;
20use crate::find::NodeInfo;
21
22const WORKER_SOURCE: &str = concat!(
25 include_str!("worker/encode.mjs"),
26 "\n",
27 include_str!("worker/proxy.mjs"),
28 "\n",
29 include_str!("worker/main.mjs"),
30);
31
32const ELEVENTY_VERSION: &str = "3.1.8";
34
35const REPLY_STACK: usize = 32 * 1024 * 1024;
37
38const STDERR_TAIL: usize = 20;
40
41const STDERR_GRACE: Duration = Duration::from_millis(200);
44
45const POLL: Duration = Duration::from_millis(100);
47
48const FIRST_NOTE: Duration = Duration::from_secs(10);
50const NEXT_NOTE: Duration = Duration::from_secs(30);
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum RunMode {
55 Build,
56 Serve,
57}
58
59impl RunMode {
60 fn as_str(self) -> &'static str {
61 match self {
62 RunMode::Build => "build",
63 RunMode::Serve => "serve",
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct WorkerError(pub String);
71
72impl std::fmt::Display for WorkerError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 f.write_str(&self.0)
75 }
76}
77
78type Reply = Result<Frame, String>;
81
82pub(crate) struct Frame {
83 pub head: Json,
85 ok: Option<Result<Decoded, String>>,
87 pub raw: Option<Json>,
90}
91
92#[derive(Clone)]
95pub(crate) struct Record {
96 pub unit: u64,
99 pub label: Arc<str>,
100 pub req: Json,
101 pub head: Json,
102 pub raw: Option<Json>,
103}
104
105pub struct Worker {
108 child: Child,
109 stdin: Option<ChildStdin>,
110 replies: Receiver<Reply>,
111 stderr_tail: Arc<Mutex<VecDeque<String>>>,
112 stderr_thread: Option<JoinHandle<()>>,
113 root: PathBuf,
114 next_id: u64,
115 failed: Option<RuntimeFailure>,
117 last_loaded: HashMap<(bool, PathBuf), Decoded>,
119 earlier: Option<Decoded>,
121 kept: Kept,
124 node: NodeInfo,
126 run_mode: RunMode,
127 pub(crate) keep_raw: Arc<std::sync::atomic::AtomicBool>,
129 load_log: Vec<Json>,
131 call_log: Vec<Record>,
133 calls_begun: bool,
135 clock: Json,
137 load_handles: u64,
139 slowest: Duration,
141 pub(crate) deadline: Option<Duration>,
144 notes: Box<dyn Fn(&str) + Send>,
146 note_times: (Duration, Duration),
148}
149
150impl Worker {
151 pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
154 let mut cmd = Command::new(&node.path);
155 cmd.args(["--input-type=module", "--eval", WORKER_SOURCE])
156 .current_dir(root)
157 .env("ELEVENTY_ROOT", root)
158 .env("ELEVENTY_SOURCE", "cli")
159 .env("ELEVENTY_RUN_MODE", run_mode.as_str())
160 .env("ELEVENTY_VERSION", ELEVENTY_VERSION)
161 .stdin(Stdio::piped());
162 let cannot =
163 |e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
164 let (mut child, frames, stderr) = spawn(cmd).map_err(cannot)?;
165 live(child.id(), true);
166 let (tx, replies) = mpsc::channel();
167 let keep_raw = Arc::new(std::sync::atomic::AtomicBool::new(false));
168 let keep = keep_raw.clone();
169 std::thread::Builder::new()
173 .name("brrrty-node-replies".into())
174 .stack_size(REPLY_STACK)
175 .spawn(move || read_frames(frames, tx, keep))
176 .map_err(|e| {
177 let _ = child.kill();
178 let _ = child.wait();
179 WorkerError(format!("cannot read Node's replies: {e}"))
180 })?;
181 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
182 let tail = stderr_tail.clone();
183 let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
184 Ok(Worker {
185 stdin: child.stdin.take(),
186 child,
187 replies,
188 stderr_tail,
189 stderr_thread: Some(stderr_thread),
190 root: root.to_path_buf(),
191 next_id: 0,
192 failed: None,
193 last_loaded: HashMap::new(),
194 earlier: None,
195 kept: Kept::default(),
196 node: node.clone(),
197 run_mode,
198 keep_raw,
199 load_log: Vec::new(),
200 call_log: Vec::new(),
201 calls_begun: false,
202 clock: Json::Array(Vec::new()),
203 load_handles: 0,
204 slowest: Duration::ZERO,
205 deadline: None,
206 notes: Box::new(|s| eprintln!("{s}")),
207 note_times: (FIRST_NOTE, NEXT_NOTE),
208 })
209 }
210
211 pub fn set_notes(
214 &mut self,
215 notes: impl Fn(&str) + Send + 'static,
216 first: Duration,
217 next: Duration,
218 ) {
219 self.notes = Box::new(notes);
220 self.note_times = (first, next);
221 }
222
223 pub fn pid(&self) -> u32 {
225 self.child.id()
226 }
227
228 pub fn root(&self) -> &Path {
230 &self.root
231 }
232
233 fn request(&mut self, req: Json, what: &str) -> JsResult<Decoded> {
236 let op = req
237 .get("op")
238 .and_then(Json::as_str)
239 .unwrap_or("")
240 .to_string();
241 let logged = !matches!(
242 op.as_str(),
243 "reads"
244 | "info"
245 | "callsBegin"
246 | "feedClock"
247 | "feedCalls"
248 | "loadsChanged"
249 | "exportsFinal"
250 | "describe"
251 );
252 if logged && !self.calls_begun {
253 self.load_log.push(req.clone());
254 }
255 let frame = match self.exchange(req.clone(), what) {
256 Ok(f) => f,
257 Err(f) => return JsResult::Failed(f),
258 };
259 if logged && self.calls_begun {
260 let (unit, label) = match brrrty_js::functions::unit() {
261 Some(u) => u,
262 None => (u64::MAX - self.call_log.len() as u64, Arc::from("")),
263 };
264 self.call_log.push(Record {
265 unit,
266 label,
267 req,
268 head: frame.head.clone(),
269 raw: frame.raw.clone(),
270 });
271 }
272 self.interpret(frame, what)
273 }
274
275 pub(crate) fn exchange(&mut self, mut req: Json, what: &str) -> Result<Frame, RuntimeFailure> {
277 if let Some(f) = &self.failed {
278 return Err(f.clone());
279 }
280 self.next_id += 1;
281 let id = self.next_id;
282 req["id"] = json!(id);
283 let mut line = req.to_string();
284 line.push('\n');
285 let sent = self
286 .stdin
287 .as_mut()
288 .map(|s| s.write_all(line.as_bytes()).and_then(|_| s.flush()));
289 if !matches!(sent, Some(Ok(()))) {
290 return Err(self.fail("Node stopped reading requests"));
291 }
292 let start = Instant::now();
293 let mut next_note = start + self.note_times.0;
294 let mut exited_at: Option<Instant> = None;
297 let reply = loop {
298 match self.replies.recv_timeout(POLL) {
299 Ok(r) => break r,
300 Err(RecvTimeoutError::Timeout) => {
301 let now = Instant::now();
302 if let Some(d) = self.deadline
303 && now.duration_since(start) > d
304 {
305 break Err(format!(
306 "{what} took more than {} s, longer than the first run allows",
307 d.as_secs()
308 ));
309 }
310 if now >= next_note {
311 (self.notes)(&format!(
312 "note: still waiting on {what}, {} s",
313 start.elapsed().as_secs()
314 ));
315 next_note = now + self.note_times.1;
316 }
317 match exited_at {
318 Some(t) if now.duration_since(t) >= POLL => {
319 break Err("Node exited without replying".to_string());
320 }
321 Some(_) => {}
322 None => {
323 if matches!(self.child.try_wait(), Ok(Some(_))) {
324 exited_at = Some(now);
325 }
326 }
327 }
328 }
329 Err(RecvTimeoutError::Disconnected) => {
330 break Err("Node closed its output".to_string());
331 }
332 }
333 };
334 self.slowest = self.slowest.max(start.elapsed());
335 let frame = match reply {
336 Ok(r) => r,
337 Err(why) => return Err(self.fail(&why)),
338 };
339 if frame.head.get("id") != Some(&json!(id)) {
340 let head = frame.head.clone();
341 return Err(self.fail(&format!("a reply out of order: {head}")));
342 }
343 Ok(frame)
344 }
345
346 fn interpret(&mut self, frame: Frame, what: &str) -> JsResult<Decoded> {
348 let Frame {
349 head: reply, ok, ..
350 } = frame;
351 if reply.get("changedArgument").is_some() {
352 return JsResult::Failed(self.fail(&format!(
353 "{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"
354 )));
355 }
356 if let Some(p) = reply.get("protocol") {
357 return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
358 }
359 if let Some(t) = reply.get("thrown") {
360 return JsResult::Thrown(js_error(t, &self.root));
361 }
362 if reply.get("dropShared").is_some() {
363 self.kept.lists.clear();
365 }
366 if let Some(r) = reply.get("refused") {
367 return JsResult::Refused(Refusal {
368 why: r.as_str().unwrap_or("").to_string(),
369 impure: reply.get("impure").and_then(Json::as_bool) == Some(true),
370 });
371 }
372 let earlier = self.earlier.take();
373 if reply.get("same").is_some() {
374 return match earlier {
375 Some(d) => JsResult::Ok(d),
376 None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
377 };
378 }
379 match ok {
380 Some(Ok(d)) => JsResult::Ok(d),
381 Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
382 None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
383 }
384 }
385
386 fn fail(&mut self, why: &str) -> RuntimeFailure {
389 drop(self.stdin.take());
390 let deadline = Instant::now() + Duration::from_secs(2);
391 let status = loop {
392 match self.child.try_wait() {
393 Ok(Some(s)) => break Some(s),
394 Ok(None) if Instant::now() < deadline => {
395 std::thread::sleep(Duration::from_millis(10))
396 }
397 _ => {
398 let _ = self.child.kill();
399 break self.child.wait().ok();
400 }
401 }
402 };
403 self.stop_group();
404 self.finish_stderr();
405 let message = match status {
406 Some(s) => match (s.code(), signal_of(&s)) {
407 (Some(code), _) => format!("Node exited with status {code} ({why})"),
408 (None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
409 _ => why.to_string(),
410 },
411 None => why.to_string(),
412 };
413 let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
414 let message = if stopped {
415 "Brrrty was stopped, and stopped Node with it".to_string()
416 } else {
417 message
418 };
419 let failure = RuntimeFailure {
420 stopped,
421 message,
422 stderr_tail: self
423 .stderr_tail
424 .lock()
425 .map(|t| t.iter().cloned().collect())
426 .unwrap_or_default(),
427 };
428 self.failed = Some(failure.clone());
429 failure
430 }
431
432 fn stop_group(&mut self) {
436 #[cfg(unix)]
437 kill_group(self.child.id());
438 live(self.child.id(), false);
439 }
440
441 fn finish_stderr(&mut self) {
444 if let Some(t) = self.stderr_thread.take() {
445 let deadline = Instant::now() + STDERR_GRACE;
446 while !t.is_finished() && Instant::now() < deadline {
447 std::thread::sleep(Duration::from_millis(5));
448 }
449 if t.is_finished() {
450 let _ = t.join();
451 }
452 }
453 }
454
455 fn shown(&self, file: &Path) -> String {
456 file.strip_prefix(&self.root)
457 .unwrap_or(file)
458 .display()
459 .to_string()
460 }
461}
462
463impl JsRuntime for Worker {
464 fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
465 match self.request(
466 json!({"op": "setArg", "value": encode(arg)}),
467 "the data argument",
468 ) {
469 JsResult::Ok(_) => JsResult::Ok(()),
470 JsResult::Thrown(e) => JsResult::Thrown(e),
471 JsResult::Refused(r) => JsResult::Refused(r),
472 JsResult::Failed(f) => JsResult::Failed(f),
473 }
474 }
475
476 fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
477 let what = self.shown(file);
478 let key = (call, file.to_path_buf());
479 self.earlier = self.last_loaded.get(&key).cloned();
483 let r = self.request(
484 json!({"op": "load", "path": file.to_string_lossy(), "call": call}),
485 &what,
486 );
487 if let JsResult::Ok(d) = &r {
488 self.last_loaded.insert(key, d.clone());
489 }
490 r
491 }
492
493 fn call(
494 &mut self,
495 f: FnHandle,
496 this: This<'_>,
497 args: &[Value],
498 settle: Settle,
499 ) -> JsResult<Decoded> {
500 let mut req = json!({"op": "call", "handle": f.0, "await": settle == Settle::Await});
501 let encoded = match this {
502 This::Value(v) => encode_all(std::iter::once(v).chain(args), Some(&mut self.kept)),
503 This::Opaque(what) => {
504 req["opaque"] = json!(what);
505 encode_all(args.iter(), Some(&mut self.kept))
506 }
507 };
508 let mut encoded = match encoded {
509 Ok(e) => e,
510 Err(why) => return JsResult::Refused(Refusal::new(why)),
511 };
512 if let This::Value(_) = this {
513 req["this"] = encoded.remove(0);
514 }
515 req["args"] = Json::Array(encoded);
516 self.request(req, "a data function")
517 }
518
519 fn page_open(
520 &mut self,
521 data: &Value,
522 traps: &[(String, String)],
523 defaults: &[String],
524 ) -> JsResult<PageId> {
525 let data = match encode_page(data, &mut self.kept) {
526 Ok(e) => e,
527 Err(why) => return JsResult::Refused(Refusal::new(why)),
528 };
529 let r = self.request(
530 json!({"op": "pageOpen", "data": data, "traps": traps, "defaults": defaults}),
531 "a page's data",
532 );
533 match r {
534 JsResult::Ok(d) => match d.value {
535 Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => JsResult::Ok(PageId(n as u64)),
536 other => JsResult::Failed(self.fail(&format!("pageOpen gave {other:?}"))),
537 },
538 JsResult::Thrown(e) => JsResult::Thrown(e),
539 JsResult::Refused(r) => JsResult::Refused(r),
540 JsResult::Failed(f) => JsResult::Failed(f),
541 }
542 }
543
544 fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
545 let r = self.request(
546 json!({"op": "pageVars", "page": page.0, "handle": f.0, "keys": keys}),
547 "a computed data function",
548 );
549 match r {
550 JsResult::Ok(d) => match strings(&d.value) {
551 Some(list) => JsResult::Ok(list),
552 None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
553 },
554 JsResult::Thrown(e) => JsResult::Thrown(e),
555 JsResult::Refused(r) => JsResult::Refused(r),
556 JsResult::Failed(f) => JsResult::Failed(f),
557 }
558 }
559
560 fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
561 self.request(
562 json!({"op": "pageCall", "page": page.0, "handle": f.0, "set": set}),
563 "a computed data function",
564 )
565 }
566
567 fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
568 let value = match encode_all(std::iter::once(value), Some(&mut self.kept)) {
569 Ok(mut e) => e.remove(0),
570 Err(why) => return JsResult::Refused(Refusal::new(why)),
571 };
572 match self.request(
573 json!({"op": "pageSet", "page": page.0, "key": key, "value": value}),
574 "a page's data",
575 ) {
576 JsResult::Ok(_) => JsResult::Ok(()),
577 JsResult::Thrown(e) => JsResult::Thrown(e),
578 JsResult::Refused(r) => JsResult::Refused(r),
579 JsResult::Failed(f) => JsResult::Failed(f),
580 }
581 }
582
583 fn page_close(&mut self, page: PageId) {
584 let _ = self.request(json!({"op": "pageClose", "page": page.0}), "a page's data");
585 }
586
587 fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
588 let d = match self.request(json!({"op": "loadsChanged"}), "the data files") {
589 JsResult::Ok(d) => d,
590 JsResult::Thrown(e) => return JsResult::Thrown(e),
591 JsResult::Refused(r) => return JsResult::Refused(r),
592 JsResult::Failed(f) => return JsResult::Failed(f),
593 };
594 let Value::Array(items) = &d.value else {
595 return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
596 };
597 let mut out = Vec::new();
598 for (i, item) in items.iter().enumerate() {
599 let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
600 return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
601 };
602 let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
603 match at {
604 [PathPart::Index(j), PathPart::Key(k), rest @ ..]
605 if *j == i && k == "value" =>
606 {
607 Some(rest.to_vec())
608 }
609 _ => None,
610 }
611 };
612 out.push((
613 PathBuf::from(&*p),
614 Decoded {
615 value,
616 functions: d
617 .functions
618 .iter()
619 .filter_map(|(at, h)| under(at).map(|a| (a, *h)))
620 .collect(),
621 refused: d
622 .refused
623 .iter()
624 .filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
625 .collect(),
626 },
627 ));
628 }
629 JsResult::Ok(out)
630 }
631
632 fn begin_calls(&mut self) -> JsResult<()> {
633 self.keep_raw
634 .store(true, std::sync::atomic::Ordering::SeqCst);
635 let frame = match self.exchange(json!({"op": "callsBegin"}), "the data files") {
636 Ok(f) => f,
637 Err(f) => return JsResult::Failed(f),
638 };
639 let raw = frame.raw.unwrap_or(Json::Null);
640 self.clock = raw.get("clock").cloned().unwrap_or(Json::Array(Vec::new()));
641 self.load_handles = raw.get("handles").and_then(Json::as_u64).unwrap_or(0);
642 self.calls_begun = true;
643 let changed: Vec<&str> = raw
644 .get("changed")
645 .and_then(Json::as_array)
646 .map(|a| a.iter().filter_map(Json::as_str).collect())
647 .unwrap_or_default();
648 if !changed.is_empty() {
649 return JsResult::Refused(Refusal {
650 why: format!(
651 "the data {} {} gave changed while template and directory data files loaded; 11ty's pages see it as it was when each page was placed, which depends on the order 11ty loads them",
652 if changed.len() == 1 { "file" } else { "files" },
653 changed.join(", ")
654 ),
655 impure: true,
656 });
657 }
658 if raw.get("protos").and_then(Json::as_bool) == Some(true) {
659 return JsResult::Refused(Refusal {
660 why: "a JavaScript data file changes one of JavaScript's built-in prototypes (`Array.prototype` and the like), which 11ty's templates use and Brrrty's don't".into(),
661 impure: true,
662 });
663 }
664 JsResult::Ok(())
665 }
666
667 fn verify(&mut self) -> JsResult<()> {
668 match self.request(json!({"op": "exportsFinal"}), "the data files' values") {
671 JsResult::Ok(_) => {}
672 other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
673 return match other {
674 JsResult::Refused(r) => JsResult::Refused(r),
675 JsResult::Failed(f) => JsResult::Failed(f),
676 _ => JsResult::Ok(()),
677 };
678 }
679 JsResult::Thrown(e) => return JsResult::Thrown(e),
680 }
681 let log = crate::replay::Log {
682 node: &self.node,
683 root: &self.root,
684 run_mode: self.run_mode,
685 loads: &self.load_log,
686 clock: &self.clock,
687 load_handles: self.load_handles,
688 calls: &self.call_log,
689 slowest: self.slowest,
690 };
691 match log.check() {
692 Ok(()) => JsResult::Ok(()),
693 Err(crate::replay::Failure::Differs(why, handle)) => {
694 let named = handle
695 .and_then(|h| {
696 self.exchange(json!({"op": "describe", "handle": h}), "a function's name")
697 .ok()
698 })
699 .and_then(|f| f.raw)
700 .and_then(|r| r.as_str().map(str::to_string))
701 .unwrap_or_else(|| "a function from JavaScript data".to_string());
702 JsResult::Refused(Refusal {
703 why: why.replace("{fn}", &named),
704 impure: true,
705 })
706 }
707 Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
708 }
709 }
710
711 fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
712 match self.request(json!({"op": "reads"}), "the list of files read") {
713 JsResult::Ok(d) => match strings(&d.value) {
714 Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
715 None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
716 },
717 JsResult::Thrown(e) => JsResult::Thrown(e),
718 JsResult::Refused(r) => JsResult::Refused(r),
719 JsResult::Failed(f) => JsResult::Failed(f),
720 }
721 }
722}
723
724impl Drop for Worker {
725 fn drop(&mut self) {
726 if let Some(mut stdin) = self.stdin.take() {
727 let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
728 }
729 let deadline = Instant::now() + Duration::from_secs(2);
730 loop {
731 match self.child.try_wait() {
732 Ok(Some(_)) => break,
733 Ok(None) if Instant::now() < deadline => {
734 std::thread::sleep(Duration::from_millis(5))
735 }
736 _ => {
737 let _ = self.child.kill();
738 let _ = self.child.wait();
739 break;
740 }
741 }
742 }
743 self.stop_group();
744 self.finish_stderr();
745 }
746}
747
748static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
751
752static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
754
755fn live(pid: u32, running: bool) {
756 let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
757 l.retain(|p| *p != pid);
758 if running {
759 l.push(pid);
760 }
761}
762
763pub fn stop_all() {
766 STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
767 let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
768 #[cfg(unix)]
769 for pid in l.iter() {
770 kill_group(*pid);
771 }
772}
773
774#[cfg(unix)]
775fn kill_group(pid: u32) {
776 if let Ok(pid) = i32::try_from(pid) {
777 unsafe {
779 libc::killpg(pid, libc::SIGKILL);
780 }
781 }
782}
783
784#[cfg(unix)]
789fn spawn(mut cmd: Command) -> std::io::Result<(Child, std::io::PipeReader, std::io::PipeReader)> {
790 use std::os::fd::AsRawFd;
791 use std::os::unix::process::CommandExt;
792 let (frames_r, frames_w) = std::io::pipe()?;
793 let frames_w = frames_w.try_clone()?;
795 let (err_r, err_w) = std::io::pipe()?;
796 let fd = frames_w.as_raw_fd();
797 cmd.stdout(err_w.try_clone()?)
798 .stderr(err_w)
799 .env("BRRRTY_FRAMES_FD", fd.to_string())
800 .process_group(0);
802 unsafe {
805 cmd.pre_exec(move || {
806 if libc::fcntl(fd, libc::F_SETFD, 0) == -1 {
808 return Err(std::io::Error::last_os_error());
809 }
810 Ok(())
811 });
812 }
813 let child = cmd.spawn();
814 drop(cmd);
816 drop(frames_w);
817 Ok((child?, frames_r, err_r))
818}
819
820#[cfg(not(unix))]
822fn spawn(
823 mut cmd: Command,
824) -> std::io::Result<(Child, std::process::ChildStdout, std::process::ChildStderr)> {
825 let mut child = cmd
826 .stdout(Stdio::piped())
827 .stderr(Stdio::piped())
828 .env("BRRRTY_FRAMES_FD", "1")
829 .spawn()?;
830 let stdout = child.stdout.take().expect("piped stdout");
831 let stderr = child.stderr.take().expect("piped stderr");
832 Ok((child, stdout, stderr))
833}
834
835#[cfg(unix)]
836fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
837 use std::os::unix::process::ExitStatusExt;
838 s.signal()
839}
840
841#[cfg(not(unix))]
842fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
843 None
844}
845
846fn read_frames(
849 stdout: impl Read,
850 tx: mpsc::Sender<Reply>,
851 keep_raw: Arc<std::sync::atomic::AtomicBool>,
852) {
853 let mut r = BufReader::new(stdout);
854 loop {
855 let mut header = Vec::new();
856 match r.read_until(b'\n', &mut header) {
857 Ok(0) => return,
858 Ok(_) => {}
859 Err(e) => {
860 let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
861 return;
862 }
863 }
864 let len = header
865 .strip_prefix(b"\x1eBRRRTY ")
866 .and_then(|h| h.strip_suffix(b"\n"))
867 .and_then(|n| std::str::from_utf8(n).ok())
868 .and_then(|n| n.parse::<usize>().ok());
869 let Some(len) = len else {
870 let shown = String::from_utf8_lossy(&header);
871 let _ = tx.send(Err(format!(
872 "something other than the worker wrote to its output: {:?}",
873 shown.chars().take(80).collect::<String>()
874 )));
875 return;
876 };
877 let mut body = vec![0; len];
878 if let Err(e) = r.read_exact(&mut body) {
879 let _ = tx.send(Err(format!("a cut-off reply: {e}")));
880 return;
881 }
882 let keep = keep_raw.load(std::sync::atomic::Ordering::SeqCst);
883 let parsed = parse_reply(&body).map(|mut head| {
884 let value = head.as_object_mut().and_then(|o| o.remove("ok"));
885 let ok = value.as_ref().map(decode);
886 let raw = if keep { value } else { None };
887 Frame { head, ok, raw }
888 });
889 if tx.send(parsed).is_err() {
890 return;
891 }
892 }
893}
894
895fn strings(v: &Value) -> Option<Vec<String>> {
897 match v {
898 Value::Array(a) => a
899 .iter()
900 .map(|s| match s {
901 Value::String(s) => Some(s.to_string()),
902 _ => None,
903 })
904 .collect(),
905 _ => None,
906 }
907}
908
909fn parse_reply(body: &[u8]) -> Result<Json, String> {
911 let mut de = serde_json::Deserializer::from_slice(body);
912 de.disable_recursion_limit();
913 let v = serde::Deserialize::deserialize(&mut de)
914 .and_then(|v: Json| de.end().map(|()| v))
915 .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
916 Ok(v)
917}
918
919fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
922 let mut r = BufReader::new(stderr);
923 let mut line = Vec::new();
924 let mut err = std::io::stderr();
925 loop {
926 line.clear();
927 match r.read_until(b'\n', &mut line) {
928 Ok(0) | Err(_) => return,
929 Ok(_) => {
930 let _ = err.write_all(&line);
931 if let Ok(mut t) = tail.lock() {
932 if t.len() == STDERR_TAIL {
933 t.pop_front();
934 }
935 t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
936 }
937 }
938 }
939 }
940}
941
942fn js_error(t: &Json, root: &Path) -> JsError {
946 let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
947 let stack = s("stack");
948 let place = crate::stack::syntax_header(&s("inspect"))
949 .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
950 JsError {
951 name: s("name"),
952 message: s("message"),
953 file: place.as_ref().map(|p| p.file.clone()),
954 line: place.as_ref().map(|p| p.line),
955 column: place.and_then(|p| p.column),
956 stack,
957 }
958}
959
960pub fn encode_all<'v>(
972 values: impl Iterator<Item = &'v Value> + Clone,
973 kept: Option<&mut Kept>,
974) -> Result<Vec<Json>, String> {
975 let mut counts: HashMap<usize, u32> = HashMap::new();
976 for v in values.clone() {
977 count(v, &mut counts, kept.as_deref());
978 }
979 let mut e = Encoder {
980 counts,
981 ids: HashMap::new(),
982 kept,
983 no_keep: None,
984 in_kept: 0,
985 };
986 values.map(|v| e.encode(v)).collect()
987}
988
989fn encode_page(data: &Value, kept: &mut Kept) -> Result<Json, String> {
992 let mut counts: HashMap<usize, u32> = HashMap::new();
993 count(data, &mut counts, Some(kept));
994 let mut e = Encoder {
995 counts,
996 ids: HashMap::new(),
997 kept: Some(kept),
998 no_keep: ptr_of(data),
999 in_kept: 0,
1000 };
1001 e.encode(data)
1002}
1003
1004pub const KEPT_LEN: usize = 8;
1007
1008#[derive(Default)]
1011pub struct Kept {
1012 lists: HashMap<usize, (Value, u64)>,
1013 next: u64,
1014}
1015
1016fn ptr_of(v: &Value) -> Option<usize> {
1017 match v {
1018 Value::Object(o) => Some(Arc::as_ptr(o) as usize),
1019 Value::Array(a) => Some(Arc::as_ptr(a) as usize),
1020 _ => None,
1021 }
1022}
1023
1024fn count(v: &Value, counts: &mut HashMap<usize, u32>, kept: Option<&Kept>) {
1027 let mut stack = vec![v];
1028 while let Some(v) = stack.pop() {
1029 let Some(p) = ptr_of(v) else { continue };
1030 let n = counts.entry(p).or_insert(0);
1031 *n += 1;
1032 if *n > 1 || kept.is_some_and(|k| k.lists.contains_key(&p)) {
1033 continue;
1034 }
1035 match v {
1036 Value::Object(o) => stack.extend(o.values()),
1037 Value::Array(a) => stack.extend(a.iter()),
1038 _ => {}
1039 }
1040 }
1041}
1042
1043struct Encoder<'k> {
1044 counts: HashMap<usize, u32>,
1045 ids: HashMap<usize, usize>,
1047 kept: Option<&'k mut Kept>,
1048 no_keep: Option<usize>,
1050 in_kept: usize,
1052}
1053
1054fn trap_reason(key: &str) -> String {
1056 match key {
1057 "templateContent" | "content" => format!(
1058 "reads `{key}` of a collection item, which 11ty fills in only as it renders pages"
1059 ),
1060 "template" => {
1061 "reads `template` of a collection item, 11ty's internal template object".to_string()
1062 }
1063 _ => format!("reads `{key}`, which Brrrty doesn't hand to JavaScript functions yet"),
1064 }
1065}
1066
1067impl Encoder<'_> {
1068 fn encode(&mut self, v: &Value) -> Result<Json, String> {
1069 let Some(p) = ptr_of(v) else {
1070 return Ok(encode(v));
1071 };
1072 let big = match v {
1073 Value::Array(a) => a.len() >= KEPT_LEN,
1074 Value::Object(o) => o.len() >= KEPT_LEN && !brrrty_js::traps::is_open_object(o),
1075 _ => false,
1076 };
1077 if big
1078 && self.no_keep != Some(p)
1079 && let Some(kept) = self.kept.as_deref_mut()
1080 {
1081 if let Some((_, id)) = kept.lists.get(&p) {
1082 return Ok(json!({"$R": id}));
1083 }
1084 let id = kept.next;
1085 kept.next += 1;
1086 kept.lists.insert(p, (v.clone(), id));
1087 self.in_kept += 1;
1091 let inner = self.inner(v);
1092 self.in_kept -= 1;
1093 return Ok(json!({"$S": [id, inner?]}));
1094 }
1095 if self.in_kept > 0 {
1096 return self.inner(v);
1097 }
1098 if let Some(id) = self.ids.get(&p) {
1099 return Ok(json!({"$r": id}));
1100 }
1101 let shared = self.counts.get(&p).copied().unwrap_or(0) > 1;
1102 let id = self.ids.len();
1103 if shared {
1104 self.ids.insert(p, id);
1105 }
1106 let inner = self.inner(v)?;
1107 Ok(if shared {
1108 json!({"$s": [id, inner]})
1109 } else {
1110 inner
1111 })
1112 }
1113
1114 fn inner(&mut self, v: &Value) -> Result<Json, String> {
1116 Ok(match v {
1117 Value::Array(a) => Json::Array(
1118 a.iter()
1119 .map(|x| self.encode(x))
1120 .collect::<Result<Vec<_>, _>>()?,
1121 ),
1122 Value::Object(o) => {
1123 if brrrty_js::traps::is_open_object(o) {
1124 return Err(
1125 "passes the whole `collections` object to a function, which Brrrty doesn't do yet; pass one collection, like `collections.post`".to_string(),
1126 );
1127 }
1128 let mut entries = Vec::with_capacity(o.len());
1129 for (k, x) in o.iter() {
1130 let item = if matches!(x, Value::Undefined)
1131 && brrrty_js::traps::TRAP_KEYS.contains(&k.as_str())
1132 {
1133 json!({"$t": trap_reason(k)})
1134 } else {
1135 self.encode(x)?
1136 };
1137 entries.push(json!([k, item]));
1138 }
1139 if let Some(keys) = brrrty_js::traps::withheld_keys(o) {
1140 for k in keys.iter().filter(|k| !o.contains_key(k.as_str())) {
1141 entries.push(json!([k, {"$t": format!("reads `{k}` of another page's `data`, which Brrrty can't supply")}]));
1142 }
1143 }
1144 json!({"$o": entries})
1145 }
1146 _ => encode(v),
1147 })
1148 }
1149}
1150
1151pub fn encode(v: &Value) -> Json {
1153 match v {
1154 Value::Undefined => json!({"$u": 1}),
1155 Value::Null => Json::Null,
1156 Value::Bool(b) => Json::Bool(*b),
1157 Value::Number(n) => {
1158 if n.is_nan() {
1159 json!({"$n": "NaN"})
1160 } else if *n == f64::INFINITY {
1161 json!({"$n": "Infinity"})
1162 } else if *n == f64::NEG_INFINITY {
1163 json!({"$n": "-Infinity"})
1164 } else if *n == 0.0 && n.is_sign_negative() {
1165 json!({"$n": "-0"})
1166 } else {
1167 serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
1168 }
1169 }
1170 Value::String(s) => Json::String(s.to_string()),
1171 Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
1172 Value::Object(o) => {
1173 json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
1174 }
1175 Value::Date(d) => json!({"$d": d.timestamp_millis()}),
1176 Value::Function(h) => json!({"$f": h.0}),
1177 }
1178}
1179
1180#[cfg(test)]
1181mod tests {
1182 use super::*;
1183
1184 fn object(n: usize) -> Value {
1185 Value::Object(Arc::new(
1186 (0..n)
1187 .map(|i| (format!("k{i}"), Value::Number(i as f64)))
1188 .collect(),
1189 ))
1190 }
1191
1192 #[test]
1193 fn big_objects_and_lists_cross_once_and_the_page_itself_never_is_kept() {
1194 let mut kept = Kept::default();
1195 let big = object(KEPT_LEN);
1196 let small = object(2);
1197 let first = encode_all([&big, &small].into_iter(), Some(&mut kept)).unwrap();
1198 assert!(first[0].get("$S").is_some(), "{}", first[0]);
1199 assert!(first[1].get("$o").is_some(), "{}", first[1]);
1200 let again = encode_all([&big].into_iter(), Some(&mut kept)).unwrap();
1201 assert_eq!(again[0], json!({"$R": 0}));
1202 let page = Value::Object(Arc::new(
1204 (0..KEPT_LEN)
1205 .map(|i| (format!("p{i}"), big.clone()))
1206 .collect(),
1207 ));
1208 let p = encode_page(&page, &mut kept).unwrap();
1209 assert!(p.get("$o").is_some(), "{p}");
1210 assert!(p.to_string().contains("\"$R\":0"), "{p}");
1211 }
1212}