Skip to main content

brrrty_node/
client.rs

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