Skip to main content

brrrty_node/
client.rs

1//! One Node process running the worker, and the requests Brrrty makes of it.
2
3use 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
26/// The worker's source: the encoding, the computed data proxy, then the
27/// protocol. Written to a temporary file Node runs.
28const 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
38/// The file name of the worker's source. Stack frames in it are the
39/// worker's own, not the site's: `[eval` in older Node, this now.
40pub const SOURCE_FILE: &str = "brrrty-worker-source.mjs";
41
42/// The worker's source as Node is handed it: without its comment lines,
43/// which are a quarter of the file. Each one leaves its line behind,
44/// empty, so a line number in a stack trace is the file's.
45fn 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        /// Extra comment bytes a test adds to the worker's source.
60        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
79/// The 11ty version the worker tells data files it is (`ELEVENTY_VERSION`).
80const ELEVENTY_VERSION: &str = "3.1.8";
81
82/// The stack of the thread that parses replies.
83pub(crate) const REPLY_STACK: usize = 32 * 1024 * 1024;
84
85/// How many of Node's last stderr lines a failure shows.
86const STDERR_TAIL: usize = 20;
87
88/// How long a stopped worker's stderr may take to reach its end: past this,
89/// a process Node started still holds it, and Brrrty stops reading.
90const STDERR_GRACE: Duration = Duration::from_millis(200);
91
92/// How often a request is sent again when the worker lost the values it
93/// refers to before giving up.
94const AGAIN: usize = 16;
95
96/// Whether a request is one the replay check runs again.
97fn logged(op: &str) -> bool {
98    !matches!(
99        op,
100        "reads" | "info" | "callsBegin" | "loadsChanged" | "exportsFinal" | "describe"
101    )
102}
103
104/// How many bytes of requests may be written behind one Node hasn't
105/// answered: less than any pipe holds.
106const PIPE_SAFE: usize = 4000;
107
108/// How long a wait for a reply looks for it before sleeping.
109const SPIN: Duration = Duration::from_micros(60);
110
111/// How often a wait for a reply checks that Node still runs.
112const POLL: Duration = Duration::from_millis(100);
113
114/// The first note about a slow request, then the gap between notes.
115const FIRST_NOTE: Duration = Duration::from_secs(10);
116const NEXT_NOTE: Duration = Duration::from_secs(30);
117
118/// How 11ty was started, as `ELEVENTY_RUN_MODE` shows it.
119#[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/// Node couldn't be started.
135#[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
144/// One frame from the worker, or why there is none.
145type Reply = Result<Frame, String>;
146
147pub(crate) struct Frame {
148    /// A question of the worker's own (a filter a JavaScript template
149    /// calls on `this`), not a reply.
150    pub question: bool,
151    /// The request it answers.
152    pub id: u64,
153    /// The reply without its value.
154    pub head: Json,
155    /// The decoded `ok` value, when the reply has one.
156    ok: Option<Result<Decoded, String>>,
157    /// The reply as sent, without its id and clock: what the replay check
158    /// compares.
159    pub body: Box<str>,
160    /// The clock and random values the request read, as JSON text.
161    pub clock: Option<Box<str>>,
162    /// The reply mentions a function a call made.
163    pub made: bool,
164    /// Its place among the frames Node sent. Node runs one request at a
165    /// time and answers each as it ends, so this is the order it ran them.
166    pub seq: u64,
167}
168
169impl Frame {
170    /// The decoded `ok` value, when it crossed exactly.
171    pub fn value(&self) -> Option<&Value> {
172        match &self.ok {
173            Some(Ok(d)) => Some(&d.value),
174            _ => None,
175        }
176    }
177}
178
179/// One request that loaded data or a template, with its reply, for the
180/// replay check.
181pub(crate) struct LoadRecord {
182    /// The request as sent, without its id.
183    pub text: Box<str>,
184    /// Whether it loads a template (`templateLoad`), a data file (`load`)
185    /// or neither.
186    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
199/// One request made after the data files loaded, with its reply, for the
200/// replay check.
201pub(crate) struct Record {
202    /// The render that made it ([`brrrty_js::functions::unit`]); a request
203    /// made outside one is a unit of its own.
204    pub unit: u64,
205    pub label: Arc<str>,
206    pub op: &'static str,
207    /// The function called, when the request calls one.
208    pub handle: Option<u32>,
209    /// The request as sent, without its id. It refers to the values the
210    /// workers keep by id, which are the same in every worker.
211    pub text: Box<str>,
212    pub body: Box<str>,
213    pub clock: Option<Box<str>>,
214    /// The reply mentions a function a call made.
215    pub made: bool,
216    /// The dynamic definitions the request needs (see [`crate::wire`]),
217    /// and whether it names a function a call made itself.
218    pub dynamic: Vec<u32>,
219    pub names_made: bool,
220    /// The questions the request asked Brrrty, with the answers it got,
221    /// both as sent.
222    pub answers: Vec<(Box<str>, Box<str>)>,
223    /// Nothing came back from it, and nothing will.
224    pub one_way: bool,
225    /// It ran after a call sent with it changed a value the worker kept:
226    /// what it gave isn't used, and a replay's won't be the same.
227    pub unchecked: bool,
228    /// When Node ran it: its reply's place among Node's frames, and for a
229    /// request with no reply, its place after the one before it. Threads
230    /// take their replies in any order, so the log is put in this order
231    /// before the replay check reads it.
232    pub at: (u64, u32),
233}
234
235/// Where notes about a slow request go.
236type Notes = Box<dyn Fn(&str) + Send>;
237
238/// The requests of one operation, how its results are shaped, the page it
239/// opens, and what to call it in a note.
240type Planned = (Vec<Request<'static>>, Shape, Option<PageId>, &'static str);
241
242/// What a worker's threads share: Node itself, and where its frames go.
243pub(crate) struct Mux {
244    child: Mutex<Child>,
245    stdin: Mutex<Option<ChildStdin>>,
246    /// Where Brrrty answers the worker's questions (a filter a JavaScript
247    /// template calls on `this`).
248    answers: Mutex<Option<Box<dyn Write + Send>>>,
249    /// The requests whose replies a [`Ticket`] waits for, by id: where
250    /// their frames go. Any other frame goes to the worker itself.
251    routes: Mutex<HashMap<u64, mpsc::Sender<Reply>>>,
252    /// Where slow-request notes go; stderr unless a test replaces it.
253    notes: Mutex<Notes>,
254    /// When the first note comes, and then how often.
255    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    /// The next frame on `rx`: a reply, or a question of Node's own. `Err`
264    /// is why none will come.
265    fn next(
266        &self,
267        rx: &Receiver<Reply>,
268        what: &str,
269        wait: &mut Wait,
270        deadline: Option<Duration>,
271    ) -> Result<Frame, String> {
272        // Most replies come within microseconds: look for one a few times
273        // before sleeping, which costs more than the wait.
274        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                        // Node runs one request at a time: this one may be
298                        // waiting its turn behind the others.
299                        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    /// Start waiting for a frame.
333    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    /// Run the filter a question names, and send Node the answer. The
343    /// answer as sent, or why it couldn't be.
344    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/// How the results of requests sent together are handed back.
384#[derive(Clone, Copy, PartialEq)]
385enum Shape {
386    /// As they are: the list ends with the first that isn't a value.
387    List,
388    /// A page opened, one function called, the page closed: the call's
389    /// result.
390    Once,
391    /// A page opened, then what each function reads: all of them, or the
392    /// first that failed (the page is then closed).
393    OpenWithVars,
394}
395
396/// One request on its way.
397struct Sent {
398    id: u64,
399    op: &'static str,
400    handle: Option<u32>,
401    text: String,
402    path: Option<String>,
403    one_way: bool,
404    /// From [`Added`]: the request holds a function a call made, and the
405    /// dynamic definitions it needs.
406    made: bool,
407    dynamic: Vec<u32>,
408}
409
410/// Requests sent together, their replies still to come. Waiting for them
411/// needs no hold on the worker, so other requests go out meanwhile and
412/// Node runs them back to back.
413pub(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
423/// The replies to a [`Ticket`]'s requests, for [`Worker::settle`].
424pub(crate) struct Done {
425    sent: Vec<Sent>,
426    /// One per request that has a reply, in order; shorter when Node
427    /// stopped.
428    frames: Vec<Frame>,
429    /// The questions each request asked, with the answers it got.
430    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    /// Wait for the replies, answering Node's questions with `filters`.
440    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
500/// A running worker. Dropping it closes Node's stdin, waits up to 2 s for
501/// it to exit, then kills it.
502pub struct Worker {
503    /// Holds the file Node runs; removed when the worker is dropped.
504    _source_dir: tempfile::TempDir,
505    mux: Arc<Mux>,
506    pid: u32,
507    /// The replay check's answers, as the first run gave them, in order.
508    pub(crate) answers_feed: Option<VecDeque<(Box<str>, Box<str>)>>,
509    /// The questions the request in flight asked, with their answers.
510    asked: Vec<(Box<str>, Box<str>)>,
511    /// Brrrty's filters, for the questions a request asks.
512    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    /// Set once the worker failed: every later request fails the same way.
520    failed: Option<RuntimeFailure>,
521    /// The value each load (by call mode and file) gave last.
522    last_loaded: HashMap<(bool, PathBuf), Decoded>,
523    /// The value a `same` reply to the request in flight stands for.
524    earlier: Option<Decoded>,
525    /// The loads whose value is the same every time, and whether the last
526    /// load's reply said so.
527    fixed: std::collections::HashSet<(bool, PathBuf)>,
528    last_fixed: bool,
529    /// The latest of Node's frames a request of this worker's was
530    /// answered by (see [`Frame::seq`]).
531    last_seq: u64,
532    /// The lists and objects the workers keep (see [`crate::wire`]).
533    table: Table,
534    /// What the worker was started with, for the replay check.
535    node: NodeInfo,
536    run_mode: RunMode,
537    /// Decode each reply's value. The replay check's workers don't: they
538    /// compare replies as text.
539    pub(crate) decode: Arc<AtomicBool>,
540    /// The requests that loaded the data, in order, with their replies.
541    load_log: Vec<LoadRecord>,
542    /// How many of them loaded global data (the rest are template and
543    /// directory data files and templates, which 11ty loads as their
544    /// files finish loading).
545    global_end: usize,
546    /// The requests made since, with their replies.
547    call_log: Vec<Record>,
548    /// A call changed a value the worker kept.
549    dropped: bool,
550    /// Set once the data files loaded: see [`JsRuntime::begin_calls`].
551    calls_begun: bool,
552    /// How many function handles the data files' values made.
553    load_handles: u64,
554    /// `--input` and `--output`: the directories a plugin reads from the config's `directories`.
555    cli_dirs: (Option<String>, Option<String>),
556    /// The replay check's two workers, started as soon as there is
557    /// something for them to check.
558    replays: Option<[crate::replay::Handle; 2]>,
559    /// The replay check runs (see [`Worker::start_with`]).
560    order_check: bool,
561    /// The longest a request took.
562    slowest: Duration,
563    /// How long a request may take before the worker is given up on (the
564    /// replay check's workers only).
565    pub(crate) deadline: Option<Duration>,
566    /// The template id of the last `templateLoad` reply.
567    last_template: Option<u64>,
568    next_ticket: u64,
569    /// What the requests cost, for `BRRRTY_JS_TRACE`.
570    stats: Stats,
571    /// The worker froze the data files' values when the calls began.
572    frozen: bool,
573    /// Why this worker was started walking, when Brrrty asked it to.
574    walk: Option<String>,
575    /// Why it walks them instead, when it does.
576    walks: Option<String>,
577}
578
579/// What a worker's requests cost so far.
580#[derive(Default)]
581struct Stats {
582    started: Option<Instant>,
583    requests: u64,
584    /// Bytes of requests, and of definitions.
585    sent: u64,
586    defined: u64,
587    definitions: u64,
588    /// Bytes of replies.
589    received: u64,
590    /// Time between a request going out and its reply coming in.
591    waited: Duration,
592}
593
594/// One request of the first run: what to send, and what the replay check
595/// needs to know of it.
596struct Request<'a> {
597    op: &'static str,
598    /// The request as JSON text, without its id.
599    text: String,
600    /// The definitions it needs sent first.
601    added: Added,
602    /// The function it calls.
603    handle: Option<u32>,
604    /// The file it loads.
605    path: Option<&'a Path>,
606    /// Nothing comes back from it (`pageClose`).
607    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
623/// A wait for one frame: when it began, and when the next note is due.
624pub(crate) struct Wait {
625    start: Instant,
626    next_note: Instant,
627    /// Node exiting ends the wait even when a process it started keeps
628    /// the replies' pipe open.
629    exited_at: Option<Instant>,
630}
631
632impl Worker {
633    /// Start Node with the worker, in `root` (the project folder), with
634    /// 11ty's environment variables added to Brrrty's own.
635    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    /// [`Worker::start`]; `replay` for one of the replay check's workers.
640    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    /// The `--input` and `--output` flags: the config sees them in `directories`, as 11ty's
650    /// command line wins over the config for it.
651    pub fn set_cli_dirs(&mut self, input: Option<String>, output: Option<String>) {
652        self.cli_dirs = (input, output);
653    }
654
655    /// [`Worker::start`], with or without the replay check: without it
656    /// the site's JavaScript runs once, in this worker's Node alone, and
657    /// nothing is kept of the calls to run them again.
658    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        // The build's own worker asks whether this folder's builds walk;
675        // the replay check's workers do as it did.
676        let walk = match replay {
677            Some(loads) => loads.walk.clone(),
678            None => walk_roots().starting(root),
679        };
680        // Linux takes no single argument of 128 KiB or more, so Node reads
681        // the source from a file in a folder of its own, removed with the
682        // worker.
683        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        // A reply nests up to three JSON levels per level of the value
725        // (`encode.mjs` refuses values deeper than 1000), and parsing it
726        // recurses once per level: a roomy stack, not serde's 128 limit.
727        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    /// The request that opens a page with `data`, and the page's number.
787    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    /// Send slow-request notes to `notes` instead of stderr, the first
814    /// after `first` and then every `next` (tests).
815    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    /// Whether the worker froze the data files' values when the pages'
826    /// calls began (`Ok`), or walks them after every call, and why (`Err`).
827    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    /// One line of what the requests cost so far (`BRRRTY_JS_TRACE`).
836    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    /// Node's process id.
851    pub fn pid(&self) -> u32 {
852        self.pid
853    }
854
855    /// The project folder the worker runs in.
856    pub fn root(&self) -> &Path {
857        &self.root
858    }
859
860    /// Send one request and wait for its reply. `what` names it in the
861    /// notes about a slow reply.
862    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    /// [`Worker::request`], answering the worker's filter questions with
877    /// `filters`.
878    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    /// Several requests sent together, and their replies in order: Node
890    /// runs them one after another without Brrrty in between, so they cost
891    /// one round trip. The list ends with the first reply that isn't a
892    /// value; the requests after it still ran.
893    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            // As many as can go in one write. Node may stop reading while
903            // it waits for an answer to a question of its own, so what is
904            // written past the first request must fit in the pipe.
905            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    /// Whether the requests can go in one write (see [`PIPE_SAFE`]).
944    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    /// Send requests together, in one write. Their replies come to the
953    /// ticket, which is waited on without the worker.
954    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        // Starting the replays hands them every definition so far, these
965        // requests' own among them: they get each one once.
966        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        // The values the requests refer to for the first time, each in a
972        // line of its own, to this worker and to the replay check's.
973        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        // The requests of one ticket say so: when the worker has lost the
990        // values one of them refers to, it runs none of the rest.
991        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    /// What the replies to a ticket's requests mean: each is logged for
1037    /// the replay check, and the results shaped as the ticket asked.
1038    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        // A call in the group changed a value the worker kept: the ones
1053        // after it ran on what it left, which a replay doesn't have.
1054        let mut unchecked = false;
1055        // When Node ran the last request of these that it answered.
1056        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                    // Node stopped before this one.
1066                    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                    // The worker forgot the values this refers to (a call
1079                    // another page made changed one): it ran nothing of
1080                    // this request or the ones sent with it after it. They
1081                    // go again, the values with them.
1082                    if results.iter().all(|r| matches!(r, JsResult::Ok(_))) {
1083                        self.table.forget();
1084                        return Finished::Again;
1085                    }
1086                    break;
1087                }
1088                // A step of the page before this one failed: the worker
1089                // ran neither this nor the ones after it.
1090                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                // Nothing runs the calls again: nothing is kept of them.
1124                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    /// The results of an operation whose requests went one part at a time.
1190    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        // The list ends with the first reply that isn't a value.
1201        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                    // Opened, then called.
1213                    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    /// The requests an operation makes, how its results are shaped, and
1239    /// the page it opens. `Err` when a value can't be handed over.
1240    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                // Whose template is calling: the worker finds that page's
1291                // own data among the collections' items by it.
1292                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    /// [`Worker::now`], for an operation with one result.
1393    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    /// Run an operation and wait for it here.
1400    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    /// Write one line to Node's stdin.
1419    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    /// Node's stdin, for a thread that writes requests ahead of their
1436    /// replies.
1437    pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
1438        locked(&self.mux.stdin).take()
1439    }
1440
1441    /// The next request id, and the line that sends `text` under it, with
1442    /// the clock and random values `feed` when the replay check hands the
1443    /// first run's back.
1444    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    /// Send one request and wait for its reply frame.
1459    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    /// Answer one of the worker's questions: run the filter it names, or,
1473    /// in the replay check, give the first run's answer.
1474    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    /// [`Worker::exchange`], answering the worker's filter questions with
1496    /// `filters` while it waits.
1497    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    /// Start waiting for a frame.
1532    pub(crate) fn wait(&self) -> Wait {
1533        self.mux.wait()
1534    }
1535
1536    /// The next frame from Node that no ticket waits for: a reply, or a
1537    /// question of its own.
1538    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    /// What a reply means.
1552    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            // The worker froze the data files' values and can't vouch for
1566            // what it then saw: this folder's builds walk them from now on.
1567            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            // The worker forgot them; ids go on rising, so none is reused.
1588            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    /// Start the replay check's two workers: they load the data again, in
1611    /// their own orders, while this one goes on, and are sent every value
1612    /// this one defines as it defines it.
1613    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            // The replays load every file again, several in one request:
1626            // none of it should take longer than all of it did here.
1627            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    /// The worker can't go on: say why, with Node's exit status when it
1644    /// exited, and the last lines of its stderr.
1645    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    /// Stop Node at once (the replay check, at a difference).
1693    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    /// Kill what is left of Node's process group: processes the site's
1711    /// code started and left running. One started in a session of its
1712    /// own (`detached`) is out of reach and keeps running, as under 11ty.
1713    fn stop_group(&mut self) {
1714        #[cfg(unix)]
1715        kill_group(self.pid);
1716        live(self.pid, false);
1717    }
1718
1719    /// Wait briefly for the rest of Node's stderr, then stop waiting: a
1720    /// process Node started may hold it open for as long as it runs.
1721    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
1741/// The filters for requests that run computed data: the worker's own.
1742fn 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
1785/// `{"op":"<op>"` and the fields `rest` writes, closed.
1786fn 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
1794/// `[[key, why], ...]` as JSON text.
1795fn 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    /// `templateLoad`: a JavaScript template or layout, or with `custom` (extension, content) a
1821    /// file of a custom extension.
1822    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        // The worker says `same` when the value is the one it sent last
1876        // time for this file, and the decoded value is used again: equal
1877        // data, and the same objects, which Brrrty compares cheaply.
1878        self.earlier = self.last_loaded.get(&key).cloned();
1879        // What a module exports as it is (no function to call, no getter)
1880        // is the same every time: one request, however many templates the
1881        // file applies to.
1882        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    /// Evaluate the `---js` front matter `code` of `file` the way 11ty 3 does.
1909    fn front_matter(&mut self, code: &str, file: &Path, input_path: &str) -> JsResult<Decoded> {
1910        let what = self.shown(file);
1911        let text = op_text("frontMatter", |t| {
1912            t.push_str(",\"code\":");
1913            crate::wire::string(t, code);
1914            t.push_str(",\"path\":");
1915            crate::wire::string(t, &file.to_string_lossy());
1916            t.push_str(",\"inputPath\":");
1917            crate::wire::string(t, input_path);
1918        });
1919        self.earlier = None;
1920        self.request(Request::new("frontMatter", text), &what)
1921    }
1922
1923    fn load_config(&mut self, file: &Path) -> JsResult<Decoded> {
1924        let what = self.shown(file);
1925        let cli = self.cli_dirs.clone();
1926        let text = op_text("configLoad", |t| {
1927            t.push_str(",\"path\":");
1928            crate::wire::string(t, &file.to_string_lossy());
1929            t.push_str(",\"cli\":{");
1930            let mut first = true;
1931            for (key, v) in [("input", &cli.0), ("output", &cli.1)] {
1932                if let Some(v) = v {
1933                    if !first {
1934                        t.push(',');
1935                    }
1936                    first = false;
1937                    crate::wire::string(t, key);
1938                    t.push(':');
1939                    crate::wire::string(t, v);
1940                }
1941            }
1942            t.push('}');
1943        });
1944        self.earlier = None;
1945        self.request(
1946            Request {
1947                path: Some(file),
1948                ..Request::new("configLoad", text)
1949            },
1950            &what,
1951        )
1952    }
1953
1954    fn call(
1955        &mut self,
1956        f: FnHandle,
1957        this: This<'_>,
1958        args: &[Value],
1959        settle: Settle,
1960    ) -> JsResult<Decoded> {
1961        let op = Op::Call {
1962            f,
1963            this,
1964            args,
1965            settle,
1966        };
1967        self.one(op, &mut no_filters())
1968    }
1969
1970    fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
1971        let (reqs, shape, page, what) = match self.op_requests(op) {
1972            Ok(r) => r,
1973            Err(why) => {
1974                return Begun::Done(Finished::Results {
1975                    results: vec![JsResult::Refused(Refusal::new(why))],
1976                    page: None,
1977                });
1978            }
1979        };
1980        if !Worker::fits(&reqs) {
1981            // Too much to send ahead of the first reply: one part at a
1982            // time, here.
1983            let results = self.requests(reqs, what, filters);
1984            let done = Done {
1985                sent: Vec::new(),
1986                frames: Vec::new(),
1987                asked: Vec::new(),
1988                failure: None,
1989                what: what.to_string(),
1990                shape,
1991                page,
1992                waited: Duration::ZERO,
1993            };
1994            return Begun::Done(self.shaped(done, results));
1995        }
1996        match self.send(reqs, what, shape, page) {
1997            Ok(ticket) => Begun::Sent(Box::new(ticket)),
1998            Err(f) => Begun::Done(Finished::Results {
1999                results: vec![JsResult::Failed(f)],
2000                page: None,
2001            }),
2002        }
2003    }
2004
2005    fn finish(&mut self, waited: Waited) -> Finished {
2006        match waited.0.downcast::<Done>() {
2007            Ok(done) => self.settle(*done),
2008            Err(_) => Finished::Results {
2009                results: vec![JsResult::Failed(
2010                    self.fail("replies that aren't this worker's"),
2011                )],
2012                page: None,
2013            },
2014        }
2015    }
2016
2017    fn page_open(
2018        &mut self,
2019        data: &Value,
2020        traps: &[(String, String)],
2021        defaults: &[String],
2022    ) -> JsResult<PageId> {
2023        let (page, open) = match self.open_request(data, traps, defaults) {
2024            Ok(r) => r,
2025            Err(why) => return JsResult::Refused(Refusal::new(why)),
2026        };
2027        match self.request(open, "a page's data") {
2028            JsResult::Ok(_) => JsResult::Ok(PageId(page.0)),
2029            JsResult::Thrown(e) => JsResult::Thrown(e),
2030            JsResult::Refused(r) => JsResult::Refused(r),
2031            JsResult::Failed(f) => JsResult::Failed(f),
2032        }
2033    }
2034
2035    fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
2036        let r = self.request(vars_request(page, f, keys), "a computed data function");
2037        match r {
2038            JsResult::Ok(d) => match strings(&d.value) {
2039                Some(list) => JsResult::Ok(list),
2040                None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
2041            },
2042            JsResult::Thrown(e) => JsResult::Thrown(e),
2043            JsResult::Refused(r) => JsResult::Refused(r),
2044            JsResult::Failed(f) => JsResult::Failed(f),
2045        }
2046    }
2047
2048    fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
2049        self.request(call_request(page, f, set), "a computed data function")
2050    }
2051
2052    fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
2053        let mut added = Added::default();
2054        let mut text = String::with_capacity(128);
2055        let _ = write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
2056        crate::wire::string(&mut text, key);
2057        text.push_str(",\"value\":");
2058        if let Err(why) = self.table.argument(value, false, &mut text, &mut added) {
2059            return JsResult::Refused(Refusal::new(why));
2060        }
2061        text.push('}');
2062        unit(self.request(
2063            Request {
2064                added,
2065                ..Request::new("pageSet", text)
2066            },
2067            "a page's data",
2068        ))
2069    }
2070
2071    fn page_close(&mut self, page: PageId) {
2072        // Nothing comes back from it.
2073        let _ = self.requests(
2074            vec![close_request(page)],
2075            "a page's data",
2076            &mut no_filters(),
2077        );
2078    }
2079
2080    fn page_once(
2081        &mut self,
2082        data: &Value,
2083        traps: &[(String, String)],
2084        defaults: &[String],
2085        f: FnHandle,
2086    ) -> JsResult<Decoded> {
2087        let op = Op::PageOnce {
2088            data,
2089            traps,
2090            defaults,
2091            f,
2092        };
2093        self.one(op, &mut no_filters())
2094    }
2095
2096    fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
2097        let filters = self.filters.clone();
2098        self.now(
2099            Op::PageRun { page, steps },
2100            &mut |name: &str, args: &[Value]| match &filters {
2101                Some(f) => f(name, args),
2102                None => Err(format!(
2103                    "calls `this.{name}` where Brrrty has no filters to run it"
2104                )),
2105            },
2106        )
2107    }
2108
2109    fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
2110        self.global_end = self.load_log.len();
2111        let d = match self.request(
2112            Request::new("loadsChanged", op_text("loadsChanged", |_| {})),
2113            "the data files",
2114        ) {
2115            JsResult::Ok(d) => d,
2116            JsResult::Thrown(e) => return JsResult::Thrown(e),
2117            JsResult::Refused(r) => return JsResult::Refused(r),
2118            JsResult::Failed(f) => return JsResult::Failed(f),
2119        };
2120        let Value::Array(items) = &d.value else {
2121            return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
2122        };
2123        let mut out = Vec::new();
2124        for (i, item) in items.iter().enumerate() {
2125            let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
2126                return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
2127            };
2128            let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
2129                match at {
2130                    [PathPart::Index(j), PathPart::Key(k), rest @ ..]
2131                        if *j == i && k == "value" =>
2132                    {
2133                        Some(rest.to_vec())
2134                    }
2135                    _ => None,
2136                }
2137            };
2138            out.push((
2139                PathBuf::from(&*p),
2140                Decoded {
2141                    value,
2142                    functions: d
2143                        .functions
2144                        .iter()
2145                        .filter_map(|(at, h)| under(at).map(|a| (a, *h)))
2146                        .collect(),
2147                    refused: d
2148                        .refused
2149                        .iter()
2150                        .filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
2151                        .collect(),
2152                },
2153            ));
2154        }
2155        JsResult::Ok(out)
2156    }
2157
2158    fn begin_calls(&mut self) -> JsResult<()> {
2159        let frame = match self.exchange(&op_text("callsBegin", |_| {}), None, "the data files") {
2160            Ok(f) => f,
2161            Err(f) => return JsResult::Failed(f),
2162        };
2163        let head = &frame.head;
2164        self.load_handles = head.get("handles").and_then(Json::as_u64).unwrap_or(0);
2165        self.frozen = head.get("exports").and_then(Json::as_str) == Some("frozen");
2166        self.walks = head.get("walks").and_then(Json::as_str).map(str::to_string);
2167        self.table.load_handles = Some(u32::try_from(self.load_handles).unwrap_or(u32::MAX));
2168        self.calls_begun = true;
2169        if trace() {
2170            self.trace("the data files loaded");
2171            match self.exports_frozen() {
2172                Ok(()) => {
2173                    eprintln!("note: the data files' values are frozen while pages call functions")
2174                }
2175                Err(why) => {
2176                    eprintln!("note: the data files' values are walked after every call ({why})")
2177                }
2178            }
2179        }
2180        let changed: Vec<&str> = head
2181            .get("changed")
2182            .and_then(Json::as_array)
2183            .map(|a| a.iter().filter_map(Json::as_str).collect())
2184            .unwrap_or_default();
2185        if !changed.is_empty() {
2186            return JsResult::Refused(Refusal {
2187                why: format!(
2188                    "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",
2189                    if changed.len() == 1 { "file" } else { "files" },
2190                    changed.join(", ")
2191                ),
2192                impure: true,
2193            });
2194        }
2195        if head.get("protos").and_then(Json::as_bool) == Some(true) {
2196            return JsResult::Refused(Refusal {
2197                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(),
2198                impure: true,
2199            });
2200        }
2201        // Template and directory data files and templates load in an order
2202        // of 11ty's own: with any, the check runs even when no page calls
2203        // a function, so it starts now.
2204        if self.load_log.len() > self.global_end {
2205            self.start_replays();
2206        }
2207        JsResult::Ok(())
2208    }
2209
2210    fn set_filters(&mut self, filters: Filters) {
2211        self.filters = Some(filters);
2212    }
2213
2214    fn template_setup(&mut self, filters: &[String], node: &[(String, u32)]) -> JsResult<()> {
2215        let text = op_text("templateSetup", |t| {
2216            t.push_str(",\"filters\":");
2217            crate::wire::strings(t, filters);
2218            // The config's own filters, which Node runs itself.
2219            t.push_str(",\"node\":[");
2220            for (i, (name, handle)) in node.iter().enumerate() {
2221                if i > 0 {
2222                    t.push(',');
2223                }
2224                t.push('[');
2225                crate::wire::string(t, name);
2226                let _ = write!(t, ",{handle}]");
2227            }
2228            t.push(']');
2229        });
2230        unit(self.request(
2231            Request::new("templateSetup", text),
2232            "the JavaScript templates' setup",
2233        ))
2234    }
2235
2236    fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate> {
2237        self.load_template_as(file, layout, None)
2238    }
2239
2240    fn load_custom_template(
2241        &mut self,
2242        file: &Path,
2243        ext: &str,
2244        content: &str,
2245    ) -> JsResult<LoadedTemplate> {
2246        self.load_template_as(file, false, Some((ext, content)))
2247    }
2248
2249    fn render(
2250        &mut self,
2251        template: TemplateId,
2252        data: &Value,
2253        first: Option<&Value>,
2254        traps: &[(String, String)],
2255        filters: &mut FilterCall<'_>,
2256    ) -> JsResult<Decoded> {
2257        let op = Op::Render {
2258            template,
2259            data,
2260            first,
2261            traps,
2262        };
2263        self.one(op, filters)
2264    }
2265
2266    fn verify(&mut self) -> JsResult<()> {
2267        // What the calls changed of the data files' values comes first: it
2268        // explains whatever the replay would find.
2269        match self.request(
2270            Request::new("exportsFinal", op_text("exportsFinal", |_| {})),
2271            "the data files' values",
2272        ) {
2273            JsResult::Ok(_) => {}
2274            other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
2275                return match other {
2276                    JsResult::Refused(r) => JsResult::Refused(r),
2277                    JsResult::Failed(f) => JsResult::Failed(f),
2278                    _ => JsResult::Ok(()),
2279                };
2280            }
2281            JsResult::Thrown(e) => return JsResult::Thrown(e),
2282        }
2283        // Nothing to check: no page called a function, and no template or
2284        // template or directory data file loaded.
2285        if self.frozen {
2286            walk_roots().froze(&self.root);
2287        }
2288        let Some(replays) = self.replays.take() else {
2289            return JsResult::Ok(());
2290        };
2291        let calls = Arc::new(crate::replay::Calls {
2292            records: {
2293                // The order Node ran them in, not the order the render
2294                // threads took their replies: the replay check's orders are
2295                // made from this one, and must differ from it.
2296                let mut records = std::mem::take(&mut self.call_log);
2297                records.sort_by_key(|r| r.at);
2298                records
2299            },
2300            load_handles: self.load_handles,
2301            slowest: self.slowest,
2302            dynamic: std::mem::take(&mut self.table.dynamic),
2303            lines: self.table.lines.clone(),
2304            dropped: self.dropped,
2305        });
2306        if trace() {
2307            self.trace("the pages' calls ended");
2308        }
2309        let checking = Instant::now();
2310        let [a, b] = replays;
2311        a.run(calls.clone());
2312        b.run(calls);
2313        let (a, b) = (a.finish(), b.finish());
2314        if trace() {
2315            eprintln!(
2316                "note: the replay check took {:.3} s after the build's own calls",
2317                checking.elapsed().as_secs_f64()
2318            );
2319        }
2320        match a.and(b) {
2321            Ok(()) => JsResult::Ok(()),
2322            Err(crate::replay::Failure::Differs(why, handle)) => {
2323                let named = handle
2324                    .and_then(|h| {
2325                        let text = op_text("describe", |t| {
2326                            let _ = write!(t, ",\"handle\":{h}");
2327                        });
2328                        self.exchange(&text, None, "a function's name").ok()
2329                    })
2330                    .and_then(|f| match f.value() {
2331                        Some(Value::String(s)) => Some(s.to_string()),
2332                        _ => None,
2333                    })
2334                    .unwrap_or_else(|| "a function from JavaScript data".to_string());
2335                JsResult::Refused(Refusal {
2336                    why: why.replace("{fn}", &named),
2337                    impure: true,
2338                })
2339            }
2340            Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
2341            Err(crate::replay::Failure::Again(why)) => {
2342                walk_roots().sent_back(&self.root, &why);
2343                let mut f = self.fail(&format!(
2344                    "the JavaScript worker has to check the data files' values after every call ({why})"
2345                ));
2346                f.again = true;
2347                self.failed = Some(f.clone());
2348                JsResult::Failed(f)
2349            }
2350        }
2351    }
2352
2353    fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
2354        match self.request(
2355            Request::new("reads", op_text("reads", |_| {})),
2356            "the list of files read",
2357        ) {
2358            JsResult::Ok(d) => match strings(&d.value) {
2359                Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
2360                None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
2361            },
2362            JsResult::Thrown(e) => JsResult::Thrown(e),
2363            JsResult::Refused(r) => JsResult::Refused(r),
2364            JsResult::Failed(f) => JsResult::Failed(f),
2365        }
2366    }
2367}
2368
2369impl Drop for Worker {
2370    fn drop(&mut self) {
2371        if let Some(mut stdin) = locked(&self.mux.stdin).take() {
2372            let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
2373        }
2374        // Node finishes what a plugin left running (see the worker's `settled`) before it exits.
2375        let deadline = Instant::now() + Duration::from_secs(20);
2376        loop {
2377            let mut child = locked(&self.mux.child);
2378            match child.try_wait() {
2379                Ok(Some(_)) => break,
2380                Ok(None) if Instant::now() < deadline => {
2381                    drop(child);
2382                    std::thread::sleep(Duration::from_millis(5))
2383                }
2384                _ => {
2385                    let _ = child.kill();
2386                    let _ = child.wait();
2387                    break;
2388                }
2389            }
2390        }
2391        self.stop_group();
2392        self.finish_stderr();
2393    }
2394}
2395
2396/// The project folders whose builds found they must walk the data files'
2397/// values after each call rather than freeze them (see the worker's
2398/// "Freezing"): a build there starts that way.
2399fn walk_roots() -> MutexGuard<'static, WalkMemo> {
2400    static ROOTS: std::sync::LazyLock<Mutex<WalkMemo>> =
2401        std::sync::LazyLock::new(|| Mutex::new(WalkMemo::default()));
2402    ROOTS.lock().unwrap_or_else(|e| e.into_inner())
2403}
2404
2405/// Which folders' builds walk, and for how long. A build that was sent
2406/// back runs again walking; the build after that tries the freeze again
2407/// (under `brrrty serve` the code may have been fixed). A folder sent
2408/// back again and again walks for twice as many builds each time, up to
2409/// 64, so a site that can't be frozen stops paying for the try.
2410#[derive(Default)]
2411pub(crate) struct WalkMemo {
2412    roots: HashMap<PathBuf, Walks>,
2413}
2414
2415struct Walks {
2416    why: String,
2417    /// How many builds still start walking.
2418    left: u32,
2419    /// How many it was the last time the folder was sent back.
2420    last: u32,
2421}
2422
2423impl WalkMemo {
2424    const MOST: u32 = 64;
2425
2426    /// A build of `root` was sent back.
2427    pub(crate) fn sent_back(&mut self, root: &Path, why: &str) {
2428        let w = self.roots.entry(root.to_path_buf()).or_insert(Walks {
2429            why: String::new(),
2430            left: 0,
2431            last: 0,
2432        });
2433        // Several of one build's requests may say so.
2434        if w.left > 0 {
2435            return;
2436        }
2437        w.why = why.to_string();
2438        w.last = (w.last * 2).clamp(1, Self::MOST);
2439        w.left = w.last;
2440    }
2441
2442    /// A build of `root` starts: why it walks, if it does.
2443    pub(crate) fn starting(&mut self, root: &Path) -> Option<String> {
2444        let w = self.roots.get_mut(root)?;
2445        if w.left == 0 {
2446            return None;
2447        }
2448        w.left -= 1;
2449        Some(w.why.clone())
2450    }
2451
2452    /// A build of `root` froze and passed.
2453    pub(crate) fn froze(&mut self, root: &Path) {
2454        self.roots.remove(root);
2455    }
2456}
2457
2458/// Whether to say on stderr what the JavaScript worker's requests cost
2459/// (`BRRRTY_JS_TRACE`, for whoever looks into a slow build).
2460fn trace() -> bool {
2461    static ON: std::sync::LazyLock<bool> =
2462        std::sync::LazyLock::new(|| std::env::var_os("BRRRTY_JS_TRACE").is_some());
2463    *ON
2464}
2465
2466/// The process ids of the workers running now. Each leads its own process
2467/// group, so a terminal's Ctrl-C doesn't reach it: [`stop_all`] does.
2468static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
2469
2470/// Set once [`stop_all`] ran: a worker failing after that was stopped.
2471static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2472
2473fn live(pid: u32, running: bool) {
2474    let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2475    l.retain(|p| *p != pid);
2476    if running {
2477        l.push(pid);
2478    }
2479}
2480
2481/// Kill every running worker and what it started, at once: for Ctrl-C,
2482/// SIGTERM and a panic. Safe to call from a signal handler thread.
2483pub fn stop_all() {
2484    STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
2485    let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2486    #[cfg(unix)]
2487    for pid in l.iter() {
2488        kill_group(*pid);
2489    }
2490}
2491
2492/// Kill the worker with this process id and what it started.
2493pub(crate) fn stop_pid(pid: u32) {
2494    #[cfg(unix)]
2495    kill_group(pid);
2496    // Elsewhere there is no group: Windows stops the tree by name.
2497    #[cfg(windows)]
2498    {
2499        let _ = Command::new("taskkill")
2500            .args(["/PID", &pid.to_string(), "/T", "/F"])
2501            .stdin(Stdio::null())
2502            .stdout(Stdio::null())
2503            .stderr(Stdio::null())
2504            .status();
2505    }
2506    #[cfg(not(any(unix, windows)))]
2507    let _ = pid;
2508}
2509
2510#[cfg(unix)]
2511fn kill_group(pid: u32) {
2512    if let Ok(pid) = i32::try_from(pid) {
2513        // SAFETY: killpg only sends a signal, to the group Node leads.
2514        unsafe {
2515            libc::killpg(pid, libc::SIGKILL);
2516        }
2517    }
2518}
2519
2520/// Start the worker. Its replies come on a pipe of their own, which Node
2521/// inherits under the descriptor number it has here, and its stdout joins
2522/// its stderr: a child process or logger writing to fd 1 is only noise, as
2523/// it is under 11ty.
2524#[cfg(unix)]
2525fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2526    use std::os::fd::AsRawFd;
2527    use std::os::unix::process::CommandExt;
2528    let (frames_r, frames_w) = std::io::pipe()?;
2529    // A copy is numbered 3 or above, clear of the standard three.
2530    let frames_w = frames_w.try_clone()?;
2531    let (answers_r, answers_w) = std::io::pipe()?;
2532    let answers_r = answers_r.try_clone()?;
2533    let (err_r, err_w) = std::io::pipe()?;
2534    let fd = frames_w.as_raw_fd();
2535    let answers_fd = answers_r.as_raw_fd();
2536    cmd.stdout(err_w.try_clone()?)
2537        .stderr(err_w)
2538        .env("BRRRTY_FRAMES_FD", fd.to_string())
2539        .env("BRRRTY_ANSWERS_FD", answers_fd.to_string())
2540        // A group of its own, so what Node starts can be stopped with it.
2541        .process_group(0);
2542    // SAFETY: fcntl is async-signal-safe, and the descriptor is this
2543    // process's own, open until after the spawn.
2544    unsafe {
2545        cmd.pre_exec(move || {
2546            // Keep it open across exec in Node only.
2547            if libc::fcntl(fd, libc::F_SETFD, 0) == -1
2548                || libc::fcntl(answers_fd, libc::F_SETFD, 0) == -1
2549            {
2550                return Err(std::io::Error::last_os_error());
2551            }
2552            Ok(())
2553        });
2554    }
2555    let child = cmd.spawn();
2556    // The parent's write ends close here, so the reads end when Node's do.
2557    drop(cmd);
2558    drop(frames_w);
2559    drop(answers_r);
2560    Ok((
2561        child?,
2562        Box::new(frames_r),
2563        Box::new(err_r),
2564        Some(Box::new(answers_w)),
2565    ))
2566}
2567
2568/// A started Node: the process, its replies, its stderr, and where
2569/// Brrrty answers its questions (none where that pipe can't be passed).
2570type Spawned = (
2571    Child,
2572    Box<dyn Read + Send>,
2573    Box<dyn Read + Send>,
2574    Option<Box<dyn Write + Send>>,
2575);
2576
2577/// Start the worker, its replies on stdout.
2578#[cfg(not(unix))]
2579fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2580    let mut child = cmd
2581        .stdout(Stdio::piped())
2582        .stderr(Stdio::piped())
2583        .env("BRRRTY_FRAMES_FD", "1")
2584        .spawn()?;
2585    let stdout = child.stdout.take().expect("piped stdout");
2586    let stderr = child.stderr.take().expect("piped stderr");
2587    Ok((child, Box::new(stdout), Box::new(stderr), None))
2588}
2589
2590#[cfg(unix)]
2591fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
2592    use std::os::unix::process::ExitStatusExt;
2593    s.signal()
2594}
2595
2596#[cfg(not(unix))]
2597fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
2598    None
2599}
2600
2601/// Read `\x1eBRRRTY <kind> <id> <clock length> <body length>\n<clock><body>`
2602/// frames until Node closes its output. Anything else is a protocol error,
2603/// sent once.
2604fn read_frames(stdout: impl Read, tx: mpsc::Sender<Reply>, decoding: Arc<AtomicBool>, mux: &Mux) {
2605    read_frames_to(stdout, &tx, decoding, mux);
2606    // No more frames: whoever waits for one learns so.
2607    locked(&mux.routes).clear();
2608}
2609
2610fn read_frames_to(
2611    stdout: impl Read,
2612    tx: &mpsc::Sender<Reply>,
2613    decoding: Arc<AtomicBool>,
2614    mux: &Mux,
2615) {
2616    let mut r = BufReader::with_capacity(1 << 16, stdout);
2617    let mut seq = 0u64;
2618    loop {
2619        seq += 1;
2620        let mut header = Vec::new();
2621        match r.read_until(b'\n', &mut header) {
2622            Ok(0) => return,
2623            Ok(_) => {}
2624            Err(e) => {
2625                let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
2626                return;
2627            }
2628        }
2629        let fields = header
2630            .strip_prefix(b"\x1eBRRRTY ")
2631            .and_then(|h| h.strip_suffix(b"\n"))
2632            .and_then(|h| std::str::from_utf8(h).ok())
2633            .and_then(|h| {
2634                let mut it = h.split(' ');
2635                let kind = it.next()?;
2636                let id = it.next()?.parse::<u64>().ok()?;
2637                let clock = it.next()?.parse::<usize>().ok()?;
2638                let body = it.next()?.parse::<usize>().ok()?;
2639                (it.next().is_none() && matches!(kind, "r" | "f" | "q"))
2640                    .then_some((kind, id, clock, body))
2641            });
2642        let Some((kind, id, clock_len, body_len)) = fields else {
2643            let shown = String::from_utf8_lossy(&header);
2644            let _ = tx.send(Err(format!(
2645                "something other than the worker wrote to its output: {:?}",
2646                shown.chars().take(80).collect::<String>()
2647            )));
2648            return;
2649        };
2650        let mut read = |len: usize| -> Result<String, String> {
2651            let mut bytes = vec![0; len];
2652            r.read_exact(&mut bytes)
2653                .map_err(|e| format!("a cut-off reply: {e}"))?;
2654            String::from_utf8(bytes).map_err(|_| "a reply that isn't UTF-8".to_string())
2655        };
2656        let parts = read(clock_len).and_then(|c| read(body_len).map(|b| (c, b)));
2657        let (clock, body) = match parts {
2658            Ok(p) => p,
2659            Err(e) => {
2660                let _ = tx.send(Err(e));
2661                return;
2662            }
2663        };
2664        let decode_ok = decoding.load(std::sync::atomic::Ordering::Relaxed);
2665        let parsed = parse_reply(body.as_bytes()).map(|mut head| {
2666            let value = head.as_object_mut().and_then(|o| o.remove("ok"));
2667            let ok = if decode_ok || kind == "q" {
2668                value.as_ref().map(decode)
2669            } else {
2670                None
2671            };
2672            Frame {
2673                question: kind == "q",
2674                id,
2675                head,
2676                ok,
2677                body: body.into_boxed_str(),
2678                clock: (!clock.is_empty()).then(|| clock.into_boxed_str()),
2679                made: kind == "f",
2680                seq,
2681            }
2682        });
2683        // A frame a ticket waits for goes to it; any other to the worker.
2684        let route = match &parsed {
2685            Ok(f) => locked(&mux.routes).get(&f.id).cloned(),
2686            Err(_) => None,
2687        };
2688        let sent = match route {
2689            Some(to) => to.send(parsed).is_ok(),
2690            None => tx.send(parsed).is_ok(),
2691        };
2692        if !sent && locked(&mux.routes).is_empty() {
2693            return;
2694        }
2695    }
2696}
2697
2698/// A list of strings, as `reads` and `varsUsed` reply.
2699fn strings(v: &Value) -> Option<Vec<String>> {
2700    match v {
2701        Value::Array(a) => a
2702            .iter()
2703            .map(|s| match s {
2704                Value::String(s) => Some(s.to_string()),
2705                _ => None,
2706            })
2707            .collect(),
2708        _ => None,
2709    }
2710}
2711
2712/// One reply body, without serde's nesting limit (see [`REPLY_STACK`]).
2713pub(crate) fn parse_reply(body: &[u8]) -> Result<Json, String> {
2714    let mut de = serde_json::Deserializer::from_slice(body);
2715    de.disable_recursion_limit();
2716    let v = serde::Deserialize::deserialize(&mut de)
2717        .and_then(|v: Json| de.end().map(|()| v))
2718        .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
2719    Ok(v)
2720}
2721
2722/// Pass Node's stderr through to Brrrty's, as it comes, keeping the last
2723/// lines for a failure report.
2724fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
2725    let mut r = BufReader::new(stderr);
2726    let mut line = Vec::new();
2727    let mut err = std::io::stderr();
2728    loop {
2729        line.clear();
2730        match r.read_until(b'\n', &mut line) {
2731            Ok(0) | Err(_) => return,
2732            Ok(_) => {
2733                let _ = err.write_all(&line);
2734                if let Ok(mut t) = tail.lock() {
2735                    if t.len() == STDERR_TAIL {
2736                        t.pop_front();
2737                    }
2738                    t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
2739                }
2740            }
2741        }
2742    }
2743}
2744
2745/// The site's error, placed: a SyntaxError at the header Node prints for
2746/// it, anything else at the first stack frame inside the project and
2747/// outside `node_modules`.
2748fn js_error(t: &Json, root: &Path) -> JsError {
2749    let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
2750    let stack = s("stack");
2751    let place = crate::stack::syntax_header(&s("inspect"))
2752        .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
2753    JsError {
2754        name: s("name"),
2755        message: s("message"),
2756        file: place.as_ref().map(|p| p.file.clone()),
2757        line: place.as_ref().map(|p| p.line),
2758        column: place.and_then(|p| p.column),
2759        stack,
2760        invalid: false,
2761    }
2762}
2763
2764/// A Brrrty value in the worker's wire forms.
2765pub fn encode(v: &Value) -> Json {
2766    match v {
2767        Value::Undefined => json!({"$u": 1}),
2768        Value::Null => Json::Null,
2769        Value::Bool(b) => Json::Bool(*b),
2770        Value::Number(n) => {
2771            if n.is_nan() {
2772                json!({"$n": "NaN"})
2773            } else if *n == f64::INFINITY {
2774                json!({"$n": "Infinity"})
2775            } else if *n == f64::NEG_INFINITY {
2776                json!({"$n": "-Infinity"})
2777            } else if *n == 0.0 && n.is_sign_negative() {
2778                json!({"$n": "-0"})
2779            } else {
2780                serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
2781            }
2782        }
2783        Value::String(s) => Json::String(s.to_string()),
2784        Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
2785        Value::Object(o) => {
2786            json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
2787        }
2788        Value::Date(d) => json!({"$d": d.timestamp_millis()}),
2789        Value::Function(h) => json!({"$f": h.0}),
2790    }
2791}
2792
2793#[cfg(test)]
2794mod source {
2795    /// The comments are left out of what Node runs, each leaving its
2796    /// line behind, so a line number in a stack trace is the file's.
2797    #[test]
2798    fn the_worker_source_keeps_the_files_line_numbers() {
2799        let source = super::worker_source();
2800        // Line numbers are the file's.
2801        assert_eq!(source.lines().count(), super::WORKER_SOURCE.lines().count());
2802        assert!(!source.lines().any(|l| l.trim_start().starts_with("//")));
2803    }
2804}
2805
2806#[cfg(test)]
2807mod source_size {
2808    use super::*;
2809
2810    /// A worker whose source is past 128 KiB starts: Linux refuses one
2811    /// command-line argument that long, so the source goes by file.
2812    #[test]
2813    fn a_worker_larger_than_one_argument_starts() {
2814        let node = match crate::find::find_node(None) {
2815            Ok(n) => n,
2816            Err(e) => {
2817                assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2818                eprintln!("skipped: {e}");
2819                return;
2820            }
2821        };
2822        tests_pad::PAD.with(|p| p.set(200 * 1024));
2823        let t = tempfile::tempdir().unwrap();
2824        let file = t.path().join("h.js");
2825        std::fs::write(&file, "module.exports = { a() { return 'ok'; } };").unwrap();
2826        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2827        assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2828    }
2829}
2830
2831#[cfg(test)]
2832mod walk_memo {
2833    use super::WalkMemo;
2834    use std::path::Path;
2835
2836    /// A build sent back runs again walking, and the one after tries the
2837    /// freeze again; a folder sent back every time walks for longer and
2838    /// longer, and one that freezes is forgotten.
2839    #[test]
2840    fn a_folder_sent_back_walks_for_a_while_not_for_good() {
2841        let root = Path::new("/site");
2842        let mut m = WalkMemo::default();
2843        assert_eq!(m.starting(root), None);
2844        m.sent_back(root, "why");
2845        // Several requests of the one build may say so.
2846        m.sent_back(root, "another request");
2847        assert_eq!(m.starting(root).as_deref(), Some("why"));
2848        // The build after the rerun tries again.
2849        assert_eq!(m.starting(root), None);
2850        m.sent_back(root, "again");
2851        assert_eq!(m.starting(root).as_deref(), Some("again"));
2852        assert_eq!(m.starting(root).as_deref(), Some("again"));
2853        assert_eq!(m.starting(root), None);
2854        m.sent_back(root, "third");
2855        let walked = std::iter::from_fn(|| m.starting(root)).count();
2856        assert_eq!(walked, 4);
2857        for _ in 0..10 {
2858            m.sent_back(root, "more");
2859            while m.starting(root).is_some() {}
2860        }
2861        m.sent_back(root, "most");
2862        assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 64);
2863        // A build that froze and passed starts over.
2864        m.froze(root);
2865        m.sent_back(root, "new");
2866        assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 1);
2867    }
2868}
2869
2870#[cfg(test)]
2871mod skipped_definition {
2872    use super::*;
2873
2874    /// A definition that refers to a value the worker forgot is skipped
2875    /// (Brrrty wrote it before it heard of the change), and so is all of
2876    /// it: the ids it had handed out before it met the forgotten value
2877    /// held objects half read, with wire markers still inside. A request
2878    /// that names one is told it is stale, like any forgotten value, and
2879    /// the worker goes on.
2880    #[test]
2881    fn a_skipped_definition_leaves_none_of_its_values_behind() {
2882        let node = match crate::find::find_node(None) {
2883            Ok(n) => n,
2884            Err(e) => {
2885                assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2886                eprintln!("skipped: {e}");
2887                return;
2888            }
2889        };
2890        let t = tempfile::tempdir().unwrap();
2891        let file = t.path().join("h.js");
2892        std::fs::write(
2893            &file,
2894            "module.exports = { poke(o) { o.k = 2; return ''; }, show(v) { return JSON.stringify(v); } };",
2895        )
2896        .unwrap();
2897        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2898        assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2899        w.exchange(r#"{"op":"callsBegin"}"#, None, "the calls' start")
2900            .expect("begins");
2901        let call = |w: &mut Worker, handle: u32, arg: u32| {
2902            w.exchange(
2903                &format!(
2904                    r#"{{"op":"call","handle":{handle},"await":false,"this":{{"$u":1}},"args":[{{"$R":{arg}}}]}}"#
2905                ),
2906                None,
2907                "a call",
2908            )
2909            .expect("answers")
2910        };
2911        // A kept value, which `poke` changes: the worker forgets it.
2912        w.write_line(r#"{"op":"def","id":50,"v":{"k":1},"n":1}"#)
2913            .unwrap();
2914        let poked = call(&mut w, 0, 50);
2915        assert!(poked.head.get("dropShared").is_some(), "{}", poked.body);
2916        // Written before Brrrty heard: it refers to the forgotten value,
2917        // after two values of its own.
2918        w.write_line(r#"{"op":"def","id":60,"v":{"a":{"x":1},"o":{"$R":50}},"n":2}"#)
2919            .unwrap();
2920        for id in [60, 61, 50] {
2921            let shown = call(&mut w, 1, id);
2922            assert_eq!(
2923                shown.head.get("stale"),
2924                Some(&Json::Bool(true)),
2925                "value {id}: {}",
2926                shown.body
2927            );
2928        }
2929        // And the worker is none the worse: the values sent again work.
2930        w.write_line(r#"{"op":"def","id":70,"v":{"a":{"x":1},"o":{"k":1}},"n":3}"#)
2931            .unwrap();
2932        let shown = call(&mut w, 1, 70);
2933        assert!(
2934            shown.body.contains(r#"{\"a\":{\"x\":1},\"o\":{\"k\":1}}"#),
2935            "{}",
2936            shown.body
2937        );
2938    }
2939}