Skip to main content

brrrty_node/
client.rs

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