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    /// The replay check's two workers, started as soon as there is
555    /// something for them to check.
556    replays: Option<[crate::replay::Handle; 2]>,
557    /// The replay check runs (see [`Worker::start_with`]).
558    order_check: bool,
559    /// The longest a request took.
560    slowest: Duration,
561    /// How long a request may take before the worker is given up on (the
562    /// replay check's workers only).
563    pub(crate) deadline: Option<Duration>,
564    /// The template id of the last `templateLoad` reply.
565    last_template: Option<u64>,
566    next_ticket: u64,
567    /// What the requests cost, for `BRRRTY_JS_TRACE`.
568    stats: Stats,
569    /// The worker froze the data files' values when the calls began.
570    frozen: bool,
571    /// Why this worker was started walking, when Brrrty asked it to.
572    walk: Option<String>,
573    /// Why it walks them instead, when it does.
574    walks: Option<String>,
575}
576
577/// What a worker's requests cost so far.
578#[derive(Default)]
579struct Stats {
580    started: Option<Instant>,
581    requests: u64,
582    /// Bytes of requests, and of definitions.
583    sent: u64,
584    defined: u64,
585    definitions: u64,
586    /// Bytes of replies.
587    received: u64,
588    /// Time between a request going out and its reply coming in.
589    waited: Duration,
590}
591
592/// One request of the first run: what to send, and what the replay check
593/// needs to know of it.
594struct Request<'a> {
595    op: &'static str,
596    /// The request as JSON text, without its id.
597    text: String,
598    /// The definitions it needs sent first.
599    added: Added,
600    /// The function it calls.
601    handle: Option<u32>,
602    /// The file it loads.
603    path: Option<&'a Path>,
604    /// Nothing comes back from it (`pageClose`).
605    one_way: bool,
606}
607
608impl<'a> Request<'a> {
609    fn new(op: &'static str, text: String) -> Request<'a> {
610        Request {
611            op,
612            text,
613            added: Added::default(),
614            handle: None,
615            path: None,
616            one_way: false,
617        }
618    }
619}
620
621/// A wait for one frame: when it began, and when the next note is due.
622pub(crate) struct Wait {
623    start: Instant,
624    next_note: Instant,
625    /// Node exiting ends the wait even when a process it started keeps
626    /// the replies' pipe open.
627    exited_at: Option<Instant>,
628}
629
630impl Worker {
631    /// Start Node with the worker, in `root` (the project folder), with
632    /// 11ty's environment variables added to Brrrty's own.
633    pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
634        Worker::start_as(node, root, run_mode, None)
635    }
636
637    /// [`Worker::start`]; `replay` for one of the replay check's workers.
638    pub(crate) fn start_as(
639        node: &NodeInfo,
640        root: &Path,
641        run_mode: RunMode,
642        replay: Option<&crate::replay::Loads>,
643    ) -> Result<Worker, WorkerError> {
644        Worker::start_checked(node, root, run_mode, replay, true)
645    }
646
647    /// [`Worker::start`], with or without the replay check: without it
648    /// the site's JavaScript runs once, in this worker's Node alone, and
649    /// nothing is kept of the calls to run them again.
650    pub fn start_with(
651        node: &NodeInfo,
652        root: &Path,
653        run_mode: RunMode,
654        order_check: bool,
655    ) -> Result<Worker, WorkerError> {
656        Worker::start_checked(node, root, run_mode, None, order_check)
657    }
658
659    fn start_checked(
660        node: &NodeInfo,
661        root: &Path,
662        run_mode: RunMode,
663        replay: Option<&crate::replay::Loads>,
664        order_check: bool,
665    ) -> Result<Worker, WorkerError> {
666        // The build's own worker asks whether this folder's builds walk;
667        // the replay check's workers do as it did.
668        let walk = match replay {
669            Some(loads) => loads.walk.clone(),
670            None => walk_roots().starting(root),
671        };
672        // Linux takes no single argument of 128 KiB or more, so Node reads
673        // the source from a file in a folder of its own, removed with the
674        // worker.
675        let cannot =
676            |e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
677        let source_dir = tempfile::Builder::new()
678            .prefix("brrrty-worker-")
679            .tempdir()
680            .map_err(cannot)?;
681        let source_file = source_dir.path().join(SOURCE_FILE);
682        std::fs::write(&source_file, worker_source().as_bytes()).map_err(cannot)?;
683        let mut cmd = Command::new(&node.path);
684        cmd.arg(&source_file)
685            .current_dir(root)
686            .env("ELEVENTY_ROOT", root)
687            .env("ELEVENTY_SOURCE", "cli")
688            .env("ELEVENTY_RUN_MODE", run_mode.as_str())
689            .env("ELEVENTY_VERSION", ELEVENTY_VERSION)
690            .stdin(Stdio::piped());
691        if let Some(why) = &walk {
692            cmd.env("BRRRTY_JS_EXPORTS", "walk");
693            cmd.env("BRRRTY_JS_WALK_WHY", why);
694        } else {
695            cmd.env_remove("BRRRTY_JS_WALK_WHY");
696        }
697        if replay.is_some() {
698            cmd.env("BRRRTY_ROLE", "replay");
699        }
700        let (mut child, frames, stderr, answers) = spawn(cmd).map_err(cannot)?;
701        let pid = child.id();
702        live(pid, true);
703        let (tx, replies) = mpsc::channel();
704        let decode = Arc::new(AtomicBool::new(true));
705        let decoding = decode.clone();
706        let stdin = child.stdin.take();
707        let mux = Arc::new(Mux {
708            child: Mutex::new(child),
709            stdin: Mutex::new(stdin),
710            answers: Mutex::new(answers),
711            routes: Mutex::new(HashMap::new()),
712            notes: Mutex::new(Box::new(|s| eprintln!("{s}"))),
713            note_times: Mutex::new((FIRST_NOTE, NEXT_NOTE)),
714        });
715        let routing = mux.clone();
716        // A reply nests up to three JSON levels per level of the value
717        // (`encode.mjs` refuses values deeper than 1000), and parsing it
718        // recurses once per level: a roomy stack, not serde's 128 limit.
719        std::thread::Builder::new()
720            .name("brrrty-node-replies".into())
721            .stack_size(REPLY_STACK)
722            .spawn(move || read_frames(frames, tx, decoding, &routing))
723            .map_err(|e| {
724                let mut child = locked(&mux.child);
725                let _ = child.kill();
726                let _ = child.wait();
727                WorkerError(format!("cannot read Node's replies: {e}"))
728            })?;
729        let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
730        let tail = stderr_tail.clone();
731        let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
732        Ok(Worker {
733            _source_dir: source_dir,
734            mux,
735            pid,
736            answers_feed: None,
737            asked: Vec::new(),
738            filters: None,
739            replies,
740            stderr_tail,
741            stderr_thread: Some(stderr_thread),
742            root: root.to_path_buf(),
743            next_id: 0,
744            next_page: 0,
745            failed: None,
746            last_loaded: HashMap::new(),
747            earlier: None,
748            fixed: std::collections::HashSet::new(),
749            last_fixed: false,
750            last_seq: 0,
751            table: Table::default(),
752            node: node.clone(),
753            run_mode,
754            decode,
755            load_log: Vec::new(),
756            global_end: 0,
757            call_log: Vec::new(),
758            dropped: false,
759            calls_begun: false,
760            load_handles: 0,
761            replays: None,
762            order_check,
763            slowest: Duration::ZERO,
764            deadline: None,
765            last_template: None,
766            next_ticket: 0,
767            stats: Stats {
768                started: Some(Instant::now()),
769                ..Stats::default()
770            },
771            frozen: false,
772            walk,
773            walks: None,
774        })
775    }
776
777    /// The request that opens a page with `data`, and the page's number.
778    fn open_request(
779        &mut self,
780        data: &Value,
781        traps: &[(String, String)],
782        defaults: &[String],
783    ) -> Result<(PageId, Request<'static>), String> {
784        self.next_page += 1;
785        let page = self.next_page;
786        let mut added = Added::default();
787        let mut text = String::with_capacity(1024);
788        let _ = write!(text, "{{\"op\":\"pageOpen\",\"page\":{page},\"data\":");
789        self.table.page_data(data, false, &mut text, &mut added)?;
790        text.push_str(",\"traps\":");
791        pairs(&mut text, traps);
792        text.push_str(",\"defaults\":");
793        crate::wire::strings(&mut text, defaults);
794        text.push('}');
795        Ok((
796            PageId(page),
797            Request {
798                added,
799                ..Request::new("pageOpen", text)
800            },
801        ))
802    }
803
804    /// Send slow-request notes to `notes` instead of stderr, the first
805    /// after `first` and then every `next` (tests).
806    pub fn set_notes(
807        &mut self,
808        notes: impl Fn(&str) + Send + 'static,
809        first: Duration,
810        next: Duration,
811    ) {
812        *locked(&self.mux.notes) = Box::new(notes);
813        *locked(&self.mux.note_times) = (first, next);
814    }
815
816    /// Whether the worker froze the data files' values when the pages'
817    /// calls began (`Ok`), or walks them after every call, and why (`Err`).
818    pub fn exports_frozen(&self) -> Result<(), String> {
819        if self.frozen {
820            Ok(())
821        } else {
822            Err(self.walks.clone().unwrap_or_default())
823        }
824    }
825
826    /// One line of what the requests cost so far (`BRRRTY_JS_TRACE`).
827    fn trace(&self, at: &str) {
828        let s = &self.stats;
829        eprintln!(
830            "note: {at}, {:.3} s after Node started: {} requests ({:.1} MB) and {} definitions ({:.1} MB) sent, {:.1} MB of replies, {:.3} s waiting on Node",
831            s.started.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0),
832            s.requests,
833            s.sent as f64 / 1e6,
834            s.definitions,
835            s.defined as f64 / 1e6,
836            s.received as f64 / 1e6,
837            s.waited.as_secs_f64(),
838        );
839    }
840
841    /// Node's process id.
842    pub fn pid(&self) -> u32 {
843        self.pid
844    }
845
846    /// The project folder the worker runs in.
847    pub fn root(&self) -> &Path {
848        &self.root
849    }
850
851    /// Send one request and wait for its reply. `what` names it in the
852    /// notes about a slow reply.
853    fn request(&mut self, req: Request<'_>, what: &str) -> JsResult<Decoded> {
854        let filters = self.filters.clone();
855        self.request_with(
856            req,
857            what,
858            &mut |name: &str, args: &[Value]| match &filters {
859                Some(f) => f(name, args),
860                None => Err(format!(
861                    "calls `this.{name}` where Brrrty has no filters to run it"
862                )),
863            },
864        )
865    }
866
867    /// [`Worker::request`], answering the worker's filter questions with
868    /// `filters`.
869    fn request_with(
870        &mut self,
871        req: Request<'_>,
872        what: &str,
873        filters: &mut FilterCall<'_>,
874    ) -> JsResult<Decoded> {
875        self.requests(vec![req], what, filters)
876            .pop()
877            .unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
878    }
879
880    /// Several requests sent together, and their replies in order: Node
881    /// runs them one after another without Brrrty in between, so they cost
882    /// one round trip. The list ends with the first reply that isn't a
883    /// value; the requests after it still ran.
884    fn requests(
885        &mut self,
886        reqs: Vec<Request<'_>>,
887        what: &str,
888        filters: &mut FilterCall<'_>,
889    ) -> Vec<JsResult<Decoded>> {
890        let mut out = Vec::with_capacity(reqs.len());
891        let mut reqs = reqs.into_iter().peekable();
892        while reqs.peek().is_some() {
893            // As many as can go in one write. Node may stop reading while
894            // it waits for an answer to a question of its own, so what is
895            // written past the first request must fit in the pipe.
896            let mut group = Vec::new();
897            let mut ahead = 0;
898            while let Some(next) = reqs.peek() {
899                if !group.is_empty() && ahead + next.text.len() + 48 > PIPE_SAFE {
900                    break;
901                }
902                if !group.is_empty() {
903                    ahead += next.text.len() + 48;
904                }
905                group.extend(reqs.next());
906            }
907            let ticket = match self.send(group, what, Shape::List, None) {
908                Ok(t) => t,
909                Err(f) => {
910                    out.push(JsResult::Failed(f));
911                    return out;
912                }
913            };
914            let done = ticket.collect(filters);
915            match self.settle(done) {
916                Finished::Results { results, .. } => {
917                    let stop = results.iter().any(|r| !matches!(r, JsResult::Ok(_)));
918                    out.extend(results);
919                    if stop {
920                        return out;
921                    }
922                }
923                Finished::Again => {
924                    out.push(JsResult::Failed(
925                        self.fail("the worker lost the values a request referred to"),
926                    ));
927                    return out;
928                }
929            }
930        }
931        out
932    }
933
934    /// Whether the requests can go in one write (see [`PIPE_SAFE`]).
935    fn fits(reqs: &[Request<'_>]) -> bool {
936        reqs.iter()
937            .skip(1)
938            .map(|r| r.text.len() + 48)
939            .sum::<usize>()
940            <= PIPE_SAFE
941    }
942
943    /// Send requests together, in one write. Their replies come to the
944    /// ticket, which is waited on without the worker.
945    fn send(
946        &mut self,
947        reqs: Vec<Request<'_>>,
948        what: &str,
949        shape: Shape,
950        page: Option<PageId>,
951    ) -> Result<Ticket, RuntimeFailure> {
952        if let Some(f) = &self.failed {
953            return Err(f.clone());
954        }
955        // Starting the replays hands them every definition so far, these
956        // requests' own among them: they get each one once.
957        let mut handed = false;
958        if self.calls_begun && self.replays.is_none() && reqs.iter().any(|r| logged(r.op)) {
959            self.start_replays();
960            handed = true;
961        }
962        // The values the requests refer to for the first time, each in a
963        // line of its own, to this worker and to the replay check's.
964        for req in &reqs {
965            for (line, dynamic) in &req.added.lines {
966                self.stats.definitions += 1;
967                self.stats.defined += line.len() as u64;
968                self.write_line(line)?;
969                if !dynamic
970                    && !handed
971                    && let Some(replays) = &self.replays
972                {
973                    for r in replays {
974                        r.line(line.clone());
975                    }
976                }
977            }
978        }
979        let (tx, rx) = mpsc::channel();
980        // The requests of one ticket say so: when the worker has lost the
981        // values one of them refers to, it runs none of the rest.
982        self.next_ticket += 1;
983        let ticket = self.next_ticket;
984        let mut lines = String::new();
985        let mut sent = Vec::with_capacity(reqs.len());
986        {
987            let mut routes = locked(&self.mux.routes);
988            for req in reqs {
989                self.next_id += 1;
990                let id = self.next_id;
991                let _ = write!(lines, "{{\"id\":{id},\"t\":{ticket},");
992                lines.push_str(req.text.strip_prefix('{').unwrap_or(&req.text));
993                lines.push('\n');
994                if !req.one_way {
995                    routes.insert(id, tx.clone());
996                }
997                sent.push(Sent {
998                    id,
999                    op: req.op,
1000                    handle: req.handle,
1001                    path: req.path.map(|p| p.to_string_lossy().into_owned()),
1002                    one_way: req.one_way,
1003                    made: req.added.made,
1004                    dynamic: req.added.dynamic,
1005                    text: req.text,
1006                });
1007            }
1008        }
1009        self.stats.sent += lines.len() as u64;
1010        let written = locked(&self.mux.stdin)
1011            .as_mut()
1012            .map(|s| s.write_all(lines.as_bytes()).and_then(|_| s.flush()));
1013        if !matches!(written, Some(Ok(()))) {
1014            return Err(self.fail("Node stopped reading requests"));
1015        }
1016        Ok(Ticket {
1017            mux: self.mux.clone(),
1018            rx,
1019            sent,
1020            what: what.to_string(),
1021            shape,
1022            page,
1023            deadline: self.deadline,
1024        })
1025    }
1026
1027    /// What the replies to a ticket's requests mean: each is logged for
1028    /// the replay check, and the results shaped as the ticket asked.
1029    fn settle(&mut self, done: Done) -> Finished {
1030        let Done {
1031            sent,
1032            frames,
1033            asked,
1034            failure,
1035            what,
1036            shape,
1037            page,
1038            waited,
1039        } = done;
1040        self.slowest = self.slowest.max(waited);
1041        self.stats.waited += waited;
1042        let mut results: Vec<JsResult<Decoded>> = Vec::with_capacity(frames.len());
1043        // A call in the group changed a value the worker kept: the ones
1044        // after it ran on what it left, which a replay doesn't have.
1045        let mut unchecked = false;
1046        // When Node ran the last request of these that it answered.
1047        let mut last_at = (self.last_seq, 0u32);
1048        let mut frames = frames.into_iter();
1049        let mut asked = asked.into_iter();
1050        for req in sent {
1051            let mut frame = if req.one_way {
1052                None
1053            } else {
1054                match frames.next() {
1055                    Some(f) => Some(f),
1056                    // Node stopped before this one.
1057                    None => break,
1058                }
1059            };
1060            let answers = if req.one_way {
1061                Vec::new()
1062            } else {
1063                asked.next().unwrap_or_default()
1064            };
1065            if let Some(f) = &frame {
1066                self.stats.requests += 1;
1067                self.stats.received += f.body.len() as u64;
1068                if f.head.get("stale").is_some() {
1069                    // The worker forgot the values this refers to (a call
1070                    // another page made changed one): it ran nothing of
1071                    // this request or the ones sent with it after it. They
1072                    // go again, the values with them.
1073                    if results.iter().all(|r| matches!(r, JsResult::Ok(_))) {
1074                        self.table.forget();
1075                        return Finished::Again;
1076                    }
1077                    break;
1078                }
1079                // A step of the page before this one failed: the worker
1080                // ran neither this nor the ones after it.
1081                if f.head.get("after").is_some() {
1082                    break;
1083                }
1084            }
1085            if req.op == "templateLoad" {
1086                self.last_template = frame
1087                    .as_ref()
1088                    .and_then(|f| f.head.get("template"))
1089                    .and_then(Json::as_u64);
1090            }
1091            if req.op == "load" {
1092                self.last_fixed = frame
1093                    .as_ref()
1094                    .is_some_and(|f| f.head.get("fixed").is_some());
1095            }
1096            let body = frame
1097                .as_mut()
1098                .map(|f| std::mem::take(&mut f.body))
1099                .unwrap_or_default();
1100            let clock = frame.as_mut().and_then(|f| f.clock.take());
1101            if logged(req.op) && !self.calls_begun {
1102                self.load_log.push(LoadRecord {
1103                    text: req.text.into_boxed_str(),
1104                    kind: match req.op {
1105                        "load" => LoadKind::Data,
1106                        "templateLoad" => LoadKind::Template,
1107                        _ => LoadKind::Other,
1108                    },
1109                    path: req.path.unwrap_or_default(),
1110                    body,
1111                    clock,
1112                });
1113            } else if logged(req.op) && !self.order_check {
1114                // Nothing runs the calls again: nothing is kept of them.
1115                let dropped = frame
1116                    .as_ref()
1117                    .is_some_and(|f| f.head.get("dropShared").is_some());
1118                self.dropped |= dropped;
1119                unchecked |= dropped;
1120            } else if logged(req.op) {
1121                let (unit, label) = match brrrty_js::functions::unit() {
1122                    Some(u) => u,
1123                    None => (u64::MAX - self.call_log.len() as u64, Arc::from("")),
1124                };
1125                let dropped = frame
1126                    .as_ref()
1127                    .is_some_and(|f| f.head.get("dropShared").is_some());
1128                self.dropped |= dropped;
1129                let at = match &frame {
1130                    Some(f) => {
1131                        self.last_seq = self.last_seq.max(f.seq);
1132                        last_at = (f.seq, 0);
1133                        last_at
1134                    }
1135                    None => {
1136                        last_at.1 += 1;
1137                        last_at
1138                    }
1139                };
1140                self.call_log.push(Record {
1141                    at,
1142                    unit,
1143                    label,
1144                    op: req.op,
1145                    handle: req.handle,
1146                    text: req.text.into_boxed_str(),
1147                    body,
1148                    clock,
1149                    made: frame.as_ref().is_some_and(|f| f.made),
1150                    names_made: req.made || req.handle.is_some_and(|h| self.table.made_by_call(h)),
1151                    dynamic: req.dynamic,
1152                    answers,
1153                    one_way: req.one_way,
1154                    unchecked,
1155                });
1156                unchecked |= dropped;
1157            }
1158            let Some(frame) = frame else {
1159                continue;
1160            };
1161            let r = self.interpret(frame, &what);
1162            let failed = matches!(r, JsResult::Failed(_));
1163            results.push(r);
1164            if failed {
1165                return Finished::Results {
1166                    results: vec![results.pop().expect("just pushed")],
1167                    page: None,
1168                };
1169            }
1170        }
1171        if let Some(why) = failure {
1172            return Finished::Results {
1173                results: vec![JsResult::Failed(self.fail(&why))],
1174                page: None,
1175            };
1176        }
1177        self.shape(shape, page, results)
1178    }
1179
1180    /// The results of an operation whose requests went one part at a time.
1181    fn shaped(&mut self, done: Done, results: Vec<JsResult<Decoded>>) -> Finished {
1182        self.shape(done.shape, done.page, results)
1183    }
1184
1185    fn shape(
1186        &mut self,
1187        shape: Shape,
1188        page: Option<PageId>,
1189        mut results: Vec<JsResult<Decoded>>,
1190    ) -> Finished {
1191        // The list ends with the first reply that isn't a value.
1192        let bad = results.iter().position(|r| !matches!(r, JsResult::Ok(_)));
1193        match shape {
1194            Shape::List => {
1195                if let Some(bad) = bad {
1196                    results.truncate(bad + 1);
1197                }
1198                Finished::Results { results, page }
1199            }
1200            Shape::Once => {
1201                let result = match bad {
1202                    Some(bad) => results.swap_remove(bad),
1203                    // Opened, then called.
1204                    None if results.len() == 2 => results.swap_remove(1),
1205                    None => JsResult::Failed(self.fail("a page's call gave no reply")),
1206                };
1207                Finished::Results {
1208                    results: vec![result],
1209                    page,
1210                }
1211            }
1212            Shape::OpenWithVars => match bad {
1213                Some(bad) => {
1214                    if bad > 0
1215                        && let Some(page) = page
1216                    {
1217                        self.page_close(page);
1218                    }
1219                    Finished::Results {
1220                        results: vec![results.swap_remove(bad)],
1221                        page: None,
1222                    }
1223                }
1224                None => Finished::Results { results, page },
1225            },
1226        }
1227    }
1228
1229    /// The requests an operation makes, how its results are shaped, and
1230    /// the page it opens. `Err` when a value can't be handed over.
1231    fn op_requests(&mut self, op: Op<'_>) -> Result<Planned, String> {
1232        Ok(match op {
1233            Op::Call {
1234                f,
1235                this,
1236                args,
1237                settle,
1238            } => {
1239                let mut added = Added::default();
1240                let mut text = String::with_capacity(128);
1241                let _ = write!(
1242                    text,
1243                    "{{\"op\":\"call\",\"handle\":{},\"await\":{}",
1244                    f.0,
1245                    settle == Settle::Await
1246                );
1247                match this {
1248                    This::Value(v) => {
1249                        text.push_str(",\"this\":");
1250                        self.table.argument(v, false, &mut text, &mut added)?;
1251                    }
1252                    This::Guarded(v, keys) => {
1253                        text.push_str(",\"this\":");
1254                        self.table.argument(v, false, &mut text, &mut added)?;
1255                        text.push_str(",\"guard\":[");
1256                        for (i, (k, what)) in keys.iter().enumerate() {
1257                            if i > 0 {
1258                                text.push(',');
1259                            }
1260                            text.push('[');
1261                            crate::wire::string(&mut text, k);
1262                            text.push(',');
1263                            crate::wire::string(&mut text, what);
1264                            text.push(']');
1265                        }
1266                        text.push(']');
1267                    }
1268                    This::Opaque(what) => {
1269                        text.push_str(",\"opaque\":");
1270                        crate::wire::string(&mut text, what);
1271                    }
1272                }
1273                text.push_str(",\"args\":[");
1274                for (i, a) in args.iter().enumerate() {
1275                    if i > 0 {
1276                        text.push(',');
1277                    }
1278                    self.table.argument(a, true, &mut text, &mut added)?;
1279                }
1280                text.push(']');
1281                // Whose template is calling: the worker finds that page's
1282                // own data among the collections' items by it.
1283                if let Some((page, number)) = brrrty_js::functions::own_page() {
1284                    text.push_str(",\"own\":");
1285                    self.table.argument(&page, false, &mut text, &mut added)?;
1286                    if let Some(n) = number {
1287                        text.push_str(",\"ownAt\":");
1288                        crate::wire::number(&mut text, n);
1289                    }
1290                }
1291                text.push('}');
1292                let req = Request {
1293                    added,
1294                    handle: Some(f.0),
1295                    ..Request::new("call", text)
1296                };
1297                (vec![req], Shape::List, None, "a data function")
1298            }
1299            Op::PageOnce {
1300                data,
1301                traps,
1302                defaults,
1303                f,
1304            } => {
1305                let (page, open) = self.open_request(data, traps, defaults)?;
1306                (
1307                    vec![open, call_request(page, f, None), close_request(page)],
1308                    Shape::Once,
1309                    None,
1310                    "a permalink function",
1311                )
1312            }
1313            Op::PageOpenWithVars {
1314                data,
1315                traps,
1316                defaults,
1317                functions,
1318                keys,
1319            } => {
1320                let (page, open) = self.open_request(data, traps, defaults)?;
1321                let mut reqs = vec![open];
1322                reqs.extend(functions.iter().map(|f| vars_request(page, *f, keys)));
1323                (
1324                    reqs,
1325                    Shape::OpenWithVars,
1326                    Some(page),
1327                    "a computed data function",
1328                )
1329            }
1330            Op::PageRun { page, steps } => {
1331                let mut reqs = Vec::with_capacity(steps.len());
1332                for step in steps {
1333                    match step {
1334                        PageStep::Call(f, set) => reqs.push(call_request(page, *f, *set)),
1335                        PageStep::Set(key, value) => {
1336                            let mut added = Added::default();
1337                            let mut text = String::with_capacity(128);
1338                            let _ =
1339                                write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
1340                            crate::wire::string(&mut text, key);
1341                            text.push_str(",\"value\":");
1342                            self.table.argument(value, false, &mut text, &mut added)?;
1343                            text.push('}');
1344                            reqs.push(Request {
1345                                added,
1346                                ..Request::new("pageSet", text)
1347                            });
1348                        }
1349                    }
1350                }
1351                (reqs, Shape::List, None, "a computed data function")
1352            }
1353            Op::Render {
1354                template,
1355                data,
1356                first,
1357                traps,
1358            } => {
1359                let mut added = Added::default();
1360                let mut text = String::with_capacity(1024);
1361                let _ = write!(
1362                    text,
1363                    "{{\"op\":\"render\",\"template\":{},\"data\":",
1364                    template.0
1365                );
1366                self.table.page_data(data, true, &mut text, &mut added)?;
1367                text.push_str(",\"traps\":");
1368                pairs(&mut text, traps);
1369                if let Some(first) = first {
1370                    text.push_str(",\"first\":");
1371                    self.table.argument(first, true, &mut text, &mut added)?;
1372                }
1373                text.push('}');
1374                let req = Request {
1375                    added,
1376                    ..Request::new("render", text)
1377                };
1378                (vec![req], Shape::List, None, "a JavaScript template")
1379            }
1380        })
1381    }
1382
1383    /// [`Worker::now`], for an operation with one result.
1384    fn one(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> JsResult<Decoded> {
1385        self.now(op, filters)
1386            .pop()
1387            .unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
1388    }
1389
1390    /// Run an operation and wait for it here.
1391    fn now(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Vec<JsResult<Decoded>> {
1392        for _ in 0..AGAIN {
1393            let finished = match self.begin(op, filters) {
1394                Begun::Done(f) => f,
1395                Begun::Sent(pending) => {
1396                    let waited = pending.wait(filters);
1397                    self.finish(waited)
1398                }
1399            };
1400            if let Finished::Results { results, .. } = finished {
1401                return results;
1402            }
1403        }
1404        vec![JsResult::Failed(self.fail(
1405            "the worker kept losing the values a request referred to",
1406        ))]
1407    }
1408
1409    /// Write one line to Node's stdin.
1410    pub(crate) fn write_line(&mut self, line: &str) -> Result<(), RuntimeFailure> {
1411        if let Some(f) = &self.failed {
1412            return Err(f.clone());
1413        }
1414        let mut bytes = Vec::with_capacity(line.len() + 1);
1415        bytes.extend_from_slice(line.as_bytes());
1416        bytes.push(b'\n');
1417        let sent = locked(&self.mux.stdin)
1418            .as_mut()
1419            .map(|s| s.write_all(&bytes).and_then(|_| s.flush()));
1420        if !matches!(sent, Some(Ok(()))) {
1421            return Err(self.fail("Node stopped reading requests"));
1422        }
1423        Ok(())
1424    }
1425
1426    /// Node's stdin, for a thread that writes requests ahead of their
1427    /// replies.
1428    pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
1429        locked(&self.mux.stdin).take()
1430    }
1431
1432    /// The next request id, and the line that sends `text` under it, with
1433    /// the clock and random values `feed` when the replay check hands the
1434    /// first run's back.
1435    pub(crate) fn line_for(&mut self, text: &str, feed: Option<&str>) -> (u64, String) {
1436        self.next_id += 1;
1437        let id = self.next_id;
1438        let mut line = String::with_capacity(text.len() + 32);
1439        let _ = write!(line, "{{\"id\":{id},");
1440        if let Some(feed) = feed {
1441            line.push_str("\"feed\":");
1442            line.push_str(feed);
1443            line.push(',');
1444        }
1445        line.push_str(text.strip_prefix('{').unwrap_or(text));
1446        (id, line)
1447    }
1448
1449    /// Send one request and wait for its reply frame.
1450    pub(crate) fn exchange(
1451        &mut self,
1452        text: &str,
1453        feed: Option<&str>,
1454        what: &str,
1455    ) -> Result<Frame, RuntimeFailure> {
1456        self.exchange_with(text, feed, what, &mut |name: &str, _: &[Value]| {
1457            Err(format!(
1458                "calls `this.{name}` where Brrrty has no filters to run it"
1459            ))
1460        })
1461    }
1462
1463    /// Answer one of the worker's questions: run the filter it names, or,
1464    /// in the replay check, give the first run's answer.
1465    pub(crate) fn answer(
1466        &mut self,
1467        frame: &Frame,
1468        filters: &mut FilterCall<'_>,
1469    ) -> Result<(), String> {
1470        let reply: Box<str> = match self.answers_feed.as_mut() {
1471            Some(feed) => {
1472                let reply: Box<str> = match feed.pop_front() {
1473                    Some((q, a)) if q == frame.body => a,
1474                    _ => r#"{"refused":"asks for a filter the first run didn't ask for at this point"}"#
1475                        .into(),
1476                };
1477                self.mux.send_answer(&reply)?;
1478                reply
1479            }
1480            None => self.mux.answer(frame, filters)?,
1481        };
1482        self.asked.push((frame.body.clone(), reply));
1483        Ok(())
1484    }
1485
1486    /// [`Worker::exchange`], answering the worker's filter questions with
1487    /// `filters` while it waits.
1488    pub(crate) fn exchange_with(
1489        &mut self,
1490        text: &str,
1491        feed: Option<&str>,
1492        what: &str,
1493        filters: &mut FilterCall<'_>,
1494    ) -> Result<Frame, RuntimeFailure> {
1495        let (id, line) = self.line_for(text, feed);
1496        self.write_line(&line)?;
1497        let mut wait = self.wait();
1498        let frame = loop {
1499            match self.next_frame(what, &mut wait) {
1500                Ok(f) if f.question => {
1501                    if let Err(why) = self.answer(&f, filters) {
1502                        return Err(self.fail(&why));
1503                    }
1504                }
1505                Ok(f) => break f,
1506                Err(f) => return Err(f),
1507            }
1508        };
1509        let took = wait.start.elapsed();
1510        self.slowest = self.slowest.max(took);
1511        self.stats.requests += 1;
1512        self.stats.sent += line.len() as u64;
1513        self.stats.received += frame.body.len() as u64;
1514        self.stats.waited += took;
1515        if frame.id != id {
1516            let head = frame.head.clone();
1517            return Err(self.fail(&format!("a reply out of order: {head}")));
1518        }
1519        Ok(frame)
1520    }
1521
1522    /// Start waiting for a frame.
1523    pub(crate) fn wait(&self) -> Wait {
1524        self.mux.wait()
1525    }
1526
1527    /// The next frame from Node that no ticket waits for: a reply, or a
1528    /// question of its own.
1529    pub(crate) fn next_frame(
1530        &mut self,
1531        what: &str,
1532        wait: &mut Wait,
1533    ) -> Result<Frame, RuntimeFailure> {
1534        if let Some(f) = &self.failed {
1535            return Err(f.clone());
1536        }
1537        let mux = self.mux.clone();
1538        mux.next(&self.replies, what, wait, self.deadline)
1539            .map_err(|why| self.fail(&why))
1540    }
1541
1542    /// What a reply means.
1543    fn interpret(&mut self, frame: Frame, what: &str) -> JsResult<Decoded> {
1544        let Frame {
1545            head: reply, ok, ..
1546        } = frame;
1547        if reply.get("changedArgument").is_some() {
1548            return JsResult::Failed(self.fail(&format!(
1549                "{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"
1550            )));
1551        }
1552        if let Some(p) = reply.get("protocol") {
1553            return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
1554        }
1555        if let Some(why) = reply.get("again") {
1556            // The worker froze the data files' values and can't vouch for
1557            // what it then saw: this folder's builds walk them from now on.
1558            walk_roots().sent_back(&self.root, why.as_str().unwrap_or(""));
1559            let mut f = self.fail(&format!(
1560                "the JavaScript worker has to check the data files' values after every call ({})",
1561                why.as_str().unwrap_or("")
1562            ));
1563            f.again = true;
1564            self.failed = Some(f.clone());
1565            return JsResult::Failed(f);
1566        }
1567        if let Some(t) = reply.get("thrown") {
1568            return JsResult::Thrown(js_error(t, &self.root));
1569        }
1570        if let Some(m) = reply.get("invalid") {
1571            return JsResult::Thrown(JsError {
1572                message: m.as_str().unwrap_or("").to_string(),
1573                invalid: true,
1574                ..JsError::default()
1575            });
1576        }
1577        if reply.get("dropShared").is_some() {
1578            // The worker forgot them; ids go on rising, so none is reused.
1579            self.table.forget();
1580        }
1581        if let Some(r) = reply.get("refused") {
1582            return JsResult::Refused(Refusal {
1583                why: r.as_str().unwrap_or("").to_string(),
1584                impure: reply.get("impure").and_then(Json::as_bool) == Some(true),
1585            });
1586        }
1587        let earlier = self.earlier.take();
1588        if reply.get("same").is_some() {
1589            return match earlier {
1590                Some(d) => JsResult::Ok(d),
1591                None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
1592            };
1593        }
1594        match ok {
1595            Some(Ok(d)) => JsResult::Ok(d),
1596            Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
1597            None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
1598        }
1599    }
1600
1601    /// Start the replay check's two workers: they load the data again, in
1602    /// their own orders, while this one goes on, and are sent every value
1603    /// this one defines as it defines it.
1604    fn start_replays(&mut self) {
1605        if !self.order_check {
1606            return;
1607        }
1608        let loads = Arc::new(crate::replay::Loads {
1609            node: self.node.clone(),
1610            root: self.root.clone(),
1611            run_mode: self.run_mode,
1612            loads: std::mem::take(&mut self.load_log),
1613            global_end: self.global_end,
1614            load_handles: self.load_handles,
1615            walk: self.walk.clone(),
1616            // The replays load every file again, several in one request:
1617            // none of it should take longer than all of it did here.
1618            took: self.stats.started.map(|t| t.elapsed()).unwrap_or_default(),
1619        });
1620        let replays = [
1621            crate::replay::Handle::start(loads.clone(), true),
1622            crate::replay::Handle::start(loads, false),
1623        ];
1624        for (line, dynamic) in &self.table.lines {
1625            if !dynamic {
1626                for r in &replays {
1627                    r.line(line.clone());
1628                }
1629            }
1630        }
1631        self.replays = Some(replays);
1632    }
1633
1634    /// The worker can't go on: say why, with Node's exit status when it
1635    /// exited, and the last lines of its stderr.
1636    pub(crate) fn fail(&mut self, why: &str) -> RuntimeFailure {
1637        drop(locked(&self.mux.stdin).take());
1638        let deadline = Instant::now() + Duration::from_secs(2);
1639        let status = loop {
1640            let mut child = locked(&self.mux.child);
1641            match child.try_wait() {
1642                Ok(Some(s)) => break Some(s),
1643                Ok(None) if Instant::now() < deadline => {
1644                    drop(child);
1645                    std::thread::sleep(Duration::from_millis(10))
1646                }
1647                _ => {
1648                    let _ = child.kill();
1649                    break child.wait().ok();
1650                }
1651            }
1652        };
1653        self.stop_group();
1654        self.finish_stderr();
1655        let message = match status {
1656            Some(s) => match (s.code(), signal_of(&s)) {
1657                (Some(code), _) => format!("Node exited with status {code} ({why})"),
1658                (None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
1659                _ => why.to_string(),
1660            },
1661            None => why.to_string(),
1662        };
1663        let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
1664        let message = if stopped {
1665            "Brrrty was stopped, and stopped Node with it".to_string()
1666        } else {
1667            message
1668        };
1669        let failure = RuntimeFailure {
1670            stopped,
1671            again: false,
1672            message,
1673            stderr_tail: self
1674                .stderr_tail
1675                .lock()
1676                .map(|t| t.iter().cloned().collect())
1677                .unwrap_or_default(),
1678        };
1679        self.failed = Some(failure.clone());
1680        failure
1681    }
1682
1683    /// Stop Node at once (the replay check, at a difference).
1684    pub(crate) fn stop(&mut self) {
1685        {
1686            let mut child = locked(&self.mux.child);
1687            let _ = child.kill();
1688            let _ = child.wait();
1689        }
1690        self.stop_group();
1691        if self.failed.is_none() {
1692            self.failed = Some(RuntimeFailure {
1693                message: "the replay check stopped its Node".into(),
1694                stderr_tail: Vec::new(),
1695                stopped: false,
1696                again: false,
1697            });
1698        }
1699    }
1700
1701    /// Kill what is left of Node's process group: processes the site's
1702    /// code started and left running. One started in a session of its
1703    /// own (`detached`) is out of reach and keeps running, as under 11ty.
1704    fn stop_group(&mut self) {
1705        #[cfg(unix)]
1706        kill_group(self.pid);
1707        live(self.pid, false);
1708    }
1709
1710    /// Wait briefly for the rest of Node's stderr, then stop waiting: a
1711    /// process Node started may hold it open for as long as it runs.
1712    fn finish_stderr(&mut self) {
1713        if let Some(t) = self.stderr_thread.take() {
1714            let deadline = Instant::now() + STDERR_GRACE;
1715            while !t.is_finished() && Instant::now() < deadline {
1716                std::thread::sleep(Duration::from_millis(5));
1717            }
1718            if t.is_finished() {
1719                let _ = t.join();
1720            }
1721        }
1722    }
1723
1724    fn shown(&self, file: &Path) -> String {
1725        file.strip_prefix(&self.root)
1726            .unwrap_or(file)
1727            .display()
1728            .to_string()
1729    }
1730}
1731
1732/// The filters for requests that run computed data: the worker's own.
1733fn no_filters() -> impl FnMut(&str, &[Value]) -> Result<Value, String> {
1734    |name: &str, _: &[Value]| {
1735        Err(format!(
1736            "calls `this.{name}` where Brrrty has no filters to run it"
1737        ))
1738    }
1739}
1740
1741fn close_request(page: PageId) -> Request<'static> {
1742    let text = op_text("pageClose", |t| {
1743        let _ = write!(t, ",\"page\":{}", page.0);
1744    });
1745    Request {
1746        one_way: true,
1747        ..Request::new("pageClose", text)
1748    }
1749}
1750
1751fn call_request(page: PageId, f: FnHandle, set: Option<&str>) -> Request<'static> {
1752    let text = op_text("pageCall", |t| {
1753        let _ = write!(t, ",\"page\":{},\"handle\":{},\"set\":", page.0, f.0);
1754        match set {
1755            Some(key) => crate::wire::string(t, key),
1756            None => t.push_str("null"),
1757        }
1758    });
1759    Request {
1760        handle: Some(f.0),
1761        ..Request::new("pageCall", text)
1762    }
1763}
1764
1765fn vars_request(page: PageId, f: FnHandle, keys: &[String]) -> Request<'static> {
1766    let text = op_text("pageVars", |t| {
1767        let _ = write!(t, ",\"page\":{},\"handle\":{},\"keys\":", page.0, f.0);
1768        crate::wire::strings(t, keys);
1769    });
1770    Request {
1771        handle: Some(f.0),
1772        ..Request::new("pageVars", text)
1773    }
1774}
1775
1776/// `{"op":"<op>"` and the fields `rest` writes, closed.
1777fn op_text(op: &str, rest: impl FnOnce(&mut String)) -> String {
1778    let mut t = String::with_capacity(96);
1779    let _ = write!(t, "{{\"op\":\"{op}\"");
1780    rest(&mut t);
1781    t.push('}');
1782    t
1783}
1784
1785/// `[[key, why], ...]` as JSON text.
1786fn pairs(out: &mut String, traps: &[(String, String)]) {
1787    out.push('[');
1788    for (i, (k, why)) in traps.iter().enumerate() {
1789        if i > 0 {
1790            out.push(',');
1791        }
1792        out.push('[');
1793        crate::wire::string(out, k);
1794        out.push(',');
1795        crate::wire::string(out, why);
1796        out.push(']');
1797    }
1798    out.push(']');
1799}
1800
1801fn unit(r: JsResult<Decoded>) -> JsResult<()> {
1802    match r {
1803        JsResult::Ok(_) => JsResult::Ok(()),
1804        JsResult::Thrown(e) => JsResult::Thrown(e),
1805        JsResult::Refused(r) => JsResult::Refused(r),
1806        JsResult::Failed(f) => JsResult::Failed(f),
1807    }
1808}
1809
1810impl Worker {
1811    /// `templateLoad`: a JavaScript template or layout, or with `custom` (extension, content) a
1812    /// file of a custom extension.
1813    fn load_template_as(
1814        &mut self,
1815        file: &Path,
1816        layout: bool,
1817        custom: Option<(&str, &str)>,
1818    ) -> JsResult<LoadedTemplate> {
1819        let what = self.shown(file);
1820        let text = op_text("templateLoad", |t| {
1821            t.push_str(",\"path\":");
1822            crate::wire::string(t, &file.to_string_lossy());
1823            let _ = write!(t, ",\"layout\":{layout}");
1824            if let Some((ext, content)) = custom {
1825                t.push_str(",\"custom\":{\"ext\":");
1826                crate::wire::string(t, ext);
1827                t.push_str(",\"content\":");
1828                crate::wire::string(t, content);
1829                t.push('}');
1830            }
1831        });
1832        self.last_template = None;
1833        let r = self.request(
1834            Request {
1835                path: Some(file),
1836                ..Request::new("templateLoad", text)
1837            },
1838            &what,
1839        );
1840        match r {
1841            JsResult::Ok(data) => match self.last_template {
1842                Some(id) => JsResult::Ok(LoadedTemplate {
1843                    id: TemplateId(id),
1844                    data,
1845                }),
1846                None => JsResult::Failed(self.fail("templateLoad gave no template id")),
1847            },
1848            JsResult::Thrown(e) => JsResult::Thrown(e),
1849            JsResult::Refused(r) => JsResult::Refused(r),
1850            JsResult::Failed(f) => JsResult::Failed(f),
1851        }
1852    }
1853}
1854
1855impl JsRuntime for Worker {
1856    fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
1857        let text = op_text("setArg", |t| {
1858            let _ = write!(t, ",\"value\":{}", encode(arg));
1859        });
1860        unit(self.request(Request::new("setArg", text), "the data argument"))
1861    }
1862
1863    fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
1864        let what = self.shown(file);
1865        let key = (call, file.to_path_buf());
1866        // The worker says `same` when the value is the one it sent last
1867        // time for this file, and the decoded value is used again: equal
1868        // data, and the same objects, which Brrrty compares cheaply.
1869        self.earlier = self.last_loaded.get(&key).cloned();
1870        // What a module exports as it is (no function to call, no getter)
1871        // is the same every time: one request, however many templates the
1872        // file applies to.
1873        if self.fixed.contains(&key)
1874            && let Some(d) = self.earlier.take()
1875        {
1876            return JsResult::Ok(d);
1877        }
1878        let text = op_text("load", |t| {
1879            t.push_str(",\"path\":");
1880            crate::wire::string(t, &file.to_string_lossy());
1881            let _ = write!(t, ",\"call\":{call}");
1882        });
1883        let r = self.request(
1884            Request {
1885                path: Some(file),
1886                ..Request::new("load", text)
1887            },
1888            &what,
1889        );
1890        if let JsResult::Ok(d) = &r {
1891            if self.last_fixed {
1892                self.fixed.insert(key.clone());
1893            }
1894            self.last_loaded.insert(key, d.clone());
1895        }
1896        r
1897    }
1898
1899    fn load_config(&mut self, file: &Path) -> JsResult<Decoded> {
1900        let what = self.shown(file);
1901        let text = op_text("configLoad", |t| {
1902            t.push_str(",\"path\":");
1903            crate::wire::string(t, &file.to_string_lossy());
1904        });
1905        self.earlier = None;
1906        self.request(
1907            Request {
1908                path: Some(file),
1909                ..Request::new("configLoad", text)
1910            },
1911            &what,
1912        )
1913    }
1914
1915    fn call(
1916        &mut self,
1917        f: FnHandle,
1918        this: This<'_>,
1919        args: &[Value],
1920        settle: Settle,
1921    ) -> JsResult<Decoded> {
1922        let op = Op::Call {
1923            f,
1924            this,
1925            args,
1926            settle,
1927        };
1928        self.one(op, &mut no_filters())
1929    }
1930
1931    fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
1932        let (reqs, shape, page, what) = match self.op_requests(op) {
1933            Ok(r) => r,
1934            Err(why) => {
1935                return Begun::Done(Finished::Results {
1936                    results: vec![JsResult::Refused(Refusal::new(why))],
1937                    page: None,
1938                });
1939            }
1940        };
1941        if !Worker::fits(&reqs) {
1942            // Too much to send ahead of the first reply: one part at a
1943            // time, here.
1944            let results = self.requests(reqs, what, filters);
1945            let done = Done {
1946                sent: Vec::new(),
1947                frames: Vec::new(),
1948                asked: Vec::new(),
1949                failure: None,
1950                what: what.to_string(),
1951                shape,
1952                page,
1953                waited: Duration::ZERO,
1954            };
1955            return Begun::Done(self.shaped(done, results));
1956        }
1957        match self.send(reqs, what, shape, page) {
1958            Ok(ticket) => Begun::Sent(Box::new(ticket)),
1959            Err(f) => Begun::Done(Finished::Results {
1960                results: vec![JsResult::Failed(f)],
1961                page: None,
1962            }),
1963        }
1964    }
1965
1966    fn finish(&mut self, waited: Waited) -> Finished {
1967        match waited.0.downcast::<Done>() {
1968            Ok(done) => self.settle(*done),
1969            Err(_) => Finished::Results {
1970                results: vec![JsResult::Failed(
1971                    self.fail("replies that aren't this worker's"),
1972                )],
1973                page: None,
1974            },
1975        }
1976    }
1977
1978    fn page_open(
1979        &mut self,
1980        data: &Value,
1981        traps: &[(String, String)],
1982        defaults: &[String],
1983    ) -> JsResult<PageId> {
1984        let (page, open) = match self.open_request(data, traps, defaults) {
1985            Ok(r) => r,
1986            Err(why) => return JsResult::Refused(Refusal::new(why)),
1987        };
1988        match self.request(open, "a page's data") {
1989            JsResult::Ok(_) => JsResult::Ok(PageId(page.0)),
1990            JsResult::Thrown(e) => JsResult::Thrown(e),
1991            JsResult::Refused(r) => JsResult::Refused(r),
1992            JsResult::Failed(f) => JsResult::Failed(f),
1993        }
1994    }
1995
1996    fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
1997        let r = self.request(vars_request(page, f, keys), "a computed data function");
1998        match r {
1999            JsResult::Ok(d) => match strings(&d.value) {
2000                Some(list) => JsResult::Ok(list),
2001                None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
2002            },
2003            JsResult::Thrown(e) => JsResult::Thrown(e),
2004            JsResult::Refused(r) => JsResult::Refused(r),
2005            JsResult::Failed(f) => JsResult::Failed(f),
2006        }
2007    }
2008
2009    fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
2010        self.request(call_request(page, f, set), "a computed data function")
2011    }
2012
2013    fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
2014        let mut added = Added::default();
2015        let mut text = String::with_capacity(128);
2016        let _ = write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
2017        crate::wire::string(&mut text, key);
2018        text.push_str(",\"value\":");
2019        if let Err(why) = self.table.argument(value, false, &mut text, &mut added) {
2020            return JsResult::Refused(Refusal::new(why));
2021        }
2022        text.push('}');
2023        unit(self.request(
2024            Request {
2025                added,
2026                ..Request::new("pageSet", text)
2027            },
2028            "a page's data",
2029        ))
2030    }
2031
2032    fn page_close(&mut self, page: PageId) {
2033        // Nothing comes back from it.
2034        let _ = self.requests(
2035            vec![close_request(page)],
2036            "a page's data",
2037            &mut no_filters(),
2038        );
2039    }
2040
2041    fn page_once(
2042        &mut self,
2043        data: &Value,
2044        traps: &[(String, String)],
2045        defaults: &[String],
2046        f: FnHandle,
2047    ) -> JsResult<Decoded> {
2048        let op = Op::PageOnce {
2049            data,
2050            traps,
2051            defaults,
2052            f,
2053        };
2054        self.one(op, &mut no_filters())
2055    }
2056
2057    fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
2058        let filters = self.filters.clone();
2059        self.now(
2060            Op::PageRun { page, steps },
2061            &mut |name: &str, args: &[Value]| match &filters {
2062                Some(f) => f(name, args),
2063                None => Err(format!(
2064                    "calls `this.{name}` where Brrrty has no filters to run it"
2065                )),
2066            },
2067        )
2068    }
2069
2070    fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
2071        self.global_end = self.load_log.len();
2072        let d = match self.request(
2073            Request::new("loadsChanged", op_text("loadsChanged", |_| {})),
2074            "the data files",
2075        ) {
2076            JsResult::Ok(d) => d,
2077            JsResult::Thrown(e) => return JsResult::Thrown(e),
2078            JsResult::Refused(r) => return JsResult::Refused(r),
2079            JsResult::Failed(f) => return JsResult::Failed(f),
2080        };
2081        let Value::Array(items) = &d.value else {
2082            return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
2083        };
2084        let mut out = Vec::new();
2085        for (i, item) in items.iter().enumerate() {
2086            let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
2087                return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
2088            };
2089            let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
2090                match at {
2091                    [PathPart::Index(j), PathPart::Key(k), rest @ ..]
2092                        if *j == i && k == "value" =>
2093                    {
2094                        Some(rest.to_vec())
2095                    }
2096                    _ => None,
2097                }
2098            };
2099            out.push((
2100                PathBuf::from(&*p),
2101                Decoded {
2102                    value,
2103                    functions: d
2104                        .functions
2105                        .iter()
2106                        .filter_map(|(at, h)| under(at).map(|a| (a, *h)))
2107                        .collect(),
2108                    refused: d
2109                        .refused
2110                        .iter()
2111                        .filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
2112                        .collect(),
2113                },
2114            ));
2115        }
2116        JsResult::Ok(out)
2117    }
2118
2119    fn begin_calls(&mut self) -> JsResult<()> {
2120        let frame = match self.exchange(&op_text("callsBegin", |_| {}), None, "the data files") {
2121            Ok(f) => f,
2122            Err(f) => return JsResult::Failed(f),
2123        };
2124        let head = &frame.head;
2125        self.load_handles = head.get("handles").and_then(Json::as_u64).unwrap_or(0);
2126        self.frozen = head.get("exports").and_then(Json::as_str) == Some("frozen");
2127        self.walks = head.get("walks").and_then(Json::as_str).map(str::to_string);
2128        self.table.load_handles = Some(u32::try_from(self.load_handles).unwrap_or(u32::MAX));
2129        self.calls_begun = true;
2130        if trace() {
2131            self.trace("the data files loaded");
2132            match self.exports_frozen() {
2133                Ok(()) => {
2134                    eprintln!("note: the data files' values are frozen while pages call functions")
2135                }
2136                Err(why) => {
2137                    eprintln!("note: the data files' values are walked after every call ({why})")
2138                }
2139            }
2140        }
2141        let changed: Vec<&str> = head
2142            .get("changed")
2143            .and_then(Json::as_array)
2144            .map(|a| a.iter().filter_map(Json::as_str).collect())
2145            .unwrap_or_default();
2146        if !changed.is_empty() {
2147            return JsResult::Refused(Refusal {
2148                why: format!(
2149                    "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",
2150                    if changed.len() == 1 { "file" } else { "files" },
2151                    changed.join(", ")
2152                ),
2153                impure: true,
2154            });
2155        }
2156        if head.get("protos").and_then(Json::as_bool) == Some(true) {
2157            return JsResult::Refused(Refusal {
2158                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(),
2159                impure: true,
2160            });
2161        }
2162        // Template and directory data files and templates load in an order
2163        // of 11ty's own: with any, the check runs even when no page calls
2164        // a function, so it starts now.
2165        if self.load_log.len() > self.global_end {
2166            self.start_replays();
2167        }
2168        JsResult::Ok(())
2169    }
2170
2171    fn set_filters(&mut self, filters: Filters) {
2172        self.filters = Some(filters);
2173    }
2174
2175    fn template_setup(&mut self, filters: &[String], node: &[(String, u32)]) -> JsResult<()> {
2176        let text = op_text("templateSetup", |t| {
2177            t.push_str(",\"filters\":");
2178            crate::wire::strings(t, filters);
2179            // The config's own filters, which Node runs itself.
2180            t.push_str(",\"node\":[");
2181            for (i, (name, handle)) in node.iter().enumerate() {
2182                if i > 0 {
2183                    t.push(',');
2184                }
2185                t.push('[');
2186                crate::wire::string(t, name);
2187                let _ = write!(t, ",{handle}]");
2188            }
2189            t.push(']');
2190        });
2191        unit(self.request(
2192            Request::new("templateSetup", text),
2193            "the JavaScript templates' setup",
2194        ))
2195    }
2196
2197    fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate> {
2198        self.load_template_as(file, layout, None)
2199    }
2200
2201    fn load_custom_template(
2202        &mut self,
2203        file: &Path,
2204        ext: &str,
2205        content: &str,
2206    ) -> JsResult<LoadedTemplate> {
2207        self.load_template_as(file, false, Some((ext, content)))
2208    }
2209
2210    fn render(
2211        &mut self,
2212        template: TemplateId,
2213        data: &Value,
2214        first: Option<&Value>,
2215        traps: &[(String, String)],
2216        filters: &mut FilterCall<'_>,
2217    ) -> JsResult<Decoded> {
2218        let op = Op::Render {
2219            template,
2220            data,
2221            first,
2222            traps,
2223        };
2224        self.one(op, filters)
2225    }
2226
2227    fn verify(&mut self) -> JsResult<()> {
2228        // What the calls changed of the data files' values comes first: it
2229        // explains whatever the replay would find.
2230        match self.request(
2231            Request::new("exportsFinal", op_text("exportsFinal", |_| {})),
2232            "the data files' values",
2233        ) {
2234            JsResult::Ok(_) => {}
2235            other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
2236                return match other {
2237                    JsResult::Refused(r) => JsResult::Refused(r),
2238                    JsResult::Failed(f) => JsResult::Failed(f),
2239                    _ => JsResult::Ok(()),
2240                };
2241            }
2242            JsResult::Thrown(e) => return JsResult::Thrown(e),
2243        }
2244        // Nothing to check: no page called a function, and no template or
2245        // template or directory data file loaded.
2246        if self.frozen {
2247            walk_roots().froze(&self.root);
2248        }
2249        let Some(replays) = self.replays.take() else {
2250            return JsResult::Ok(());
2251        };
2252        let calls = Arc::new(crate::replay::Calls {
2253            records: {
2254                // The order Node ran them in, not the order the render
2255                // threads took their replies: the replay check's orders are
2256                // made from this one, and must differ from it.
2257                let mut records = std::mem::take(&mut self.call_log);
2258                records.sort_by_key(|r| r.at);
2259                records
2260            },
2261            load_handles: self.load_handles,
2262            slowest: self.slowest,
2263            dynamic: std::mem::take(&mut self.table.dynamic),
2264            lines: self.table.lines.clone(),
2265            dropped: self.dropped,
2266        });
2267        if trace() {
2268            self.trace("the pages' calls ended");
2269        }
2270        let checking = Instant::now();
2271        let [a, b] = replays;
2272        a.run(calls.clone());
2273        b.run(calls);
2274        let (a, b) = (a.finish(), b.finish());
2275        if trace() {
2276            eprintln!(
2277                "note: the replay check took {:.3} s after the build's own calls",
2278                checking.elapsed().as_secs_f64()
2279            );
2280        }
2281        match a.and(b) {
2282            Ok(()) => JsResult::Ok(()),
2283            Err(crate::replay::Failure::Differs(why, handle)) => {
2284                let named = handle
2285                    .and_then(|h| {
2286                        let text = op_text("describe", |t| {
2287                            let _ = write!(t, ",\"handle\":{h}");
2288                        });
2289                        self.exchange(&text, None, "a function's name").ok()
2290                    })
2291                    .and_then(|f| match f.value() {
2292                        Some(Value::String(s)) => Some(s.to_string()),
2293                        _ => None,
2294                    })
2295                    .unwrap_or_else(|| "a function from JavaScript data".to_string());
2296                JsResult::Refused(Refusal {
2297                    why: why.replace("{fn}", &named),
2298                    impure: true,
2299                })
2300            }
2301            Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
2302            Err(crate::replay::Failure::Again(why)) => {
2303                walk_roots().sent_back(&self.root, &why);
2304                let mut f = self.fail(&format!(
2305                    "the JavaScript worker has to check the data files' values after every call ({why})"
2306                ));
2307                f.again = true;
2308                self.failed = Some(f.clone());
2309                JsResult::Failed(f)
2310            }
2311        }
2312    }
2313
2314    fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
2315        match self.request(
2316            Request::new("reads", op_text("reads", |_| {})),
2317            "the list of files read",
2318        ) {
2319            JsResult::Ok(d) => match strings(&d.value) {
2320                Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
2321                None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
2322            },
2323            JsResult::Thrown(e) => JsResult::Thrown(e),
2324            JsResult::Refused(r) => JsResult::Refused(r),
2325            JsResult::Failed(f) => JsResult::Failed(f),
2326        }
2327    }
2328}
2329
2330impl Drop for Worker {
2331    fn drop(&mut self) {
2332        if let Some(mut stdin) = locked(&self.mux.stdin).take() {
2333            let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
2334        }
2335        // Node finishes what a plugin left running (see the worker's `settled`) before it exits.
2336        let deadline = Instant::now() + Duration::from_secs(20);
2337        loop {
2338            let mut child = locked(&self.mux.child);
2339            match child.try_wait() {
2340                Ok(Some(_)) => break,
2341                Ok(None) if Instant::now() < deadline => {
2342                    drop(child);
2343                    std::thread::sleep(Duration::from_millis(5))
2344                }
2345                _ => {
2346                    let _ = child.kill();
2347                    let _ = child.wait();
2348                    break;
2349                }
2350            }
2351        }
2352        self.stop_group();
2353        self.finish_stderr();
2354    }
2355}
2356
2357/// The project folders whose builds found they must walk the data files'
2358/// values after each call rather than freeze them (see the worker's
2359/// "Freezing"): a build there starts that way.
2360fn walk_roots() -> MutexGuard<'static, WalkMemo> {
2361    static ROOTS: std::sync::LazyLock<Mutex<WalkMemo>> =
2362        std::sync::LazyLock::new(|| Mutex::new(WalkMemo::default()));
2363    ROOTS.lock().unwrap_or_else(|e| e.into_inner())
2364}
2365
2366/// Which folders' builds walk, and for how long. A build that was sent
2367/// back runs again walking; the build after that tries the freeze again
2368/// (under `brrrty serve` the code may have been fixed). A folder sent
2369/// back again and again walks for twice as many builds each time, up to
2370/// 64, so a site that can't be frozen stops paying for the try.
2371#[derive(Default)]
2372pub(crate) struct WalkMemo {
2373    roots: HashMap<PathBuf, Walks>,
2374}
2375
2376struct Walks {
2377    why: String,
2378    /// How many builds still start walking.
2379    left: u32,
2380    /// How many it was the last time the folder was sent back.
2381    last: u32,
2382}
2383
2384impl WalkMemo {
2385    const MOST: u32 = 64;
2386
2387    /// A build of `root` was sent back.
2388    pub(crate) fn sent_back(&mut self, root: &Path, why: &str) {
2389        let w = self.roots.entry(root.to_path_buf()).or_insert(Walks {
2390            why: String::new(),
2391            left: 0,
2392            last: 0,
2393        });
2394        // Several of one build's requests may say so.
2395        if w.left > 0 {
2396            return;
2397        }
2398        w.why = why.to_string();
2399        w.last = (w.last * 2).clamp(1, Self::MOST);
2400        w.left = w.last;
2401    }
2402
2403    /// A build of `root` starts: why it walks, if it does.
2404    pub(crate) fn starting(&mut self, root: &Path) -> Option<String> {
2405        let w = self.roots.get_mut(root)?;
2406        if w.left == 0 {
2407            return None;
2408        }
2409        w.left -= 1;
2410        Some(w.why.clone())
2411    }
2412
2413    /// A build of `root` froze and passed.
2414    pub(crate) fn froze(&mut self, root: &Path) {
2415        self.roots.remove(root);
2416    }
2417}
2418
2419/// Whether to say on stderr what the JavaScript worker's requests cost
2420/// (`BRRRTY_JS_TRACE`, for whoever looks into a slow build).
2421fn trace() -> bool {
2422    static ON: std::sync::LazyLock<bool> =
2423        std::sync::LazyLock::new(|| std::env::var_os("BRRRTY_JS_TRACE").is_some());
2424    *ON
2425}
2426
2427/// The process ids of the workers running now. Each leads its own process
2428/// group, so a terminal's Ctrl-C doesn't reach it: [`stop_all`] does.
2429static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
2430
2431/// Set once [`stop_all`] ran: a worker failing after that was stopped.
2432static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2433
2434fn live(pid: u32, running: bool) {
2435    let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2436    l.retain(|p| *p != pid);
2437    if running {
2438        l.push(pid);
2439    }
2440}
2441
2442/// Kill every running worker and what it started, at once: for Ctrl-C,
2443/// SIGTERM and a panic. Safe to call from a signal handler thread.
2444pub fn stop_all() {
2445    STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
2446    let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
2447    #[cfg(unix)]
2448    for pid in l.iter() {
2449        kill_group(*pid);
2450    }
2451}
2452
2453/// Kill the worker with this process id and what it started.
2454pub(crate) fn stop_pid(pid: u32) {
2455    #[cfg(unix)]
2456    kill_group(pid);
2457    // Elsewhere there is no group: Windows stops the tree by name.
2458    #[cfg(windows)]
2459    {
2460        let _ = Command::new("taskkill")
2461            .args(["/PID", &pid.to_string(), "/T", "/F"])
2462            .stdin(Stdio::null())
2463            .stdout(Stdio::null())
2464            .stderr(Stdio::null())
2465            .status();
2466    }
2467    #[cfg(not(any(unix, windows)))]
2468    let _ = pid;
2469}
2470
2471#[cfg(unix)]
2472fn kill_group(pid: u32) {
2473    if let Ok(pid) = i32::try_from(pid) {
2474        // SAFETY: killpg only sends a signal, to the group Node leads.
2475        unsafe {
2476            libc::killpg(pid, libc::SIGKILL);
2477        }
2478    }
2479}
2480
2481/// Start the worker. Its replies come on a pipe of their own, which Node
2482/// inherits under the descriptor number it has here, and its stdout joins
2483/// its stderr: a child process or logger writing to fd 1 is only noise, as
2484/// it is under 11ty.
2485#[cfg(unix)]
2486fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2487    use std::os::fd::AsRawFd;
2488    use std::os::unix::process::CommandExt;
2489    let (frames_r, frames_w) = std::io::pipe()?;
2490    // A copy is numbered 3 or above, clear of the standard three.
2491    let frames_w = frames_w.try_clone()?;
2492    let (answers_r, answers_w) = std::io::pipe()?;
2493    let answers_r = answers_r.try_clone()?;
2494    let (err_r, err_w) = std::io::pipe()?;
2495    let fd = frames_w.as_raw_fd();
2496    let answers_fd = answers_r.as_raw_fd();
2497    cmd.stdout(err_w.try_clone()?)
2498        .stderr(err_w)
2499        .env("BRRRTY_FRAMES_FD", fd.to_string())
2500        .env("BRRRTY_ANSWERS_FD", answers_fd.to_string())
2501        // A group of its own, so what Node starts can be stopped with it.
2502        .process_group(0);
2503    // SAFETY: fcntl is async-signal-safe, and the descriptor is this
2504    // process's own, open until after the spawn.
2505    unsafe {
2506        cmd.pre_exec(move || {
2507            // Keep it open across exec in Node only.
2508            if libc::fcntl(fd, libc::F_SETFD, 0) == -1
2509                || libc::fcntl(answers_fd, libc::F_SETFD, 0) == -1
2510            {
2511                return Err(std::io::Error::last_os_error());
2512            }
2513            Ok(())
2514        });
2515    }
2516    let child = cmd.spawn();
2517    // The parent's write ends close here, so the reads end when Node's do.
2518    drop(cmd);
2519    drop(frames_w);
2520    drop(answers_r);
2521    Ok((
2522        child?,
2523        Box::new(frames_r),
2524        Box::new(err_r),
2525        Some(Box::new(answers_w)),
2526    ))
2527}
2528
2529/// A started Node: the process, its replies, its stderr, and where
2530/// Brrrty answers its questions (none where that pipe can't be passed).
2531type Spawned = (
2532    Child,
2533    Box<dyn Read + Send>,
2534    Box<dyn Read + Send>,
2535    Option<Box<dyn Write + Send>>,
2536);
2537
2538/// Start the worker, its replies on stdout.
2539#[cfg(not(unix))]
2540fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
2541    let mut child = cmd
2542        .stdout(Stdio::piped())
2543        .stderr(Stdio::piped())
2544        .env("BRRRTY_FRAMES_FD", "1")
2545        .spawn()?;
2546    let stdout = child.stdout.take().expect("piped stdout");
2547    let stderr = child.stderr.take().expect("piped stderr");
2548    Ok((child, Box::new(stdout), Box::new(stderr), None))
2549}
2550
2551#[cfg(unix)]
2552fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
2553    use std::os::unix::process::ExitStatusExt;
2554    s.signal()
2555}
2556
2557#[cfg(not(unix))]
2558fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
2559    None
2560}
2561
2562/// Read `\x1eBRRRTY <kind> <id> <clock length> <body length>\n<clock><body>`
2563/// frames until Node closes its output. Anything else is a protocol error,
2564/// sent once.
2565fn read_frames(stdout: impl Read, tx: mpsc::Sender<Reply>, decoding: Arc<AtomicBool>, mux: &Mux) {
2566    read_frames_to(stdout, &tx, decoding, mux);
2567    // No more frames: whoever waits for one learns so.
2568    locked(&mux.routes).clear();
2569}
2570
2571fn read_frames_to(
2572    stdout: impl Read,
2573    tx: &mpsc::Sender<Reply>,
2574    decoding: Arc<AtomicBool>,
2575    mux: &Mux,
2576) {
2577    let mut r = BufReader::with_capacity(1 << 16, stdout);
2578    let mut seq = 0u64;
2579    loop {
2580        seq += 1;
2581        let mut header = Vec::new();
2582        match r.read_until(b'\n', &mut header) {
2583            Ok(0) => return,
2584            Ok(_) => {}
2585            Err(e) => {
2586                let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
2587                return;
2588            }
2589        }
2590        let fields = header
2591            .strip_prefix(b"\x1eBRRRTY ")
2592            .and_then(|h| h.strip_suffix(b"\n"))
2593            .and_then(|h| std::str::from_utf8(h).ok())
2594            .and_then(|h| {
2595                let mut it = h.split(' ');
2596                let kind = it.next()?;
2597                let id = it.next()?.parse::<u64>().ok()?;
2598                let clock = it.next()?.parse::<usize>().ok()?;
2599                let body = it.next()?.parse::<usize>().ok()?;
2600                (it.next().is_none() && matches!(kind, "r" | "f" | "q"))
2601                    .then_some((kind, id, clock, body))
2602            });
2603        let Some((kind, id, clock_len, body_len)) = fields else {
2604            let shown = String::from_utf8_lossy(&header);
2605            let _ = tx.send(Err(format!(
2606                "something other than the worker wrote to its output: {:?}",
2607                shown.chars().take(80).collect::<String>()
2608            )));
2609            return;
2610        };
2611        let mut read = |len: usize| -> Result<String, String> {
2612            let mut bytes = vec![0; len];
2613            r.read_exact(&mut bytes)
2614                .map_err(|e| format!("a cut-off reply: {e}"))?;
2615            String::from_utf8(bytes).map_err(|_| "a reply that isn't UTF-8".to_string())
2616        };
2617        let parts = read(clock_len).and_then(|c| read(body_len).map(|b| (c, b)));
2618        let (clock, body) = match parts {
2619            Ok(p) => p,
2620            Err(e) => {
2621                let _ = tx.send(Err(e));
2622                return;
2623            }
2624        };
2625        let decode_ok = decoding.load(std::sync::atomic::Ordering::Relaxed);
2626        let parsed = parse_reply(body.as_bytes()).map(|mut head| {
2627            let value = head.as_object_mut().and_then(|o| o.remove("ok"));
2628            let ok = if decode_ok || kind == "q" {
2629                value.as_ref().map(decode)
2630            } else {
2631                None
2632            };
2633            Frame {
2634                question: kind == "q",
2635                id,
2636                head,
2637                ok,
2638                body: body.into_boxed_str(),
2639                clock: (!clock.is_empty()).then(|| clock.into_boxed_str()),
2640                made: kind == "f",
2641                seq,
2642            }
2643        });
2644        // A frame a ticket waits for goes to it; any other to the worker.
2645        let route = match &parsed {
2646            Ok(f) => locked(&mux.routes).get(&f.id).cloned(),
2647            Err(_) => None,
2648        };
2649        let sent = match route {
2650            Some(to) => to.send(parsed).is_ok(),
2651            None => tx.send(parsed).is_ok(),
2652        };
2653        if !sent && locked(&mux.routes).is_empty() {
2654            return;
2655        }
2656    }
2657}
2658
2659/// A list of strings, as `reads` and `varsUsed` reply.
2660fn strings(v: &Value) -> Option<Vec<String>> {
2661    match v {
2662        Value::Array(a) => a
2663            .iter()
2664            .map(|s| match s {
2665                Value::String(s) => Some(s.to_string()),
2666                _ => None,
2667            })
2668            .collect(),
2669        _ => None,
2670    }
2671}
2672
2673/// One reply body, without serde's nesting limit (see [`REPLY_STACK`]).
2674pub(crate) fn parse_reply(body: &[u8]) -> Result<Json, String> {
2675    let mut de = serde_json::Deserializer::from_slice(body);
2676    de.disable_recursion_limit();
2677    let v = serde::Deserialize::deserialize(&mut de)
2678        .and_then(|v: Json| de.end().map(|()| v))
2679        .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
2680    Ok(v)
2681}
2682
2683/// Pass Node's stderr through to Brrrty's, as it comes, keeping the last
2684/// lines for a failure report.
2685fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
2686    let mut r = BufReader::new(stderr);
2687    let mut line = Vec::new();
2688    let mut err = std::io::stderr();
2689    loop {
2690        line.clear();
2691        match r.read_until(b'\n', &mut line) {
2692            Ok(0) | Err(_) => return,
2693            Ok(_) => {
2694                let _ = err.write_all(&line);
2695                if let Ok(mut t) = tail.lock() {
2696                    if t.len() == STDERR_TAIL {
2697                        t.pop_front();
2698                    }
2699                    t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
2700                }
2701            }
2702        }
2703    }
2704}
2705
2706/// The site's error, placed: a SyntaxError at the header Node prints for
2707/// it, anything else at the first stack frame inside the project and
2708/// outside `node_modules`.
2709fn js_error(t: &Json, root: &Path) -> JsError {
2710    let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
2711    let stack = s("stack");
2712    let place = crate::stack::syntax_header(&s("inspect"))
2713        .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
2714    JsError {
2715        name: s("name"),
2716        message: s("message"),
2717        file: place.as_ref().map(|p| p.file.clone()),
2718        line: place.as_ref().map(|p| p.line),
2719        column: place.and_then(|p| p.column),
2720        stack,
2721        invalid: false,
2722    }
2723}
2724
2725/// A Brrrty value in the worker's wire forms.
2726pub fn encode(v: &Value) -> Json {
2727    match v {
2728        Value::Undefined => json!({"$u": 1}),
2729        Value::Null => Json::Null,
2730        Value::Bool(b) => Json::Bool(*b),
2731        Value::Number(n) => {
2732            if n.is_nan() {
2733                json!({"$n": "NaN"})
2734            } else if *n == f64::INFINITY {
2735                json!({"$n": "Infinity"})
2736            } else if *n == f64::NEG_INFINITY {
2737                json!({"$n": "-Infinity"})
2738            } else if *n == 0.0 && n.is_sign_negative() {
2739                json!({"$n": "-0"})
2740            } else {
2741                serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
2742            }
2743        }
2744        Value::String(s) => Json::String(s.to_string()),
2745        Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
2746        Value::Object(o) => {
2747            json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
2748        }
2749        Value::Date(d) => json!({"$d": d.timestamp_millis()}),
2750        Value::Function(h) => json!({"$f": h.0}),
2751    }
2752}
2753
2754#[cfg(test)]
2755mod source {
2756    /// The comments are left out of what Node runs, each leaving its
2757    /// line behind, so a line number in a stack trace is the file's.
2758    #[test]
2759    fn the_worker_source_keeps_the_files_line_numbers() {
2760        let source = super::worker_source();
2761        // Line numbers are the file's.
2762        assert_eq!(source.lines().count(), super::WORKER_SOURCE.lines().count());
2763        assert!(!source.lines().any(|l| l.trim_start().starts_with("//")));
2764    }
2765}
2766
2767#[cfg(test)]
2768mod source_size {
2769    use super::*;
2770
2771    /// A worker whose source is past 128 KiB starts: Linux refuses one
2772    /// command-line argument that long, so the source goes by file.
2773    #[test]
2774    fn a_worker_larger_than_one_argument_starts() {
2775        let node = match crate::find::find_node(None) {
2776            Ok(n) => n,
2777            Err(e) => {
2778                assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2779                eprintln!("skipped: {e}");
2780                return;
2781            }
2782        };
2783        tests_pad::PAD.with(|p| p.set(200 * 1024));
2784        let t = tempfile::tempdir().unwrap();
2785        let file = t.path().join("h.js");
2786        std::fs::write(&file, "module.exports = { a() { return 'ok'; } };").unwrap();
2787        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2788        assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2789    }
2790}
2791
2792#[cfg(test)]
2793mod walk_memo {
2794    use super::WalkMemo;
2795    use std::path::Path;
2796
2797    /// A build sent back runs again walking, and the one after tries the
2798    /// freeze again; a folder sent back every time walks for longer and
2799    /// longer, and one that freezes is forgotten.
2800    #[test]
2801    fn a_folder_sent_back_walks_for_a_while_not_for_good() {
2802        let root = Path::new("/site");
2803        let mut m = WalkMemo::default();
2804        assert_eq!(m.starting(root), None);
2805        m.sent_back(root, "why");
2806        // Several requests of the one build may say so.
2807        m.sent_back(root, "another request");
2808        assert_eq!(m.starting(root).as_deref(), Some("why"));
2809        // The build after the rerun tries again.
2810        assert_eq!(m.starting(root), None);
2811        m.sent_back(root, "again");
2812        assert_eq!(m.starting(root).as_deref(), Some("again"));
2813        assert_eq!(m.starting(root).as_deref(), Some("again"));
2814        assert_eq!(m.starting(root), None);
2815        m.sent_back(root, "third");
2816        let walked = std::iter::from_fn(|| m.starting(root)).count();
2817        assert_eq!(walked, 4);
2818        for _ in 0..10 {
2819            m.sent_back(root, "more");
2820            while m.starting(root).is_some() {}
2821        }
2822        m.sent_back(root, "most");
2823        assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 64);
2824        // A build that froze and passed starts over.
2825        m.froze(root);
2826        m.sent_back(root, "new");
2827        assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 1);
2828    }
2829}
2830
2831#[cfg(test)]
2832mod skipped_definition {
2833    use super::*;
2834
2835    /// A definition that refers to a value the worker forgot is skipped
2836    /// (Brrrty wrote it before it heard of the change), and so is all of
2837    /// it: the ids it had handed out before it met the forgotten value
2838    /// held objects half read, with wire markers still inside. A request
2839    /// that names one is told it is stale, like any forgotten value, and
2840    /// the worker goes on.
2841    #[test]
2842    fn a_skipped_definition_leaves_none_of_its_values_behind() {
2843        let node = match crate::find::find_node(None) {
2844            Ok(n) => n,
2845            Err(e) => {
2846                assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
2847                eprintln!("skipped: {e}");
2848                return;
2849            }
2850        };
2851        let t = tempfile::tempdir().unwrap();
2852        let file = t.path().join("h.js");
2853        std::fs::write(
2854            &file,
2855            "module.exports = { poke(o) { o.k = 2; return ''; }, show(v) { return JSON.stringify(v); } };",
2856        )
2857        .unwrap();
2858        let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
2859        assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
2860        w.exchange(r#"{"op":"callsBegin"}"#, None, "the calls' start")
2861            .expect("begins");
2862        let call = |w: &mut Worker, handle: u32, arg: u32| {
2863            w.exchange(
2864                &format!(
2865                    r#"{{"op":"call","handle":{handle},"await":false,"this":{{"$u":1}},"args":[{{"$R":{arg}}}]}}"#
2866                ),
2867                None,
2868                "a call",
2869            )
2870            .expect("answers")
2871        };
2872        // A kept value, which `poke` changes: the worker forgets it.
2873        w.write_line(r#"{"op":"def","id":50,"v":{"k":1},"n":1}"#)
2874            .unwrap();
2875        let poked = call(&mut w, 0, 50);
2876        assert!(poked.head.get("dropShared").is_some(), "{}", poked.body);
2877        // Written before Brrrty heard: it refers to the forgotten value,
2878        // after two values of its own.
2879        w.write_line(r#"{"op":"def","id":60,"v":{"a":{"x":1},"o":{"$R":50}},"n":2}"#)
2880            .unwrap();
2881        for id in [60, 61, 50] {
2882            let shown = call(&mut w, 1, id);
2883            assert_eq!(
2884                shown.head.get("stale"),
2885                Some(&Json::Bool(true)),
2886                "value {id}: {}",
2887                shown.body
2888            );
2889        }
2890        // And the worker is none the worse: the values sent again work.
2891        w.write_line(r#"{"op":"def","id":70,"v":{"a":{"x":1},"o":{"k":1}},"n":3}"#)
2892            .unwrap();
2893        let shown = call(&mut w, 1, 70);
2894        assert!(
2895            shown.body.contains(r#"{\"a\":{\"x\":1},\"o\":{\"k\":1}}"#),
2896            "{}",
2897            shown.body
2898        );
2899    }
2900}