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