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