1use std::collections::{HashMap, VecDeque};
4use std::fmt::Write as _;
5use std::io::{BufRead, BufReader, Read, Write};
6use std::path::{Path, PathBuf};
7use std::process::{Child, ChildStdin, Command, Stdio};
8use std::sync::atomic::AtomicBool;
9use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
10use std::sync::{Arc, Mutex, MutexGuard};
11use std::thread::JoinHandle;
12use std::time::{Duration, Instant};
13
14use brrrty_js::Value;
15use brrrty_js::runtime::{
16 Begun, Decoded, FilterCall, Filters, Finished, FnHandle, JsError, JsResult, JsRuntime,
17 LoadedTemplate, Op, PageId, PageStep, PathPart, Pending, Refusal, RuntimeFailure, Settle,
18 TemplateId, This, Waited,
19};
20use serde_json::{Value as Json, json};
21
22use crate::decode::decode;
23use crate::find::NodeInfo;
24use crate::wire::{Added, Table};
25
26const WORKER_SOURCE: &str = concat!(
29 include_str!("worker/encode.mjs"),
30 "\n",
31 include_str!("worker/proxy.mjs"),
32 "\n",
33 include_str!("worker/config.mjs"),
34 "\n",
35 include_str!("worker/main.mjs"),
36);
37
38pub const SOURCE_FILE: &str = "brrrty-worker-source.mjs";
41
42fn worker_source() -> std::borrow::Cow<'static, str> {
46 #[cfg(test)]
47 {
48 let pad = tests_pad::PAD.with(|p| p.get());
49 if pad > 0 {
50 return format!("{}\n//{}\n", base_source(), "x".repeat(pad)).into();
51 }
52 }
53 std::borrow::Cow::Borrowed(base_source())
54}
55
56#[cfg(test)]
57mod tests_pad {
58 thread_local! {
59 pub(super) static PAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
61 }
62}
63
64fn base_source() -> &'static str {
65 static SOURCE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
66 let mut out = String::with_capacity(WORKER_SOURCE.len());
67 for line in WORKER_SOURCE.split('\n') {
68 if !line.trim_start().starts_with("//") {
69 out.push_str(line);
70 }
71 out.push('\n');
72 }
73 out.pop();
74 out
75 });
76 &SOURCE
77}
78
79const ELEVENTY_VERSION: &str = "3.1.8";
81
82pub(crate) const REPLY_STACK: usize = 32 * 1024 * 1024;
84
85const STDERR_TAIL: usize = 20;
87
88const STDERR_GRACE: Duration = Duration::from_millis(200);
91
92const AGAIN: usize = 16;
95
96fn logged(op: &str) -> bool {
98 !matches!(
99 op,
100 "reads" | "info" | "callsBegin" | "loadsChanged" | "exportsFinal" | "describe"
101 )
102}
103
104const PIPE_SAFE: usize = 4000;
107
108const SPIN: Duration = Duration::from_micros(60);
110
111const POLL: Duration = Duration::from_millis(100);
113
114const FIRST_NOTE: Duration = Duration::from_secs(10);
116const NEXT_NOTE: Duration = Duration::from_secs(30);
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum RunMode {
121 Build,
122 Serve,
123}
124
125impl RunMode {
126 pub fn as_str(self) -> &'static str {
127 match self {
128 RunMode::Build => "build",
129 RunMode::Serve => "serve",
130 }
131 }
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct WorkerError(pub String);
137
138impl std::fmt::Display for WorkerError {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 f.write_str(&self.0)
141 }
142}
143
144type Reply = Result<Frame, String>;
146
147pub(crate) struct Frame {
148 pub question: bool,
151 pub id: u64,
153 pub head: Json,
155 ok: Option<Result<Decoded, String>>,
157 pub body: Box<str>,
160 pub clock: Option<Box<str>>,
162 pub made: bool,
164 pub seq: u64,
167}
168
169impl Frame {
170 pub fn value(&self) -> Option<&Value> {
172 match &self.ok {
173 Some(Ok(d)) => Some(&d.value),
174 _ => None,
175 }
176 }
177}
178
179pub(crate) struct LoadRecord {
182 pub text: Box<str>,
184 pub kind: LoadKind,
187 pub path: String,
188 pub body: Box<str>,
189 pub clock: Option<Box<str>>,
190}
191
192#[derive(Clone, Copy, PartialEq, Eq)]
193pub(crate) enum LoadKind {
194 Data,
195 Template,
196 Other,
197}
198
199pub(crate) struct Record {
202 pub unit: u64,
205 pub label: Arc<str>,
206 pub op: &'static str,
207 pub handle: Option<u32>,
209 pub text: Box<str>,
212 pub body: Box<str>,
213 pub clock: Option<Box<str>>,
214 pub made: bool,
216 pub dynamic: Vec<u32>,
219 pub names_made: bool,
220 pub answers: Vec<(Box<str>, Box<str>)>,
223 pub one_way: bool,
225 pub unchecked: bool,
228 pub at: (u64, u32),
233}
234
235type Notes = Box<dyn Fn(&str) + Send>;
237
238type Planned = (Vec<Request<'static>>, Shape, Option<PageId>, &'static str);
241
242pub(crate) struct Mux {
244 child: Mutex<Child>,
245 stdin: Mutex<Option<ChildStdin>>,
246 answers: Mutex<Option<Box<dyn Write + Send>>>,
249 routes: Mutex<HashMap<u64, mpsc::Sender<Reply>>>,
252 notes: Mutex<Notes>,
254 note_times: Mutex<(Duration, Duration)>,
256}
257
258fn locked<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
259 m.lock().unwrap_or_else(|e| e.into_inner())
260}
261
262impl Mux {
263 fn next(
266 &self,
267 rx: &Receiver<Reply>,
268 what: &str,
269 wait: &mut Wait,
270 deadline: Option<Duration>,
271 ) -> Result<Frame, String> {
272 let spun = Instant::now();
275 loop {
276 match rx.try_recv() {
277 Ok(r) => return r,
278 Err(mpsc::TryRecvError::Disconnected) => break,
279 Err(mpsc::TryRecvError::Empty) if spun.elapsed() < SPIN => std::hint::spin_loop(),
280 Err(mpsc::TryRecvError::Empty) => break,
281 }
282 }
283 loop {
284 match rx.recv_timeout(POLL) {
285 Ok(r) => return r,
286 Err(RecvTimeoutError::Timeout) => {
287 let now = Instant::now();
288 if let Some(d) = deadline
289 && now.duration_since(wait.start) > d
290 {
291 return Err(format!(
292 "{what} took more than {} s, longer than the first run allows",
293 d.as_secs()
294 ));
295 }
296 if now >= wait.next_note {
297 let waiting = locked(&self.routes).len();
300 let behind = if waiting > 1 {
301 format!(
302 " ({waiting} requests are waiting on Node, which runs one at a time)"
303 )
304 } else {
305 String::new()
306 };
307 (locked(&self.notes))(&format!(
308 "note: still waiting on {what}, {} s{behind}",
309 wait.start.elapsed().as_secs()
310 ));
311 wait.next_note = now + locked(&self.note_times).1;
312 }
313 match wait.exited_at {
314 Some(t) if now.duration_since(t) >= POLL => {
315 return Err("Node exited without replying".to_string());
316 }
317 Some(_) => {}
318 None => {
319 if matches!(locked(&self.child).try_wait(), Ok(Some(_))) {
320 wait.exited_at = Some(now);
321 }
322 }
323 }
324 }
325 Err(RecvTimeoutError::Disconnected) => {
326 return Err("Node closed its output".to_string());
327 }
328 }
329 }
330 }
331
332 fn wait(&self) -> Wait {
334 let start = Instant::now();
335 Wait {
336 start,
337 next_note: start + locked(&self.note_times).0,
338 exited_at: None,
339 }
340 }
341
342 fn answer(&self, frame: &Frame, filters: &mut FilterCall<'_>) -> Result<Box<str>, String> {
345 let name = frame
346 .head
347 .get("filter")
348 .and_then(Json::as_str)
349 .unwrap_or("")
350 .to_string();
351 let args = match &frame.ok {
352 Some(Ok(d)) if d.is_exact() => match &d.value {
353 Value::Array(a) => Ok(a.to_vec()),
354 _ => Err("passes its filter something Brrrty can't read".to_string()),
355 },
356 Some(Ok(_)) => Err(format!(
357 "passes `this.{name}` a function or a value that can't cross from JavaScript to Brrrty exactly"
358 )),
359 _ => Err("passes its filter something Brrrty can't read".to_string()),
360 };
361 let reply: Box<str> = match args.and_then(|a| filters(&name, &a)) {
362 Ok(v) => json!({"ok": encode(&v)}),
363 Err(why) => json!({"refused": why}),
364 }
365 .to_string()
366 .into();
367 self.send_answer(&reply)?;
368 Ok(reply)
369 }
370
371 fn send_answer(&self, reply: &str) -> Result<(), String> {
372 match locked(&self.answers).as_mut() {
373 Some(w) => w
374 .write_all(reply.as_bytes())
375 .and_then(|_| w.write_all(b"\n"))
376 .and_then(|_| w.flush())
377 .map_err(|e| format!("cannot answer Node: {e}")),
378 None => Err("Node asked a question it can't be answered on".to_string()),
379 }
380 }
381}
382
383#[derive(Clone, Copy, PartialEq)]
385enum Shape {
386 List,
388 Once,
391 OpenWithVars,
394}
395
396struct Sent {
398 id: u64,
399 op: &'static str,
400 handle: Option<u32>,
401 text: String,
402 path: Option<String>,
403 one_way: bool,
404 made: bool,
407 dynamic: Vec<u32>,
408}
409
410pub(crate) struct Ticket {
414 mux: Arc<Mux>,
415 rx: Receiver<Reply>,
416 sent: Vec<Sent>,
417 what: String,
418 shape: Shape,
419 page: Option<PageId>,
420 deadline: Option<Duration>,
421}
422
423pub(crate) struct Done {
425 sent: Vec<Sent>,
426 frames: Vec<Frame>,
429 asked: Vec<Vec<(Box<str>, Box<str>)>>,
431 failure: Option<String>,
432 what: String,
433 shape: Shape,
434 page: Option<PageId>,
435 waited: Duration,
436}
437
438impl Ticket {
439 fn collect(self, filters: &mut FilterCall<'_>) -> Done {
441 let started = Instant::now();
442 let mut frames = Vec::with_capacity(self.sent.len());
443 let mut asked = Vec::with_capacity(self.sent.len());
444 let mut failure = None;
445 'all: for sent in self.sent.iter().filter(|s| !s.one_way) {
446 let mut wait = self.mux.wait();
447 let mut questions = Vec::new();
448 loop {
449 match self
450 .mux
451 .next(&self.rx, &self.what, &mut wait, self.deadline)
452 {
453 Ok(f) if f.question => match self.mux.answer(&f, filters) {
454 Ok(reply) => questions.push((f.body.clone(), reply)),
455 Err(why) => {
456 failure = Some(why);
457 break 'all;
458 }
459 },
460 Ok(f) if f.id != sent.id => {
461 failure = Some(format!("a reply out of order: {}", f.head));
462 break 'all;
463 }
464 Ok(f) => {
465 frames.push(f);
466 asked.push(questions);
467 break;
468 }
469 Err(why) => {
470 failure = Some(why);
471 break 'all;
472 }
473 }
474 }
475 }
476 let mut routes = locked(&self.mux.routes);
477 for sent in &self.sent {
478 routes.remove(&sent.id);
479 }
480 drop(routes);
481 Done {
482 sent: self.sent,
483 frames,
484 asked,
485 failure,
486 what: self.what,
487 shape: self.shape,
488 page: self.page,
489 waited: started.elapsed(),
490 }
491 }
492}
493
494impl Pending for Ticket {
495 fn wait(self: Box<Self>, filters: &mut FilterCall<'_>) -> Waited {
496 Waited(Box::new(self.collect(filters)))
497 }
498}
499
500pub struct Worker {
503 _source_dir: tempfile::TempDir,
505 mux: Arc<Mux>,
506 pid: u32,
507 pub(crate) answers_feed: Option<VecDeque<(Box<str>, Box<str>)>>,
509 asked: Vec<(Box<str>, Box<str>)>,
511 filters: Option<Filters>,
513 replies: Receiver<Reply>,
514 stderr_tail: Arc<Mutex<VecDeque<String>>>,
515 stderr_thread: Option<JoinHandle<()>>,
516 root: PathBuf,
517 next_id: u64,
518 next_page: u64,
519 failed: Option<RuntimeFailure>,
521 last_loaded: HashMap<(bool, PathBuf), Decoded>,
523 earlier: Option<Decoded>,
525 fixed: std::collections::HashSet<(bool, PathBuf)>,
528 last_fixed: bool,
529 last_seq: u64,
532 table: Table,
534 node: NodeInfo,
536 run_mode: RunMode,
537 pub(crate) decode: Arc<AtomicBool>,
540 load_log: Vec<LoadRecord>,
542 global_end: usize,
546 call_log: Vec<Record>,
548 dropped: bool,
550 calls_begun: bool,
552 load_handles: u64,
554 cli_dirs: (Option<String>, Option<String>),
556 replays: Option<[crate::replay::Handle; 2]>,
559 order_check: bool,
561 slowest: Duration,
563 pub(crate) deadline: Option<Duration>,
566 last_template: Option<u64>,
568 next_ticket: u64,
569 stats: Stats,
571 frozen: bool,
573 walk: Option<String>,
575 walks: Option<String>,
577}
578
579#[derive(Default)]
581struct Stats {
582 started: Option<Instant>,
583 requests: u64,
584 sent: u64,
586 defined: u64,
587 definitions: u64,
588 received: u64,
590 waited: Duration,
592}
593
594struct Request<'a> {
597 op: &'static str,
598 text: String,
600 added: Added,
602 handle: Option<u32>,
604 path: Option<&'a Path>,
606 one_way: bool,
608}
609
610impl<'a> Request<'a> {
611 fn new(op: &'static str, text: String) -> Request<'a> {
612 Request {
613 op,
614 text,
615 added: Added::default(),
616 handle: None,
617 path: None,
618 one_way: false,
619 }
620 }
621}
622
623pub(crate) struct Wait {
625 start: Instant,
626 next_note: Instant,
627 exited_at: Option<Instant>,
630}
631
632impl Worker {
633 pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
636 Worker::start_as(node, root, run_mode, None)
637 }
638
639 pub(crate) fn start_as(
641 node: &NodeInfo,
642 root: &Path,
643 run_mode: RunMode,
644 replay: Option<&crate::replay::Loads>,
645 ) -> Result<Worker, WorkerError> {
646 Worker::start_checked(node, root, run_mode, replay, true)
647 }
648
649 pub fn set_cli_dirs(&mut self, input: Option<String>, output: Option<String>) {
652 self.cli_dirs = (input, output);
653 }
654
655 pub fn start_with(
659 node: &NodeInfo,
660 root: &Path,
661 run_mode: RunMode,
662 order_check: bool,
663 ) -> Result<Worker, WorkerError> {
664 Worker::start_checked(node, root, run_mode, None, order_check)
665 }
666
667 fn start_checked(
668 node: &NodeInfo,
669 root: &Path,
670 run_mode: RunMode,
671 replay: Option<&crate::replay::Loads>,
672 order_check: bool,
673 ) -> Result<Worker, WorkerError> {
674 let walk = match replay {
677 Some(loads) => loads.walk.clone(),
678 None => walk_roots().starting(root),
679 };
680 let cannot =
684 |e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
685 let source_dir = tempfile::Builder::new()
686 .prefix("brrrty-worker-")
687 .tempdir()
688 .map_err(cannot)?;
689 let source_file = source_dir.path().join(SOURCE_FILE);
690 std::fs::write(&source_file, worker_source().as_bytes()).map_err(cannot)?;
691 let mut cmd = Command::new(&node.path);
692 cmd.arg(&source_file)
693 .current_dir(root)
694 .env("ELEVENTY_ROOT", root)
695 .env("ELEVENTY_SOURCE", "cli")
696 .env("ELEVENTY_RUN_MODE", run_mode.as_str())
697 .env("ELEVENTY_VERSION", ELEVENTY_VERSION)
698 .stdin(Stdio::piped());
699 if let Some(why) = &walk {
700 cmd.env("BRRRTY_JS_EXPORTS", "walk");
701 cmd.env("BRRRTY_JS_WALK_WHY", why);
702 } else {
703 cmd.env_remove("BRRRTY_JS_WALK_WHY");
704 }
705 if replay.is_some() {
706 cmd.env("BRRRTY_ROLE", "replay");
707 }
708 let (mut child, frames, stderr, answers) = spawn(cmd).map_err(cannot)?;
709 let pid = child.id();
710 live(pid, true);
711 let (tx, replies) = mpsc::channel();
712 let decode = Arc::new(AtomicBool::new(true));
713 let decoding = decode.clone();
714 let stdin = child.stdin.take();
715 let mux = Arc::new(Mux {
716 child: Mutex::new(child),
717 stdin: Mutex::new(stdin),
718 answers: Mutex::new(answers),
719 routes: Mutex::new(HashMap::new()),
720 notes: Mutex::new(Box::new(|s| eprintln!("{s}"))),
721 note_times: Mutex::new((FIRST_NOTE, NEXT_NOTE)),
722 });
723 let routing = mux.clone();
724 std::thread::Builder::new()
728 .name("brrrty-node-replies".into())
729 .stack_size(REPLY_STACK)
730 .spawn(move || read_frames(frames, tx, decoding, &routing))
731 .map_err(|e| {
732 let mut child = locked(&mux.child);
733 let _ = child.kill();
734 let _ = child.wait();
735 WorkerError(format!("cannot read Node's replies: {e}"))
736 })?;
737 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
738 let tail = stderr_tail.clone();
739 let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
740 Ok(Worker {
741 _source_dir: source_dir,
742 mux,
743 pid,
744 answers_feed: None,
745 asked: Vec::new(),
746 filters: None,
747 replies,
748 stderr_tail,
749 stderr_thread: Some(stderr_thread),
750 root: root.to_path_buf(),
751 next_id: 0,
752 next_page: 0,
753 failed: None,
754 last_loaded: HashMap::new(),
755 earlier: None,
756 fixed: std::collections::HashSet::new(),
757 last_fixed: false,
758 last_seq: 0,
759 table: Table::default(),
760 node: node.clone(),
761 run_mode,
762 decode,
763 load_log: Vec::new(),
764 global_end: 0,
765 call_log: Vec::new(),
766 dropped: false,
767 calls_begun: false,
768 load_handles: 0,
769 cli_dirs: (None, None),
770 replays: None,
771 order_check,
772 slowest: Duration::ZERO,
773 deadline: None,
774 last_template: None,
775 next_ticket: 0,
776 stats: Stats {
777 started: Some(Instant::now()),
778 ..Stats::default()
779 },
780 frozen: false,
781 walk,
782 walks: None,
783 })
784 }
785
786 fn open_request(
788 &mut self,
789 data: &Value,
790 traps: &[(String, String)],
791 defaults: &[String],
792 ) -> Result<(PageId, Request<'static>), String> {
793 self.next_page += 1;
794 let page = self.next_page;
795 let mut added = Added::default();
796 let mut text = String::with_capacity(1024);
797 let _ = write!(text, "{{\"op\":\"pageOpen\",\"page\":{page},\"data\":");
798 self.table.page_data(data, false, &mut text, &mut added)?;
799 text.push_str(",\"traps\":");
800 pairs(&mut text, traps);
801 text.push_str(",\"defaults\":");
802 crate::wire::strings(&mut text, defaults);
803 text.push('}');
804 Ok((
805 PageId(page),
806 Request {
807 added,
808 ..Request::new("pageOpen", text)
809 },
810 ))
811 }
812
813 pub fn set_notes(
816 &mut self,
817 notes: impl Fn(&str) + Send + 'static,
818 first: Duration,
819 next: Duration,
820 ) {
821 *locked(&self.mux.notes) = Box::new(notes);
822 *locked(&self.mux.note_times) = (first, next);
823 }
824
825 pub fn exports_frozen(&self) -> Result<(), String> {
828 if self.frozen {
829 Ok(())
830 } else {
831 Err(self.walks.clone().unwrap_or_default())
832 }
833 }
834
835 fn trace(&self, at: &str) {
837 let s = &self.stats;
838 eprintln!(
839 "note: {at}, {:.3} s after Node started: {} requests ({:.1} MB) and {} definitions ({:.1} MB) sent, {:.1} MB of replies, {:.3} s waiting on Node",
840 s.started.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0),
841 s.requests,
842 s.sent as f64 / 1e6,
843 s.definitions,
844 s.defined as f64 / 1e6,
845 s.received as f64 / 1e6,
846 s.waited.as_secs_f64(),
847 );
848 }
849
850 pub fn pid(&self) -> u32 {
852 self.pid
853 }
854
855 pub fn root(&self) -> &Path {
857 &self.root
858 }
859
860 fn request(&mut self, req: Request<'_>, what: &str) -> JsResult<Decoded> {
863 let filters = self.filters.clone();
864 self.request_with(
865 req,
866 what,
867 &mut |name: &str, args: &[Value]| match &filters {
868 Some(f) => f(name, args),
869 None => Err(format!(
870 "calls `this.{name}` where Brrrty has no filters to run it"
871 )),
872 },
873 )
874 }
875
876 fn request_with(
879 &mut self,
880 req: Request<'_>,
881 what: &str,
882 filters: &mut FilterCall<'_>,
883 ) -> JsResult<Decoded> {
884 self.requests(vec![req], what, filters)
885 .pop()
886 .unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
887 }
888
889 fn requests(
894 &mut self,
895 reqs: Vec<Request<'_>>,
896 what: &str,
897 filters: &mut FilterCall<'_>,
898 ) -> Vec<JsResult<Decoded>> {
899 let mut out = Vec::with_capacity(reqs.len());
900 let mut reqs = reqs.into_iter().peekable();
901 while reqs.peek().is_some() {
902 let mut group = Vec::new();
906 let mut ahead = 0;
907 while let Some(next) = reqs.peek() {
908 if !group.is_empty() && ahead + next.text.len() + 48 > PIPE_SAFE {
909 break;
910 }
911 if !group.is_empty() {
912 ahead += next.text.len() + 48;
913 }
914 group.extend(reqs.next());
915 }
916 let ticket = match self.send(group, what, Shape::List, None) {
917 Ok(t) => t,
918 Err(f) => {
919 out.push(JsResult::Failed(f));
920 return out;
921 }
922 };
923 let done = ticket.collect(filters);
924 match self.settle(done) {
925 Finished::Results { results, .. } => {
926 let stop = results.iter().any(|r| !matches!(r, JsResult::Ok(_)));
927 out.extend(results);
928 if stop {
929 return out;
930 }
931 }
932 Finished::Again => {
933 out.push(JsResult::Failed(
934 self.fail("the worker lost the values a request referred to"),
935 ));
936 return out;
937 }
938 }
939 }
940 out
941 }
942
943 fn fits(reqs: &[Request<'_>]) -> bool {
945 reqs.iter()
946 .skip(1)
947 .map(|r| r.text.len() + 48)
948 .sum::<usize>()
949 <= PIPE_SAFE
950 }
951
952 fn send(
955 &mut self,
956 reqs: Vec<Request<'_>>,
957 what: &str,
958 shape: Shape,
959 page: Option<PageId>,
960 ) -> Result<Ticket, RuntimeFailure> {
961 if let Some(f) = &self.failed {
962 return Err(f.clone());
963 }
964 let mut handed = false;
967 if self.calls_begun && self.replays.is_none() && reqs.iter().any(|r| logged(r.op)) {
968 self.start_replays();
969 handed = true;
970 }
971 for req in &reqs {
974 for (line, dynamic) in &req.added.lines {
975 self.stats.definitions += 1;
976 self.stats.defined += line.len() as u64;
977 self.write_line(line)?;
978 if !dynamic
979 && !handed
980 && let Some(replays) = &self.replays
981 {
982 for r in replays {
983 r.line(line.clone());
984 }
985 }
986 }
987 }
988 let (tx, rx) = mpsc::channel();
989 self.next_ticket += 1;
992 let ticket = self.next_ticket;
993 let mut lines = String::new();
994 let mut sent = Vec::with_capacity(reqs.len());
995 {
996 let mut routes = locked(&self.mux.routes);
997 for req in reqs {
998 self.next_id += 1;
999 let id = self.next_id;
1000 let _ = write!(lines, "{{\"id\":{id},\"t\":{ticket},");
1001 lines.push_str(req.text.strip_prefix('{').unwrap_or(&req.text));
1002 lines.push('\n');
1003 if !req.one_way {
1004 routes.insert(id, tx.clone());
1005 }
1006 sent.push(Sent {
1007 id,
1008 op: req.op,
1009 handle: req.handle,
1010 path: req.path.map(|p| p.to_string_lossy().into_owned()),
1011 one_way: req.one_way,
1012 made: req.added.made,
1013 dynamic: req.added.dynamic,
1014 text: req.text,
1015 });
1016 }
1017 }
1018 self.stats.sent += lines.len() as u64;
1019 let written = locked(&self.mux.stdin)
1020 .as_mut()
1021 .map(|s| s.write_all(lines.as_bytes()).and_then(|_| s.flush()));
1022 if !matches!(written, Some(Ok(()))) {
1023 return Err(self.fail("Node stopped reading requests"));
1024 }
1025 Ok(Ticket {
1026 mux: self.mux.clone(),
1027 rx,
1028 sent,
1029 what: what.to_string(),
1030 shape,
1031 page,
1032 deadline: self.deadline,
1033 })
1034 }
1035
1036 fn settle(&mut self, done: Done) -> Finished {
1039 let Done {
1040 sent,
1041 frames,
1042 asked,
1043 failure,
1044 what,
1045 shape,
1046 page,
1047 waited,
1048 } = done;
1049 self.slowest = self.slowest.max(waited);
1050 self.stats.waited += waited;
1051 let mut results: Vec<JsResult<Decoded>> = Vec::with_capacity(frames.len());
1052 let mut unchecked = false;
1055 let mut last_at = (self.last_seq, 0u32);
1057 let mut frames = frames.into_iter();
1058 let mut asked = asked.into_iter();
1059 for req in sent {
1060 let mut frame = if req.one_way {
1061 None
1062 } else {
1063 match frames.next() {
1064 Some(f) => Some(f),
1065 None => break,
1067 }
1068 };
1069 let answers = if req.one_way {
1070 Vec::new()
1071 } else {
1072 asked.next().unwrap_or_default()
1073 };
1074 if let Some(f) = &frame {
1075 self.stats.requests += 1;
1076 self.stats.received += f.body.len() as u64;
1077 if f.head.get("stale").is_some() {
1078 if results.iter().all(|r| matches!(r, JsResult::Ok(_))) {
1083 self.table.forget();
1084 return Finished::Again;
1085 }
1086 break;
1087 }
1088 if f.head.get("after").is_some() {
1091 break;
1092 }
1093 }
1094 if req.op == "templateLoad" {
1095 self.last_template = frame
1096 .as_ref()
1097 .and_then(|f| f.head.get("template"))
1098 .and_then(Json::as_u64);
1099 }
1100 if req.op == "load" {
1101 self.last_fixed = frame
1102 .as_ref()
1103 .is_some_and(|f| f.head.get("fixed").is_some());
1104 }
1105 let body = frame
1106 .as_mut()
1107 .map(|f| std::mem::take(&mut f.body))
1108 .unwrap_or_default();
1109 let clock = frame.as_mut().and_then(|f| f.clock.take());
1110 if logged(req.op) && !self.calls_begun {
1111 self.load_log.push(LoadRecord {
1112 text: req.text.into_boxed_str(),
1113 kind: match req.op {
1114 "load" => LoadKind::Data,
1115 "templateLoad" => LoadKind::Template,
1116 _ => LoadKind::Other,
1117 },
1118 path: req.path.unwrap_or_default(),
1119 body,
1120 clock,
1121 });
1122 } else if logged(req.op) && !self.order_check {
1123 let dropped = frame
1125 .as_ref()
1126 .is_some_and(|f| f.head.get("dropShared").is_some());
1127 self.dropped |= dropped;
1128 unchecked |= dropped;
1129 } else if logged(req.op) {
1130 let (unit, label) = match brrrty_js::functions::unit() {
1131 Some(u) => u,
1132 None => (u64::MAX - self.call_log.len() as u64, Arc::from("")),
1133 };
1134 let dropped = frame
1135 .as_ref()
1136 .is_some_and(|f| f.head.get("dropShared").is_some());
1137 self.dropped |= dropped;
1138 let at = match &frame {
1139 Some(f) => {
1140 self.last_seq = self.last_seq.max(f.seq);
1141 last_at = (f.seq, 0);
1142 last_at
1143 }
1144 None => {
1145 last_at.1 += 1;
1146 last_at
1147 }
1148 };
1149 self.call_log.push(Record {
1150 at,
1151 unit,
1152 label,
1153 op: req.op,
1154 handle: req.handle,
1155 text: req.text.into_boxed_str(),
1156 body,
1157 clock,
1158 made: frame.as_ref().is_some_and(|f| f.made),
1159 names_made: req.made || req.handle.is_some_and(|h| self.table.made_by_call(h)),
1160 dynamic: req.dynamic,
1161 answers,
1162 one_way: req.one_way,
1163 unchecked,
1164 });
1165 unchecked |= dropped;
1166 }
1167 let Some(frame) = frame else {
1168 continue;
1169 };
1170 let r = self.interpret(frame, &what);
1171 let failed = matches!(r, JsResult::Failed(_));
1172 results.push(r);
1173 if failed {
1174 return Finished::Results {
1175 results: vec![results.pop().expect("just pushed")],
1176 page: None,
1177 };
1178 }
1179 }
1180 if let Some(why) = failure {
1181 return Finished::Results {
1182 results: vec![JsResult::Failed(self.fail(&why))],
1183 page: None,
1184 };
1185 }
1186 self.shape(shape, page, results)
1187 }
1188
1189 fn shaped(&mut self, done: Done, results: Vec<JsResult<Decoded>>) -> Finished {
1191 self.shape(done.shape, done.page, results)
1192 }
1193
1194 fn shape(
1195 &mut self,
1196 shape: Shape,
1197 page: Option<PageId>,
1198 mut results: Vec<JsResult<Decoded>>,
1199 ) -> Finished {
1200 let bad = results.iter().position(|r| !matches!(r, JsResult::Ok(_)));
1202 match shape {
1203 Shape::List => {
1204 if let Some(bad) = bad {
1205 results.truncate(bad + 1);
1206 }
1207 Finished::Results { results, page }
1208 }
1209 Shape::Once => {
1210 let result = match bad {
1211 Some(bad) => results.swap_remove(bad),
1212 None if results.len() == 2 => results.swap_remove(1),
1214 None => JsResult::Failed(self.fail("a page's call gave no reply")),
1215 };
1216 Finished::Results {
1217 results: vec![result],
1218 page,
1219 }
1220 }
1221 Shape::OpenWithVars => match bad {
1222 Some(bad) => {
1223 if bad > 0
1224 && let Some(page) = page
1225 {
1226 self.page_close(page);
1227 }
1228 Finished::Results {
1229 results: vec![results.swap_remove(bad)],
1230 page: None,
1231 }
1232 }
1233 None => Finished::Results { results, page },
1234 },
1235 }
1236 }
1237
1238 fn op_requests(&mut self, op: Op<'_>) -> Result<Planned, String> {
1241 Ok(match op {
1242 Op::Call {
1243 f,
1244 this,
1245 args,
1246 settle,
1247 } => {
1248 let mut added = Added::default();
1249 let mut text = String::with_capacity(128);
1250 let _ = write!(
1251 text,
1252 "{{\"op\":\"call\",\"handle\":{},\"await\":{}",
1253 f.0,
1254 settle == Settle::Await
1255 );
1256 match this {
1257 This::Value(v) => {
1258 text.push_str(",\"this\":");
1259 self.table.argument(v, false, &mut text, &mut added)?;
1260 }
1261 This::Guarded(v, keys) => {
1262 text.push_str(",\"this\":");
1263 self.table.argument(v, false, &mut text, &mut added)?;
1264 text.push_str(",\"guard\":[");
1265 for (i, (k, what)) in keys.iter().enumerate() {
1266 if i > 0 {
1267 text.push(',');
1268 }
1269 text.push('[');
1270 crate::wire::string(&mut text, k);
1271 text.push(',');
1272 crate::wire::string(&mut text, what);
1273 text.push(']');
1274 }
1275 text.push(']');
1276 }
1277 This::Opaque(what) => {
1278 text.push_str(",\"opaque\":");
1279 crate::wire::string(&mut text, what);
1280 }
1281 }
1282 text.push_str(",\"args\":[");
1283 for (i, a) in args.iter().enumerate() {
1284 if i > 0 {
1285 text.push(',');
1286 }
1287 self.table.argument(a, true, &mut text, &mut added)?;
1288 }
1289 text.push(']');
1290 if let Some((page, number)) = brrrty_js::functions::own_page() {
1293 text.push_str(",\"own\":");
1294 self.table.argument(&page, false, &mut text, &mut added)?;
1295 if let Some(n) = number {
1296 text.push_str(",\"ownAt\":");
1297 crate::wire::number(&mut text, n);
1298 }
1299 }
1300 text.push('}');
1301 let req = Request {
1302 added,
1303 handle: Some(f.0),
1304 ..Request::new("call", text)
1305 };
1306 (vec![req], Shape::List, None, "a data function")
1307 }
1308 Op::PageOnce {
1309 data,
1310 traps,
1311 defaults,
1312 f,
1313 } => {
1314 let (page, open) = self.open_request(data, traps, defaults)?;
1315 (
1316 vec![open, call_request(page, f, None), close_request(page)],
1317 Shape::Once,
1318 None,
1319 "a permalink function",
1320 )
1321 }
1322 Op::PageOpenWithVars {
1323 data,
1324 traps,
1325 defaults,
1326 functions,
1327 keys,
1328 } => {
1329 let (page, open) = self.open_request(data, traps, defaults)?;
1330 let mut reqs = vec![open];
1331 reqs.extend(functions.iter().map(|f| vars_request(page, *f, keys)));
1332 (
1333 reqs,
1334 Shape::OpenWithVars,
1335 Some(page),
1336 "a computed data function",
1337 )
1338 }
1339 Op::PageRun { page, steps } => {
1340 let mut reqs = Vec::with_capacity(steps.len());
1341 for step in steps {
1342 match step {
1343 PageStep::Call(f, set) => reqs.push(call_request(page, *f, *set)),
1344 PageStep::Set(key, value) => {
1345 let mut added = Added::default();
1346 let mut text = String::with_capacity(128);
1347 let _ =
1348 write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
1349 crate::wire::string(&mut text, key);
1350 text.push_str(",\"value\":");
1351 self.table.argument(value, false, &mut text, &mut added)?;
1352 text.push('}');
1353 reqs.push(Request {
1354 added,
1355 ..Request::new("pageSet", text)
1356 });
1357 }
1358 }
1359 }
1360 (reqs, Shape::List, None, "a computed data function")
1361 }
1362 Op::Render {
1363 template,
1364 data,
1365 first,
1366 traps,
1367 } => {
1368 let mut added = Added::default();
1369 let mut text = String::with_capacity(1024);
1370 let _ = write!(
1371 text,
1372 "{{\"op\":\"render\",\"template\":{},\"data\":",
1373 template.0
1374 );
1375 self.table.page_data(data, true, &mut text, &mut added)?;
1376 text.push_str(",\"traps\":");
1377 pairs(&mut text, traps);
1378 if let Some(first) = first {
1379 text.push_str(",\"first\":");
1380 self.table.argument(first, true, &mut text, &mut added)?;
1381 }
1382 text.push('}');
1383 let req = Request {
1384 added,
1385 ..Request::new("render", text)
1386 };
1387 (vec![req], Shape::List, None, "a JavaScript template")
1388 }
1389 })
1390 }
1391
1392 fn one(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> JsResult<Decoded> {
1394 self.now(op, filters)
1395 .pop()
1396 .unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
1397 }
1398
1399 fn now(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Vec<JsResult<Decoded>> {
1401 for _ in 0..AGAIN {
1402 let finished = match self.begin(op, filters) {
1403 Begun::Done(f) => f,
1404 Begun::Sent(pending) => {
1405 let waited = pending.wait(filters);
1406 self.finish(waited)
1407 }
1408 };
1409 if let Finished::Results { results, .. } = finished {
1410 return results;
1411 }
1412 }
1413 vec![JsResult::Failed(self.fail(
1414 "the worker kept losing the values a request referred to",
1415 ))]
1416 }
1417
1418 pub(crate) fn write_line(&mut self, line: &str) -> Result<(), RuntimeFailure> {
1420 if let Some(f) = &self.failed {
1421 return Err(f.clone());
1422 }
1423 let mut bytes = Vec::with_capacity(line.len() + 1);
1424 bytes.extend_from_slice(line.as_bytes());
1425 bytes.push(b'\n');
1426 let sent = locked(&self.mux.stdin)
1427 .as_mut()
1428 .map(|s| s.write_all(&bytes).and_then(|_| s.flush()));
1429 if !matches!(sent, Some(Ok(()))) {
1430 return Err(self.fail("Node stopped reading requests"));
1431 }
1432 Ok(())
1433 }
1434
1435 pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
1438 locked(&self.mux.stdin).take()
1439 }
1440
1441 pub(crate) fn line_for(&mut self, text: &str, feed: Option<&str>) -> (u64, String) {
1445 self.next_id += 1;
1446 let id = self.next_id;
1447 let mut line = String::with_capacity(text.len() + 32);
1448 let _ = write!(line, "{{\"id\":{id},");
1449 if let Some(feed) = feed {
1450 line.push_str("\"feed\":");
1451 line.push_str(feed);
1452 line.push(',');
1453 }
1454 line.push_str(text.strip_prefix('{').unwrap_or(text));
1455 (id, line)
1456 }
1457
1458 pub(crate) fn exchange(
1460 &mut self,
1461 text: &str,
1462 feed: Option<&str>,
1463 what: &str,
1464 ) -> Result<Frame, RuntimeFailure> {
1465 self.exchange_with(text, feed, what, &mut |name: &str, _: &[Value]| {
1466 Err(format!(
1467 "calls `this.{name}` where Brrrty has no filters to run it"
1468 ))
1469 })
1470 }
1471
1472 pub(crate) fn answer(
1475 &mut self,
1476 frame: &Frame,
1477 filters: &mut FilterCall<'_>,
1478 ) -> Result<(), String> {
1479 let reply: Box<str> = match self.answers_feed.as_mut() {
1480 Some(feed) => {
1481 let reply: Box<str> = match feed.pop_front() {
1482 Some((q, a)) if q == frame.body => a,
1483 _ => r#"{"refused":"asks for a filter the first run didn't ask for at this point"}"#
1484 .into(),
1485 };
1486 self.mux.send_answer(&reply)?;
1487 reply
1488 }
1489 None => self.mux.answer(frame, filters)?,
1490 };
1491 self.asked.push((frame.body.clone(), reply));
1492 Ok(())
1493 }
1494
1495 pub(crate) fn exchange_with(
1498 &mut self,
1499 text: &str,
1500 feed: Option<&str>,
1501 what: &str,
1502 filters: &mut FilterCall<'_>,
1503 ) -> Result<Frame, RuntimeFailure> {
1504 let (id, line) = self.line_for(text, feed);
1505 self.write_line(&line)?;
1506 let mut wait = self.wait();
1507 let frame = loop {
1508 match self.next_frame(what, &mut wait) {
1509 Ok(f) if f.question => {
1510 if let Err(why) = self.answer(&f, filters) {
1511 return Err(self.fail(&why));
1512 }
1513 }
1514 Ok(f) => break f,
1515 Err(f) => return Err(f),
1516 }
1517 };
1518 let took = wait.start.elapsed();
1519 self.slowest = self.slowest.max(took);
1520 self.stats.requests += 1;
1521 self.stats.sent += line.len() as u64;
1522 self.stats.received += frame.body.len() as u64;
1523 self.stats.waited += took;
1524 if frame.id != id {
1525 let head = frame.head.clone();
1526 return Err(self.fail(&format!("a reply out of order: {head}")));
1527 }
1528 Ok(frame)
1529 }
1530
1531 pub(crate) fn wait(&self) -> Wait {
1533 self.mux.wait()
1534 }
1535
1536 pub(crate) fn next_frame(
1539 &mut self,
1540 what: &str,
1541 wait: &mut Wait,
1542 ) -> Result<Frame, RuntimeFailure> {
1543 if let Some(f) = &self.failed {
1544 return Err(f.clone());
1545 }
1546 let mux = self.mux.clone();
1547 mux.next(&self.replies, what, wait, self.deadline)
1548 .map_err(|why| self.fail(&why))
1549 }
1550
1551 fn interpret(&mut self, frame: Frame, what: &str) -> JsResult<Decoded> {
1553 let Frame {
1554 head: reply, ok, ..
1555 } = frame;
1556 if reply.get("changedArgument").is_some() {
1557 return JsResult::Failed(self.fail(&format!(
1558 "{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"
1559 )));
1560 }
1561 if let Some(p) = reply.get("protocol") {
1562 return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
1563 }
1564 if let Some(why) = reply.get("again") {
1565 walk_roots().sent_back(&self.root, why.as_str().unwrap_or(""));
1568 let mut f = self.fail(&format!(
1569 "the JavaScript worker has to check the data files' values after every call ({})",
1570 why.as_str().unwrap_or("")
1571 ));
1572 f.again = true;
1573 self.failed = Some(f.clone());
1574 return JsResult::Failed(f);
1575 }
1576 if let Some(t) = reply.get("thrown") {
1577 return JsResult::Thrown(js_error(t, &self.root));
1578 }
1579 if let Some(m) = reply.get("invalid") {
1580 return JsResult::Thrown(JsError {
1581 message: m.as_str().unwrap_or("").to_string(),
1582 invalid: true,
1583 ..JsError::default()
1584 });
1585 }
1586 if reply.get("dropShared").is_some() {
1587 self.table.forget();
1589 }
1590 if let Some(r) = reply.get("refused") {
1591 return JsResult::Refused(Refusal {
1592 why: r.as_str().unwrap_or("").to_string(),
1593 impure: reply.get("impure").and_then(Json::as_bool) == Some(true),
1594 });
1595 }
1596 let earlier = self.earlier.take();
1597 if reply.get("same").is_some() {
1598 return match earlier {
1599 Some(d) => JsResult::Ok(d),
1600 None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
1601 };
1602 }
1603 match ok {
1604 Some(Ok(d)) => JsResult::Ok(d),
1605 Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
1606 None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
1607 }
1608 }
1609
1610 fn start_replays(&mut self) {
1614 if !self.order_check {
1615 return;
1616 }
1617 let loads = Arc::new(crate::replay::Loads {
1618 node: self.node.clone(),
1619 root: self.root.clone(),
1620 run_mode: self.run_mode,
1621 loads: std::mem::take(&mut self.load_log),
1622 global_end: self.global_end,
1623 load_handles: self.load_handles,
1624 walk: self.walk.clone(),
1625 took: self.stats.started.map(|t| t.elapsed()).unwrap_or_default(),
1628 });
1629 let replays = [
1630 crate::replay::Handle::start(loads.clone(), true),
1631 crate::replay::Handle::start(loads, false),
1632 ];
1633 for (line, dynamic) in &self.table.lines {
1634 if !dynamic {
1635 for r in &replays {
1636 r.line(line.clone());
1637 }
1638 }
1639 }
1640 self.replays = Some(replays);
1641 }
1642
1643 pub(crate) fn fail(&mut self, why: &str) -> RuntimeFailure {
1646 drop(locked(&self.mux.stdin).take());
1647 let deadline = Instant::now() + Duration::from_secs(2);
1648 let status = loop {
1649 let mut child = locked(&self.mux.child);
1650 match child.try_wait() {
1651 Ok(Some(s)) => break Some(s),
1652 Ok(None) if Instant::now() < deadline => {
1653 drop(child);
1654 std::thread::sleep(Duration::from_millis(10))
1655 }
1656 _ => {
1657 let _ = child.kill();
1658 break child.wait().ok();
1659 }
1660 }
1661 };
1662 self.stop_group();
1663 self.finish_stderr();
1664 let message = match status {
1665 Some(s) => match (s.code(), signal_of(&s)) {
1666 (Some(code), _) => format!("Node exited with status {code} ({why})"),
1667 (None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
1668 _ => why.to_string(),
1669 },
1670 None => why.to_string(),
1671 };
1672 let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
1673 let message = if stopped {
1674 "Brrrty was stopped, and stopped Node with it".to_string()
1675 } else {
1676 message
1677 };
1678 let failure = RuntimeFailure {
1679 stopped,
1680 again: false,
1681 message,
1682 stderr_tail: self
1683 .stderr_tail
1684 .lock()
1685 .map(|t| t.iter().cloned().collect())
1686 .unwrap_or_default(),
1687 };
1688 self.failed = Some(failure.clone());
1689 failure
1690 }
1691
1692 pub(crate) fn stop(&mut self) {
1694 {
1695 let mut child = locked(&self.mux.child);
1696 let _ = child.kill();
1697 let _ = child.wait();
1698 }
1699 self.stop_group();
1700 if self.failed.is_none() {
1701 self.failed = Some(RuntimeFailure {
1702 message: "the replay check stopped its Node".into(),
1703 stderr_tail: Vec::new(),
1704 stopped: false,
1705 again: false,
1706 });
1707 }
1708 }
1709
1710 fn stop_group(&mut self) {
1714 #[cfg(unix)]
1715 kill_group(self.pid);
1716 live(self.pid, false);
1717 }
1718
1719 fn finish_stderr(&mut self) {
1722 if let Some(t) = self.stderr_thread.take() {
1723 let deadline = Instant::now() + STDERR_GRACE;
1724 while !t.is_finished() && Instant::now() < deadline {
1725 std::thread::sleep(Duration::from_millis(5));
1726 }
1727 if t.is_finished() {
1728 let _ = t.join();
1729 }
1730 }
1731 }
1732
1733 fn shown(&self, file: &Path) -> String {
1734 file.strip_prefix(&self.root)
1735 .unwrap_or(file)
1736 .display()
1737 .to_string()
1738 }
1739}
1740
1741fn no_filters() -> impl FnMut(&str, &[Value]) -> Result<Value, String> {
1743 |name: &str, _: &[Value]| {
1744 Err(format!(
1745 "calls `this.{name}` where Brrrty has no filters to run it"
1746 ))
1747 }
1748}
1749
1750fn close_request(page: PageId) -> Request<'static> {
1751 let text = op_text("pageClose", |t| {
1752 let _ = write!(t, ",\"page\":{}", page.0);
1753 });
1754 Request {
1755 one_way: true,
1756 ..Request::new("pageClose", text)
1757 }
1758}
1759
1760fn call_request(page: PageId, f: FnHandle, set: Option<&str>) -> Request<'static> {
1761 let text = op_text("pageCall", |t| {
1762 let _ = write!(t, ",\"page\":{},\"handle\":{},\"set\":", page.0, f.0);
1763 match set {
1764 Some(key) => crate::wire::string(t, key),
1765 None => t.push_str("null"),
1766 }
1767 });
1768 Request {
1769 handle: Some(f.0),
1770 ..Request::new("pageCall", text)
1771 }
1772}
1773
1774fn vars_request(page: PageId, f: FnHandle, keys: &[String]) -> Request<'static> {
1775 let text = op_text("pageVars", |t| {
1776 let _ = write!(t, ",\"page\":{},\"handle\":{},\"keys\":", page.0, f.0);
1777 crate::wire::strings(t, keys);
1778 });
1779 Request {
1780 handle: Some(f.0),
1781 ..Request::new("pageVars", text)
1782 }
1783}
1784
1785fn op_text(op: &str, rest: impl FnOnce(&mut String)) -> String {
1787 let mut t = String::with_capacity(96);
1788 let _ = write!(t, "{{\"op\":\"{op}\"");
1789 rest(&mut t);
1790 t.push('}');
1791 t
1792}
1793
1794fn pairs(out: &mut String, traps: &[(String, String)]) {
1796 out.push('[');
1797 for (i, (k, why)) in traps.iter().enumerate() {
1798 if i > 0 {
1799 out.push(',');
1800 }
1801 out.push('[');
1802 crate::wire::string(out, k);
1803 out.push(',');
1804 crate::wire::string(out, why);
1805 out.push(']');
1806 }
1807 out.push(']');
1808}
1809
1810fn unit(r: JsResult<Decoded>) -> JsResult<()> {
1811 match r {
1812 JsResult::Ok(_) => JsResult::Ok(()),
1813 JsResult::Thrown(e) => JsResult::Thrown(e),
1814 JsResult::Refused(r) => JsResult::Refused(r),
1815 JsResult::Failed(f) => JsResult::Failed(f),
1816 }
1817}
1818
1819impl Worker {
1820 fn load_template_as(
1823 &mut self,
1824 file: &Path,
1825 layout: bool,
1826 custom: Option<(&str, &str)>,
1827 ) -> JsResult<LoadedTemplate> {
1828 let what = self.shown(file);
1829 let text = op_text("templateLoad", |t| {
1830 t.push_str(",\"path\":");
1831 crate::wire::string(t, &file.to_string_lossy());
1832 let _ = write!(t, ",\"layout\":{layout}");
1833 if let Some((ext, content)) = custom {
1834 t.push_str(",\"custom\":{\"ext\":");
1835 crate::wire::string(t, ext);
1836 t.push_str(",\"content\":");
1837 crate::wire::string(t, content);
1838 t.push('}');
1839 }
1840 });
1841 self.last_template = None;
1842 let r = self.request(
1843 Request {
1844 path: Some(file),
1845 ..Request::new("templateLoad", text)
1846 },
1847 &what,
1848 );
1849 match r {
1850 JsResult::Ok(data) => match self.last_template {
1851 Some(id) => JsResult::Ok(LoadedTemplate {
1852 id: TemplateId(id),
1853 data,
1854 }),
1855 None => JsResult::Failed(self.fail("templateLoad gave no template id")),
1856 },
1857 JsResult::Thrown(e) => JsResult::Thrown(e),
1858 JsResult::Refused(r) => JsResult::Refused(r),
1859 JsResult::Failed(f) => JsResult::Failed(f),
1860 }
1861 }
1862}
1863
1864impl JsRuntime for Worker {
1865 fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
1866 let text = op_text("setArg", |t| {
1867 let _ = write!(t, ",\"value\":{}", encode(arg));
1868 });
1869 unit(self.request(Request::new("setArg", text), "the data argument"))
1870 }
1871
1872 fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
1873 let what = self.shown(file);
1874 let key = (call, file.to_path_buf());
1875 self.earlier = self.last_loaded.get(&key).cloned();
1879 if self.fixed.contains(&key)
1883 && let Some(d) = self.earlier.take()
1884 {
1885 return JsResult::Ok(d);
1886 }
1887 let text = op_text("load", |t| {
1888 t.push_str(",\"path\":");
1889 crate::wire::string(t, &file.to_string_lossy());
1890 let _ = write!(t, ",\"call\":{call}");
1891 });
1892 let r = self.request(
1893 Request {
1894 path: Some(file),
1895 ..Request::new("load", text)
1896 },
1897 &what,
1898 );
1899 if let JsResult::Ok(d) = &r {
1900 if self.last_fixed {
1901 self.fixed.insert(key.clone());
1902 }
1903 self.last_loaded.insert(key, d.clone());
1904 }
1905 r
1906 }
1907
1908 fn load_config(&mut self, file: &Path) -> JsResult<Decoded> {
1909 let what = self.shown(file);
1910 let cli = self.cli_dirs.clone();
1911 let text = op_text("configLoad", |t| {
1912 t.push_str(",\"path\":");
1913 crate::wire::string(t, &file.to_string_lossy());
1914 t.push_str(",\"cli\":{");
1915 let mut first = true;
1916 for (key, v) in [("input", &cli.0), ("output", &cli.1)] {
1917 if let Some(v) = v {
1918 if !first {
1919 t.push(',');
1920 }
1921 first = false;
1922 crate::wire::string(t, key);
1923 t.push(':');
1924 crate::wire::string(t, v);
1925 }
1926 }
1927 t.push('}');
1928 });
1929 self.earlier = None;
1930 self.request(
1931 Request {
1932 path: Some(file),
1933 ..Request::new("configLoad", text)
1934 },
1935 &what,
1936 )
1937 }
1938
1939 fn call(
1940 &mut self,
1941 f: FnHandle,
1942 this: This<'_>,
1943 args: &[Value],
1944 settle: Settle,
1945 ) -> JsResult<Decoded> {
1946 let op = Op::Call {
1947 f,
1948 this,
1949 args,
1950 settle,
1951 };
1952 self.one(op, &mut no_filters())
1953 }
1954
1955 fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
1956 let (reqs, shape, page, what) = match self.op_requests(op) {
1957 Ok(r) => r,
1958 Err(why) => {
1959 return Begun::Done(Finished::Results {
1960 results: vec![JsResult::Refused(Refusal::new(why))],
1961 page: None,
1962 });
1963 }
1964 };
1965 if !Worker::fits(&reqs) {
1966 let results = self.requests(reqs, what, filters);
1969 let done = Done {
1970 sent: Vec::new(),
1971 frames: Vec::new(),
1972 asked: Vec::new(),
1973 failure: None,
1974 what: what.to_string(),
1975 shape,
1976 page,
1977 waited: Duration::ZERO,
1978 };
1979 return Begun::Done(self.shaped(done, results));
1980 }
1981 match self.send(reqs, what, shape, page) {
1982 Ok(ticket) => Begun::Sent(Box::new(ticket)),
1983 Err(f) => Begun::Done(Finished::Results {
1984 results: vec![JsResult::Failed(f)],
1985 page: None,
1986 }),
1987 }
1988 }
1989
1990 fn finish(&mut self, waited: Waited) -> Finished {
1991 match waited.0.downcast::<Done>() {
1992 Ok(done) => self.settle(*done),
1993 Err(_) => Finished::Results {
1994 results: vec![JsResult::Failed(
1995 self.fail("replies that aren't this worker's"),
1996 )],
1997 page: None,
1998 },
1999 }
2000 }
2001
2002 fn page_open(
2003 &mut self,
2004 data: &Value,
2005 traps: &[(String, String)],
2006 defaults: &[String],
2007 ) -> JsResult<PageId> {
2008 let (page, open) = match self.open_request(data, traps, defaults) {
2009 Ok(r) => r,
2010 Err(why) => return JsResult::Refused(Refusal::new(why)),
2011 };
2012 match self.request(open, "a page's data") {
2013 JsResult::Ok(_) => JsResult::Ok(PageId(page.0)),
2014 JsResult::Thrown(e) => JsResult::Thrown(e),
2015 JsResult::Refused(r) => JsResult::Refused(r),
2016 JsResult::Failed(f) => JsResult::Failed(f),
2017 }
2018 }
2019
2020 fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
2021 let r = self.request(vars_request(page, f, keys), "a computed data function");
2022 match r {
2023 JsResult::Ok(d) => match strings(&d.value) {
2024 Some(list) => JsResult::Ok(list),
2025 None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
2026 },
2027 JsResult::Thrown(e) => JsResult::Thrown(e),
2028 JsResult::Refused(r) => JsResult::Refused(r),
2029 JsResult::Failed(f) => JsResult::Failed(f),
2030 }
2031 }
2032
2033 fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
2034 self.request(call_request(page, f, set), "a computed data function")
2035 }
2036
2037 fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
2038 let mut added = Added::default();
2039 let mut text = String::with_capacity(128);
2040 let _ = write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
2041 crate::wire::string(&mut text, key);
2042 text.push_str(",\"value\":");
2043 if let Err(why) = self.table.argument(value, false, &mut text, &mut added) {
2044 return JsResult::Refused(Refusal::new(why));
2045 }
2046 text.push('}');
2047 unit(self.request(
2048 Request {
2049 added,
2050 ..Request::new("pageSet", text)
2051 },
2052 "a page's data",
2053 ))
2054 }
2055
2056 fn page_close(&mut self, page: PageId) {
2057 let _ = self.requests(
2059 vec![close_request(page)],
2060 "a page's data",
2061 &mut no_filters(),
2062 );
2063 }
2064
2065 fn page_once(
2066 &mut self,
2067 data: &Value,
2068 traps: &[(String, String)],
2069 defaults: &[String],
2070 f: FnHandle,
2071 ) -> JsResult<Decoded> {
2072 let op = Op::PageOnce {
2073 data,
2074 traps,
2075 defaults,
2076 f,
2077 };
2078 self.one(op, &mut no_filters())
2079 }
2080
2081 fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
2082 let filters = self.filters.clone();
2083 self.now(
2084 Op::PageRun { page, steps },
2085 &mut |name: &str, args: &[Value]| match &filters {
2086 Some(f) => f(name, args),
2087 None => Err(format!(
2088 "calls `this.{name}` where Brrrty has no filters to run it"
2089 )),
2090 },
2091 )
2092 }
2093
2094 fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
2095 self.global_end = self.load_log.len();
2096 let d = match self.request(
2097 Request::new("loadsChanged", op_text("loadsChanged", |_| {})),
2098 "the data files",
2099 ) {
2100 JsResult::Ok(d) => d,
2101 JsResult::Thrown(e) => return JsResult::Thrown(e),
2102 JsResult::Refused(r) => return JsResult::Refused(r),
2103 JsResult::Failed(f) => return JsResult::Failed(f),
2104 };
2105 let Value::Array(items) = &d.value else {
2106 return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
2107 };
2108 let mut out = Vec::new();
2109 for (i, item) in items.iter().enumerate() {
2110 let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
2111 return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
2112 };
2113 let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
2114 match at {
2115 [PathPart::Index(j), PathPart::Key(k), rest @ ..]
2116 if *j == i && k == "value" =>
2117 {
2118 Some(rest.to_vec())
2119 }
2120 _ => None,
2121 }
2122 };
2123 out.push((
2124 PathBuf::from(&*p),
2125 Decoded {
2126 value,
2127 functions: d
2128 .functions
2129 .iter()
2130 .filter_map(|(at, h)| under(at).map(|a| (a, *h)))
2131 .collect(),
2132 refused: d
2133 .refused
2134 .iter()
2135 .filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
2136 .collect(),
2137 },
2138 ));
2139 }
2140 JsResult::Ok(out)
2141 }
2142
2143 fn begin_calls(&mut self) -> JsResult<()> {
2144 let frame = match self.exchange(&op_text("callsBegin", |_| {}), None, "the data files") {
2145 Ok(f) => f,
2146 Err(f) => return JsResult::Failed(f),
2147 };
2148 let head = &frame.head;
2149 self.load_handles = head.get("handles").and_then(Json::as_u64).unwrap_or(0);
2150 self.frozen = head.get("exports").and_then(Json::as_str) == Some("frozen");
2151 self.walks = head.get("walks").and_then(Json::as_str).map(str::to_string);
2152 self.table.load_handles = Some(u32::try_from(self.load_handles).unwrap_or(u32::MAX));
2153 self.calls_begun = true;
2154 if trace() {
2155 self.trace("the data files loaded");
2156 match self.exports_frozen() {
2157 Ok(()) => {
2158 eprintln!("note: the data files' values are frozen while pages call functions")
2159 }
2160 Err(why) => {
2161 eprintln!("note: the data files' values are walked after every call ({why})")
2162 }
2163 }
2164 }
2165 let changed: Vec<&str> = head
2166 .get("changed")
2167 .and_then(Json::as_array)
2168 .map(|a| a.iter().filter_map(Json::as_str).collect())
2169 .unwrap_or_default();
2170 if !changed.is_empty() {
2171 return JsResult::Refused(Refusal {
2172 why: format!(
2173 "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",
2174 if changed.len() == 1 { "file" } else { "files" },
2175 changed.join(", ")
2176 ),
2177 impure: true,
2178 });
2179 }
2180 if head.get("protos").and_then(Json::as_bool) == Some(true) {
2181 return JsResult::Refused(Refusal {
2182 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(),
2183 impure: true,
2184 });
2185 }
2186 if self.load_log.len() > self.global_end {
2190 self.start_replays();
2191 }
2192 JsResult::Ok(())
2193 }
2194
2195 fn set_filters(&mut self, filters: Filters) {
2196 self.filters = Some(filters);
2197 }
2198
2199 fn template_setup(&mut self, filters: &[String], node: &[(String, u32)]) -> JsResult<()> {
2200 let text = op_text("templateSetup", |t| {
2201 t.push_str(",\"filters\":");
2202 crate::wire::strings(t, filters);
2203 t.push_str(",\"node\":[");
2205 for (i, (name, handle)) in node.iter().enumerate() {
2206 if i > 0 {
2207 t.push(',');
2208 }
2209 t.push('[');
2210 crate::wire::string(t, name);
2211 let _ = write!(t, ",{handle}]");
2212 }
2213 t.push(']');
2214 });
2215 unit(self.request(
2216 Request::new("templateSetup", text),
2217 "the JavaScript templates' setup",
2218 ))
2219 }
2220
2221 fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate> {
2222 self.load_template_as(file, layout, None)
2223 }
2224
2225 fn load_custom_template(
2226 &mut self,
2227 file: &Path,
2228 ext: &str,
2229 content: &str,
2230 ) -> JsResult<LoadedTemplate> {
2231 self.load_template_as(file, false, Some((ext, content)))
2232 }
2233
2234 fn render(
2235 &mut self,
2236 template: TemplateId,
2237 data: &Value,
2238 first: Option<&Value>,
2239 traps: &[(String, String)],
2240 filters: &mut FilterCall<'_>,
2241 ) -> JsResult<Decoded> {
2242 let op = Op::Render {
2243 template,
2244 data,
2245 first,
2246 traps,
2247 };
2248 self.one(op, filters)
2249 }
2250
2251 fn verify(&mut self) -> JsResult<()> {
2252 match self.request(
2255 Request::new("exportsFinal", op_text("exportsFinal", |_| {})),
2256 "the data files' values",
2257 ) {
2258 JsResult::Ok(_) => {}
2259 other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
2260 return match other {
2261 JsResult::Refused(r) => JsResult::Refused(r),
2262 JsResult::Failed(f) => JsResult::Failed(f),
2263 _ => JsResult::Ok(()),
2264 };
2265 }
2266 JsResult::Thrown(e) => return JsResult::Thrown(e),
2267 }
2268 if self.frozen {
2271 walk_roots().froze(&self.root);
2272 }
2273 let Some(replays) = self.replays.take() else {
2274 return JsResult::Ok(());
2275 };
2276 let calls = Arc::new(crate::replay::Calls {
2277 records: {
2278 let mut records = std::mem::take(&mut self.call_log);
2282 records.sort_by_key(|r| r.at);
2283 records
2284 },
2285 load_handles: self.load_handles,
2286 slowest: self.slowest,
2287 dynamic: std::mem::take(&mut self.table.dynamic),
2288 lines: self.table.lines.clone(),
2289 dropped: self.dropped,
2290 });
2291 if trace() {
2292 self.trace("the pages' calls ended");
2293 }
2294 let checking = Instant::now();
2295 let [a, b] = replays;
2296 a.run(calls.clone());
2297 b.run(calls);
2298 let (a, b) = (a.finish(), b.finish());
2299 if trace() {
2300 eprintln!(
2301 "note: the replay check took {:.3} s after the build's own calls",
2302 checking.elapsed().as_secs_f64()
2303 );
2304 }
2305 match a.and(b) {
2306 Ok(()) => JsResult::Ok(()),
2307 Err(crate::replay::Failure::Differs(why, handle)) => {
2308 let named = handle
2309 .and_then(|h| {
2310 let text = op_text("describe", |t| {
2311 let _ = write!(t, ",\"handle\":{h}");
2312 });
2313 self.exchange(&text, None, "a function's name").ok()
2314 })
2315 .and_then(|f| match f.value() {
2316 Some(Value::String(s)) => Some(s.to_string()),
2317 _ => None,
2318 })
2319 .unwrap_or_else(|| "a function from JavaScript data".to_string());
2320 JsResult::Refused(Refusal {
2321 why: why.replace("{fn}", &named),
2322 impure: true,
2323 })
2324 }
2325 Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
2326 Err(crate::replay::Failure::Again(why)) => {
2327 walk_roots().sent_back(&self.root, &why);
2328 let mut f = self.fail(&format!(
2329 "the JavaScript worker has to check the data files' values after every call ({why})"
2330 ));
2331 f.again = true;
2332 self.failed = Some(f.clone());
2333 JsResult::Failed(f)
2334 }
2335 }
2336 }
2337
2338 fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
2339 match self.request(
2340 Request::new("reads", op_text("reads", |_| {})),
2341 "the list of files read",
2342 ) {
2343 JsResult::Ok(d) => match strings(&d.value) {
2344 Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
2345 None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
2346 },
2347 JsResult::Thrown(e) => JsResult::Thrown(e),
2348 JsResult::Refused(r) => JsResult::Refused(r),
2349 JsResult::Failed(f) => JsResult::Failed(f),
2350 }
2351 }
2352}
2353
2354impl Drop for Worker {
2355 fn drop(&mut self) {
2356 if let Some(mut stdin) = locked(&self.mux.stdin).take() {
2357 let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
2358 }
2359 let deadline = Instant::now() + Duration::from_secs(20);
2361 loop {
2362 let mut child = locked(&self.mux.child);
2363 match child.try_wait() {
2364 Ok(Some(_)) => break,
2365 Ok(None) if Instant::now() < deadline => {
2366 drop(child);
2367 std::thread::sleep(Duration::from_millis(5))
2368 }
2369 _ => {
2370 let _ = child.kill();
2371 let _ = child.wait();
2372 break;
2373 }
2374 }
2375 }
2376 self.stop_group();
2377 self.finish_stderr();
2378 }
2379}
2380
2381fn walk_roots() -> MutexGuard<'static, WalkMemo> {
2385 static ROOTS: std::sync::LazyLock<Mutex<WalkMemo>> =
2386 std::sync::LazyLock::new(|| Mutex::new(WalkMemo::default()));
2387 ROOTS.lock().unwrap_or_else(|e| e.into_inner())
2388}
2389
2390#[derive(Default)]
2396pub(crate) struct WalkMemo {
2397 roots: HashMap<PathBuf, Walks>,
2398}
2399
2400struct Walks {
2401 why: String,
2402 left: u32,
2404 last: u32,
2406}
2407
2408impl WalkMemo {
2409 const MOST: u32 = 64;
2410
2411 pub(crate) fn sent_back(&mut self, root: &Path, why: &str) {
2413 let w = self.roots.entry(root.to_path_buf()).or_insert(Walks {
2414 why: String::new(),
2415 left: 0,
2416 last: 0,
2417 });
2418 if w.left > 0 {
2420 return;
2421 }
2422 w.why = why.to_string();
2423 w.last = (w.last * 2).clamp(1, Self::MOST);
2424 w.left = w.last;
2425 }
2426
2427 pub(crate) fn starting(&mut self, root: &Path) -> Option<String> {
2429 let w = self.roots.get_mut(root)?;
2430 if w.left == 0 {
2431 return None;
2432 }
2433 w.left -= 1;
2434 Some(w.why.clone())
2435 }
2436
2437 pub(crate) fn froze(&mut self, root: &Path) {
2439 self.roots.remove(root);
2440 }
2441}
2442
2443fn trace() -> bool {
2446 static ON: std::sync::LazyLock<bool> =
2447 std::sync::LazyLock::new(|| std::env::var_os("BRRRTY_JS_TRACE").is_some());
2448 *ON
2449}
2450
2451static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
2454
2455static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2457
2458fn live(pid: u32, running: bool) {
2459 let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2460 l.retain(|p| *p != pid);
2461 if running {
2462 l.push(pid);
2463 }
2464}
2465
2466pub fn stop_all() {
2469 STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
2470 let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2471 #[cfg(unix)]
2472 for pid in l.iter() {
2473 kill_group(*pid);
2474 }
2475}
2476
2477pub(crate) fn stop_pid(pid: u32) {
2479 #[cfg(unix)]
2480 kill_group(pid);
2481 #[cfg(windows)]
2483 {
2484 let _ = Command::new("taskkill")
2485 .args(["/PID", &pid.to_string(), "/T", "/F"])
2486 .stdin(Stdio::null())
2487 .stdout(Stdio::null())
2488 .stderr(Stdio::null())
2489 .status();
2490 }
2491 #[cfg(not(any(unix, windows)))]
2492 let _ = pid;
2493}
2494
2495#[cfg(unix)]
2496fn kill_group(pid: u32) {
2497 if let Ok(pid) = i32::try_from(pid) {
2498 unsafe {
2500 libc::killpg(pid, libc::SIGKILL);
2501 }
2502 }
2503}
2504
2505#[cfg(unix)]
2510fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2511 use std::os::fd::AsRawFd;
2512 use std::os::unix::process::CommandExt;
2513 let (frames_r, frames_w) = std::io::pipe()?;
2514 let frames_w = frames_w.try_clone()?;
2516 let (answers_r, answers_w) = std::io::pipe()?;
2517 let answers_r = answers_r.try_clone()?;
2518 let (err_r, err_w) = std::io::pipe()?;
2519 let fd = frames_w.as_raw_fd();
2520 let answers_fd = answers_r.as_raw_fd();
2521 cmd.stdout(err_w.try_clone()?)
2522 .stderr(err_w)
2523 .env("BRRRTY_FRAMES_FD", fd.to_string())
2524 .env("BRRRTY_ANSWERS_FD", answers_fd.to_string())
2525 .process_group(0);
2527 unsafe {
2530 cmd.pre_exec(move || {
2531 if libc::fcntl(fd, libc::F_SETFD, 0) == -1
2533 || libc::fcntl(answers_fd, libc::F_SETFD, 0) == -1
2534 {
2535 return Err(std::io::Error::last_os_error());
2536 }
2537 Ok(())
2538 });
2539 }
2540 let child = cmd.spawn();
2541 drop(cmd);
2543 drop(frames_w);
2544 drop(answers_r);
2545 Ok((
2546 child?,
2547 Box::new(frames_r),
2548 Box::new(err_r),
2549 Some(Box::new(answers_w)),
2550 ))
2551}
2552
2553type Spawned = (
2556 Child,
2557 Box<dyn Read + Send>,
2558 Box<dyn Read + Send>,
2559 Option<Box<dyn Write + Send>>,
2560);
2561
2562#[cfg(not(unix))]
2564fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2565 let mut child = cmd
2566 .stdout(Stdio::piped())
2567 .stderr(Stdio::piped())
2568 .env("BRRRTY_FRAMES_FD", "1")
2569 .spawn()?;
2570 let stdout = child.stdout.take().expect("piped stdout");
2571 let stderr = child.stderr.take().expect("piped stderr");
2572 Ok((child, Box::new(stdout), Box::new(stderr), None))
2573}
2574
2575#[cfg(unix)]
2576fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
2577 use std::os::unix::process::ExitStatusExt;
2578 s.signal()
2579}
2580
2581#[cfg(not(unix))]
2582fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
2583 None
2584}
2585
2586fn read_frames(stdout: impl Read, tx: mpsc::Sender<Reply>, decoding: Arc<AtomicBool>, mux: &Mux) {
2590 read_frames_to(stdout, &tx, decoding, mux);
2591 locked(&mux.routes).clear();
2593}
2594
2595fn read_frames_to(
2596 stdout: impl Read,
2597 tx: &mpsc::Sender<Reply>,
2598 decoding: Arc<AtomicBool>,
2599 mux: &Mux,
2600) {
2601 let mut r = BufReader::with_capacity(1 << 16, stdout);
2602 let mut seq = 0u64;
2603 loop {
2604 seq += 1;
2605 let mut header = Vec::new();
2606 match r.read_until(b'\n', &mut header) {
2607 Ok(0) => return,
2608 Ok(_) => {}
2609 Err(e) => {
2610 let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
2611 return;
2612 }
2613 }
2614 let fields = header
2615 .strip_prefix(b"\x1eBRRRTY ")
2616 .and_then(|h| h.strip_suffix(b"\n"))
2617 .and_then(|h| std::str::from_utf8(h).ok())
2618 .and_then(|h| {
2619 let mut it = h.split(' ');
2620 let kind = it.next()?;
2621 let id = it.next()?.parse::<u64>().ok()?;
2622 let clock = it.next()?.parse::<usize>().ok()?;
2623 let body = it.next()?.parse::<usize>().ok()?;
2624 (it.next().is_none() && matches!(kind, "r" | "f" | "q"))
2625 .then_some((kind, id, clock, body))
2626 });
2627 let Some((kind, id, clock_len, body_len)) = fields else {
2628 let shown = String::from_utf8_lossy(&header);
2629 let _ = tx.send(Err(format!(
2630 "something other than the worker wrote to its output: {:?}",
2631 shown.chars().take(80).collect::<String>()
2632 )));
2633 return;
2634 };
2635 let mut read = |len: usize| -> Result<String, String> {
2636 let mut bytes = vec![0; len];
2637 r.read_exact(&mut bytes)
2638 .map_err(|e| format!("a cut-off reply: {e}"))?;
2639 String::from_utf8(bytes).map_err(|_| "a reply that isn't UTF-8".to_string())
2640 };
2641 let parts = read(clock_len).and_then(|c| read(body_len).map(|b| (c, b)));
2642 let (clock, body) = match parts {
2643 Ok(p) => p,
2644 Err(e) => {
2645 let _ = tx.send(Err(e));
2646 return;
2647 }
2648 };
2649 let decode_ok = decoding.load(std::sync::atomic::Ordering::Relaxed);
2650 let parsed = parse_reply(body.as_bytes()).map(|mut head| {
2651 let value = head.as_object_mut().and_then(|o| o.remove("ok"));
2652 let ok = if decode_ok || kind == "q" {
2653 value.as_ref().map(decode)
2654 } else {
2655 None
2656 };
2657 Frame {
2658 question: kind == "q",
2659 id,
2660 head,
2661 ok,
2662 body: body.into_boxed_str(),
2663 clock: (!clock.is_empty()).then(|| clock.into_boxed_str()),
2664 made: kind == "f",
2665 seq,
2666 }
2667 });
2668 let route = match &parsed {
2670 Ok(f) => locked(&mux.routes).get(&f.id).cloned(),
2671 Err(_) => None,
2672 };
2673 let sent = match route {
2674 Some(to) => to.send(parsed).is_ok(),
2675 None => tx.send(parsed).is_ok(),
2676 };
2677 if !sent && locked(&mux.routes).is_empty() {
2678 return;
2679 }
2680 }
2681}
2682
2683fn strings(v: &Value) -> Option<Vec<String>> {
2685 match v {
2686 Value::Array(a) => a
2687 .iter()
2688 .map(|s| match s {
2689 Value::String(s) => Some(s.to_string()),
2690 _ => None,
2691 })
2692 .collect(),
2693 _ => None,
2694 }
2695}
2696
2697pub(crate) fn parse_reply(body: &[u8]) -> Result<Json, String> {
2699 let mut de = serde_json::Deserializer::from_slice(body);
2700 de.disable_recursion_limit();
2701 let v = serde::Deserialize::deserialize(&mut de)
2702 .and_then(|v: Json| de.end().map(|()| v))
2703 .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
2704 Ok(v)
2705}
2706
2707fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
2710 let mut r = BufReader::new(stderr);
2711 let mut line = Vec::new();
2712 let mut err = std::io::stderr();
2713 loop {
2714 line.clear();
2715 match r.read_until(b'\n', &mut line) {
2716 Ok(0) | Err(_) => return,
2717 Ok(_) => {
2718 let _ = err.write_all(&line);
2719 if let Ok(mut t) = tail.lock() {
2720 if t.len() == STDERR_TAIL {
2721 t.pop_front();
2722 }
2723 t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
2724 }
2725 }
2726 }
2727 }
2728}
2729
2730fn js_error(t: &Json, root: &Path) -> JsError {
2734 let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
2735 let stack = s("stack");
2736 let place = crate::stack::syntax_header(&s("inspect"))
2737 .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
2738 JsError {
2739 name: s("name"),
2740 message: s("message"),
2741 file: place.as_ref().map(|p| p.file.clone()),
2742 line: place.as_ref().map(|p| p.line),
2743 column: place.and_then(|p| p.column),
2744 stack,
2745 invalid: false,
2746 }
2747}
2748
2749pub fn encode(v: &Value) -> Json {
2751 match v {
2752 Value::Undefined => json!({"$u": 1}),
2753 Value::Null => Json::Null,
2754 Value::Bool(b) => Json::Bool(*b),
2755 Value::Number(n) => {
2756 if n.is_nan() {
2757 json!({"$n": "NaN"})
2758 } else if *n == f64::INFINITY {
2759 json!({"$n": "Infinity"})
2760 } else if *n == f64::NEG_INFINITY {
2761 json!({"$n": "-Infinity"})
2762 } else if *n == 0.0 && n.is_sign_negative() {
2763 json!({"$n": "-0"})
2764 } else {
2765 serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
2766 }
2767 }
2768 Value::String(s) => Json::String(s.to_string()),
2769 Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
2770 Value::Object(o) => {
2771 json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
2772 }
2773 Value::Date(d) => json!({"$d": d.timestamp_millis()}),
2774 Value::Function(h) => json!({"$f": h.0}),
2775 }
2776}
2777
2778#[cfg(test)]
2779mod source {
2780 #[test]
2783 fn the_worker_source_keeps_the_files_line_numbers() {
2784 let source = super::worker_source();
2785 assert_eq!(source.lines().count(), super::WORKER_SOURCE.lines().count());
2787 assert!(!source.lines().any(|l| l.trim_start().starts_with("//")));
2788 }
2789}
2790
2791#[cfg(test)]
2792mod source_size {
2793 use super::*;
2794
2795 #[test]
2798 fn a_worker_larger_than_one_argument_starts() {
2799 let node = match crate::find::find_node(None) {
2800 Ok(n) => n,
2801 Err(e) => {
2802 assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2803 eprintln!("skipped: {e}");
2804 return;
2805 }
2806 };
2807 tests_pad::PAD.with(|p| p.set(200 * 1024));
2808 let t = tempfile::tempdir().unwrap();
2809 let file = t.path().join("h.js");
2810 std::fs::write(&file, "module.exports = { a() { return 'ok'; } };").unwrap();
2811 let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2812 assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2813 }
2814}
2815
2816#[cfg(test)]
2817mod walk_memo {
2818 use super::WalkMemo;
2819 use std::path::Path;
2820
2821 #[test]
2825 fn a_folder_sent_back_walks_for_a_while_not_for_good() {
2826 let root = Path::new("/site");
2827 let mut m = WalkMemo::default();
2828 assert_eq!(m.starting(root), None);
2829 m.sent_back(root, "why");
2830 m.sent_back(root, "another request");
2832 assert_eq!(m.starting(root).as_deref(), Some("why"));
2833 assert_eq!(m.starting(root), None);
2835 m.sent_back(root, "again");
2836 assert_eq!(m.starting(root).as_deref(), Some("again"));
2837 assert_eq!(m.starting(root).as_deref(), Some("again"));
2838 assert_eq!(m.starting(root), None);
2839 m.sent_back(root, "third");
2840 let walked = std::iter::from_fn(|| m.starting(root)).count();
2841 assert_eq!(walked, 4);
2842 for _ in 0..10 {
2843 m.sent_back(root, "more");
2844 while m.starting(root).is_some() {}
2845 }
2846 m.sent_back(root, "most");
2847 assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 64);
2848 m.froze(root);
2850 m.sent_back(root, "new");
2851 assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 1);
2852 }
2853}
2854
2855#[cfg(test)]
2856mod skipped_definition {
2857 use super::*;
2858
2859 #[test]
2866 fn a_skipped_definition_leaves_none_of_its_values_behind() {
2867 let node = match crate::find::find_node(None) {
2868 Ok(n) => n,
2869 Err(e) => {
2870 assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2871 eprintln!("skipped: {e}");
2872 return;
2873 }
2874 };
2875 let t = tempfile::tempdir().unwrap();
2876 let file = t.path().join("h.js");
2877 std::fs::write(
2878 &file,
2879 "module.exports = { poke(o) { o.k = 2; return ''; }, show(v) { return JSON.stringify(v); } };",
2880 )
2881 .unwrap();
2882 let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2883 assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2884 w.exchange(r#"{"op":"callsBegin"}"#, None, "the calls' start")
2885 .expect("begins");
2886 let call = |w: &mut Worker, handle: u32, arg: u32| {
2887 w.exchange(
2888 &format!(
2889 r#"{{"op":"call","handle":{handle},"await":false,"this":{{"$u":1}},"args":[{{"$R":{arg}}}]}}"#
2890 ),
2891 None,
2892 "a call",
2893 )
2894 .expect("answers")
2895 };
2896 w.write_line(r#"{"op":"def","id":50,"v":{"k":1},"n":1}"#)
2898 .unwrap();
2899 let poked = call(&mut w, 0, 50);
2900 assert!(poked.head.get("dropShared").is_some(), "{}", poked.body);
2901 w.write_line(r#"{"op":"def","id":60,"v":{"a":{"x":1},"o":{"$R":50}},"n":2}"#)
2904 .unwrap();
2905 for id in [60, 61, 50] {
2906 let shown = call(&mut w, 1, id);
2907 assert_eq!(
2908 shown.head.get("stale"),
2909 Some(&Json::Bool(true)),
2910 "value {id}: {}",
2911 shown.body
2912 );
2913 }
2914 w.write_line(r#"{"op":"def","id":70,"v":{"a":{"x":1},"o":{"k":1}},"n":3}"#)
2916 .unwrap();
2917 let shown = call(&mut w, 1, 70);
2918 assert!(
2919 shown.body.contains(r#"{\"a\":{\"x\":1},\"o\":{\"k\":1}}"#),
2920 "{}",
2921 shown.body
2922 );
2923 }
2924}