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