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::io::{BufRead, BufReader, Read, Write};
5use std::path::{Path, PathBuf};
6use std::process::{Child, ChildStdin, Command, Stdio};
7use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
8use std::sync::{Arc, Mutex};
9use std::thread::JoinHandle;
10use std::time::{Duration, Instant};
11
12use brrrty_js::Value;
13use brrrty_js::runtime::{
14    Decoded, FilterCall, Filters, FnHandle, JsError, JsResult, JsRuntime, LoadedTemplate, PageId,
15    PathPart, Refusal, RuntimeFailure, Settle, TemplateId, This,
16};
17use serde_json::{Value as Json, json};
18
19use crate::decode::decode;
20use crate::find::NodeInfo;
21
22/// The worker's source: the encoding, the computed data proxy, then the
23/// protocol. Passed with `--eval`; nothing is written to disk.
24const WORKER_SOURCE: &str = concat!(
25    include_str!("worker/encode.mjs"),
26    "\n",
27    include_str!("worker/proxy.mjs"),
28    "\n",
29    include_str!("worker/main.mjs"),
30);
31
32/// The 11ty version the worker tells data files it is (`ELEVENTY_VERSION`).
33const ELEVENTY_VERSION: &str = "3.1.8";
34
35/// The stack of the thread that parses replies.
36pub(crate) const REPLY_STACK: usize = 32 * 1024 * 1024;
37
38/// How many of Node's last stderr lines a failure shows.
39const STDERR_TAIL: usize = 20;
40
41/// How long a stopped worker's stderr may take to reach its end: past this,
42/// a process Node started still holds it, and Brrrty stops reading.
43const STDERR_GRACE: Duration = Duration::from_millis(200);
44
45/// How often a wait for a reply checks that Node still runs.
46const POLL: Duration = Duration::from_millis(100);
47
48/// The first note about a slow request, then the gap between notes.
49const FIRST_NOTE: Duration = Duration::from_secs(10);
50const NEXT_NOTE: Duration = Duration::from_secs(30);
51
52/// How 11ty was started, as `ELEVENTY_RUN_MODE` shows it.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum RunMode {
55    Build,
56    Serve,
57}
58
59impl RunMode {
60    fn as_str(self) -> &'static str {
61        match self {
62            RunMode::Build => "build",
63            RunMode::Serve => "serve",
64        }
65    }
66}
67
68/// Node couldn't be started.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct WorkerError(pub String);
71
72impl std::fmt::Display for WorkerError {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.write_str(&self.0)
75    }
76}
77
78/// One reply frame, its value already decoded on the reader's thread (see
79/// [`REPLY_STACK`]), or why there is none.
80type Reply = Result<Frame, String>;
81
82pub(crate) struct Frame {
83    /// The reply without its value.
84    pub head: Json,
85    /// The decoded `ok` value, when the reply has one.
86    ok: Option<Result<Decoded, String>>,
87    /// The `ok` value as sent, kept when the worker records its requests
88    /// for the replay check (see `JsRuntime::verify`).
89    pub raw: Option<Json>,
90    /// The whole reply as text, kept while the data loads: the replay
91    /// check compares loads, and a deep value is safer kept as text than
92    /// as a parsed value on a thread with a small stack.
93    pub text: Option<Box<str>>,
94}
95
96/// What a reply's reader keeps besides the decoded value.
97pub(crate) const KEEP_RAW: u8 = 1;
98pub(crate) const KEEP_TEXT: u8 = 2;
99
100impl Record {
101    /// The request, parsed.
102    pub fn req(&self) -> Json {
103        parse_reply(self.req_text.as_bytes()).unwrap_or(Json::Null)
104    }
105}
106
107/// One request that loaded data or a template, with its reply, for the
108/// replay check.
109#[derive(Clone)]
110pub(crate) struct LoadRecord {
111    pub req: Json,
112    /// The whole reply, as text: parsed by the replay check, on its roomy
113    /// stack.
114    pub text: Box<str>,
115}
116
117/// One request made after the data files loaded, with its reply, for the
118/// replay check.
119#[derive(Clone)]
120pub(crate) struct Record {
121    /// The render that made it ([`brrrty_js::functions::unit`]); a request
122    /// made outside one is a unit of its own.
123    pub unit: u64,
124    pub label: Arc<str>,
125    /// The request as sent, as text: a parsed request takes ten times the
126    /// memory, and a build keeps one per call (see [`Record::req`]).
127    pub req_text: Box<str>,
128    pub head: Json,
129    pub raw: Option<Json>,
130    /// The questions the request asked Brrrty, with the answers it got.
131    pub answers: Vec<(Json, Json)>,
132}
133
134/// A running worker. Dropping it closes Node's stdin, waits up to 2 s for
135/// it to exit, then kills it.
136pub struct Worker {
137    child: Child,
138    stdin: Option<ChildStdin>,
139    /// Where Brrrty answers the worker's questions (a filter a JavaScript
140    /// template calls on `this`).
141    answers: Option<Box<dyn Write + Send>>,
142    /// The replay check's answers, as the first run gave them, in order.
143    pub(crate) answers_feed: Option<VecDeque<(Json, Json)>>,
144    /// The questions the request in flight asked, with their answers.
145    asked: Vec<(Json, Json)>,
146    /// Brrrty's filters, for the questions a request asks.
147    filters: Option<Filters>,
148    replies: Receiver<Reply>,
149    stderr_tail: Arc<Mutex<VecDeque<String>>>,
150    stderr_thread: Option<JoinHandle<()>>,
151    root: PathBuf,
152    next_id: u64,
153    /// Set once the worker failed: every later request fails the same way.
154    failed: Option<RuntimeFailure>,
155    /// The value each load (by call mode and file) gave last.
156    last_loaded: HashMap<(bool, PathBuf), Decoded>,
157    /// The value a `same` reply to the request in flight stands for.
158    earlier: Option<Decoded>,
159    /// Values sent to the worker and kept there, by their data's address
160    /// (the value is held, so the address can't be reused).
161    kept: Kept,
162    /// What the worker was started with, for the replay check.
163    node: NodeInfo,
164    run_mode: RunMode,
165    /// Keep each reply's value as sent, as well as decoded.
166    pub(crate) keep_raw: Arc<std::sync::atomic::AtomicU8>,
167    /// The requests that loaded the data, in order, with their replies.
168    load_log: Vec<LoadRecord>,
169    /// How many of them loaded global data (the rest are template and
170    /// directory data files and templates, which 11ty loads as their
171    /// files finish loading).
172    global_end: usize,
173    /// The requests made since, with their replies.
174    call_log: Vec<Record>,
175    /// Set once the data files loaded: see [`JsRuntime::begin_calls`].
176    calls_begun: bool,
177    /// How many function handles the data files' values made.
178    load_handles: u64,
179    /// The longest a request took.
180    slowest: Duration,
181    /// How long a request may take before the worker is given up on (the
182    /// replay check's workers only).
183    pub(crate) deadline: Option<Duration>,
184    /// The last reply's head, for a request whose reply says more than its
185    /// value (`templateLoad`'s id).
186    last_head: Json,
187    /// Where slow-request notes go; stderr unless a test replaces it.
188    notes: Box<dyn Fn(&str) + Send>,
189    /// When the first note comes, and then how often.
190    note_times: (Duration, Duration),
191}
192
193impl Worker {
194    /// Start Node with the worker, in `root` (the project folder), with
195    /// 11ty's environment variables added to Brrrty's own.
196    pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
197        let mut cmd = Command::new(&node.path);
198        cmd.args(["--input-type=module", "--eval", WORKER_SOURCE])
199            .current_dir(root)
200            .env("ELEVENTY_ROOT", root)
201            .env("ELEVENTY_SOURCE", "cli")
202            .env("ELEVENTY_RUN_MODE", run_mode.as_str())
203            .env("ELEVENTY_VERSION", ELEVENTY_VERSION)
204            .stdin(Stdio::piped());
205        let cannot =
206            |e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
207        let (mut child, frames, stderr, answers) = spawn(cmd).map_err(cannot)?;
208        live(child.id(), true);
209        let (tx, replies) = mpsc::channel();
210        // Load replies are kept as text: the replay check compares them.
211        let keep_raw = Arc::new(std::sync::atomic::AtomicU8::new(KEEP_TEXT));
212        let keep = keep_raw.clone();
213        // A reply nests up to three JSON levels per level of the value
214        // (`encode.mjs` refuses values deeper than 1000), and parsing it
215        // recurses once per level: a roomy stack, not serde's 128 limit.
216        std::thread::Builder::new()
217            .name("brrrty-node-replies".into())
218            .stack_size(REPLY_STACK)
219            .spawn(move || read_frames(frames, tx, keep))
220            .map_err(|e| {
221                let _ = child.kill();
222                let _ = child.wait();
223                WorkerError(format!("cannot read Node's replies: {e}"))
224            })?;
225        let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
226        let tail = stderr_tail.clone();
227        let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
228        Ok(Worker {
229            stdin: child.stdin.take(),
230            answers,
231            answers_feed: None,
232            asked: Vec::new(),
233            filters: None,
234            child,
235            replies,
236            stderr_tail,
237            stderr_thread: Some(stderr_thread),
238            root: root.to_path_buf(),
239            next_id: 0,
240            failed: None,
241            last_loaded: HashMap::new(),
242            earlier: None,
243            kept: Kept::default(),
244            node: node.clone(),
245            run_mode,
246            keep_raw,
247            load_log: Vec::new(),
248            global_end: 0,
249            call_log: Vec::new(),
250            calls_begun: false,
251            load_handles: 0,
252            slowest: Duration::ZERO,
253            deadline: None,
254            last_head: Json::Null,
255            notes: Box::new(|s| eprintln!("{s}")),
256            note_times: (FIRST_NOTE, NEXT_NOTE),
257        })
258    }
259
260    /// Send slow-request notes to `notes` instead of stderr, the first
261    /// after `first` and then every `next` (tests).
262    pub fn set_notes(
263        &mut self,
264        notes: impl Fn(&str) + Send + 'static,
265        first: Duration,
266        next: Duration,
267    ) {
268        self.notes = Box::new(notes);
269        self.note_times = (first, next);
270    }
271
272    /// Node's process id.
273    pub fn pid(&self) -> u32 {
274        self.child.id()
275    }
276
277    /// The project folder the worker runs in.
278    pub fn root(&self) -> &Path {
279        &self.root
280    }
281
282    /// Send one request and wait for its reply. `what` names it in the
283    /// notes about a slow reply.
284    fn request(&mut self, req: Json, what: &str) -> JsResult<Decoded> {
285        let filters = self.filters.clone();
286        self.request_with(
287            req,
288            what,
289            &mut |name: &str, args: &[Value]| match &filters {
290                Some(f) => f(name, args),
291                None => Err(format!(
292                    "calls `this.{name}` where Brrrty has no filters to run it"
293                )),
294            },
295        )
296    }
297
298    /// [`Worker::request`], answering the worker's filter questions with
299    /// `filters`.
300    fn request_with(
301        &mut self,
302        req: Json,
303        what: &str,
304        filters: &mut FilterCall<'_>,
305    ) -> JsResult<Decoded> {
306        let op = req
307            .get("op")
308            .and_then(Json::as_str)
309            .unwrap_or("")
310            .to_string();
311        let logged = !matches!(
312            op.as_str(),
313            "reads"
314                | "info"
315                | "callsBegin"
316                | "feedClock"
317                | "feedCalls"
318                | "loadsChanged"
319                | "exportsFinal"
320                | "describe"
321        );
322        self.asked.clear();
323        let frame = match self.exchange_with(req.clone(), what, filters) {
324            Ok(f) => f,
325            Err(f) => return JsResult::Failed(f),
326        };
327        if logged && !self.calls_begun {
328            self.load_log.push(LoadRecord {
329                req: req.clone(),
330                text: frame.text.clone().unwrap_or_default(),
331            });
332        }
333        if logged && self.calls_begun {
334            let (unit, label) = match brrrty_js::functions::unit() {
335                Some(u) => u,
336                None => (u64::MAX - self.call_log.len() as u64, Arc::from("")),
337            };
338            self.call_log.push(Record {
339                unit,
340                label,
341                req_text: req.to_string().into_boxed_str(),
342                head: frame.head.clone(),
343                raw: frame.raw.clone(),
344                answers: std::mem::take(&mut self.asked),
345            });
346        }
347        self.last_head = frame.head.clone();
348        self.interpret(frame, what)
349    }
350
351    /// Send one request and wait for its reply frame.
352    pub(crate) fn exchange(&mut self, req: Json, what: &str) -> Result<Frame, RuntimeFailure> {
353        self.exchange_with(req, what, &mut |name: &str, _: &[Value]| {
354            Err(format!(
355                "calls `this.{name}` where Brrrty has no filters to run it"
356            ))
357        })
358    }
359
360    /// Answer one of the worker's questions: run the filter it names, or,
361    /// in the replay check, give the first run's answer.
362    fn answer(&mut self, frame: &Frame, filters: &mut FilterCall<'_>) -> Result<(), String> {
363        let name = frame
364            .head
365            .get("filter")
366            .and_then(Json::as_str)
367            .unwrap_or("")
368            .to_string();
369        let question = json!({"filter": name, "args": frame.raw.clone().unwrap_or(Json::Null)});
370        let reply = match self.answers_feed.as_mut() {
371            Some(feed) => match feed.pop_front() {
372                Some((q, a)) if q == question => a,
373                _ => {
374                    json!({"refused": "asks for a filter the first run didn't ask for at this point"})
375                }
376            },
377            None => {
378                let args = match &frame.ok {
379                    Some(Ok(d)) if d.is_exact() => match &d.value {
380                        Value::Array(a) => Ok(a.to_vec()),
381                        _ => Err("passes its filter something Brrrty can't read".to_string()),
382                    },
383                    Some(Ok(_)) => Err(format!(
384                        "passes `this.{name}` a function or a value that can't cross from JavaScript to Brrrty exactly"
385                    )),
386                    _ => Err("passes its filter something Brrrty can't read".to_string()),
387                };
388                match args.and_then(|a| filters(&name, &a)) {
389                    Ok(v) => json!({"ok": encode(&v)}),
390                    Err(why) => json!({"refused": why}),
391                }
392            }
393        };
394        self.asked.push((question, reply.clone()));
395        let mut line = reply.to_string();
396        line.push('\n');
397        match self.answers.as_mut() {
398            Some(w) => w
399                .write_all(line.as_bytes())
400                .and_then(|_| w.flush())
401                .map_err(|e| format!("cannot answer Node: {e}")),
402            None => Err("Node asked a question it can't be answered on".to_string()),
403        }
404    }
405
406    /// [`Worker::exchange`], answering the worker's filter questions with
407    /// `filters` while it waits.
408    pub(crate) fn exchange_with(
409        &mut self,
410        mut req: Json,
411        what: &str,
412        filters: &mut FilterCall<'_>,
413    ) -> Result<Frame, RuntimeFailure> {
414        if let Some(f) = &self.failed {
415            return Err(f.clone());
416        }
417        self.next_id += 1;
418        let id = self.next_id;
419        req["id"] = json!(id);
420        let mut line = req.to_string();
421        line.push('\n');
422        let sent = self
423            .stdin
424            .as_mut()
425            .map(|s| s.write_all(line.as_bytes()).and_then(|_| s.flush()));
426        if !matches!(sent, Some(Ok(()))) {
427            return Err(self.fail("Node stopped reading requests"));
428        }
429        let start = Instant::now();
430        let mut next_note = start + self.note_times.0;
431        // Node exiting ends the wait even when a process it started keeps
432        // the replies' pipe open.
433        let mut exited_at: Option<Instant> = None;
434        let reply = loop {
435            match self.replies.recv_timeout(POLL) {
436                Ok(Ok(f)) if f.head.get("filter").is_some() => {
437                    if let Err(why) = self.answer(&f, filters) {
438                        break Err(why);
439                    }
440                }
441                Ok(r) => break r,
442                Err(RecvTimeoutError::Timeout) => {
443                    let now = Instant::now();
444                    if let Some(d) = self.deadline
445                        && now.duration_since(start) > d
446                    {
447                        break Err(format!(
448                            "{what} took more than {} s, longer than the first run allows",
449                            d.as_secs()
450                        ));
451                    }
452                    if now >= next_note {
453                        (self.notes)(&format!(
454                            "note: still waiting on {what}, {} s",
455                            start.elapsed().as_secs()
456                        ));
457                        next_note = now + self.note_times.1;
458                    }
459                    match exited_at {
460                        Some(t) if now.duration_since(t) >= POLL => {
461                            break Err("Node exited without replying".to_string());
462                        }
463                        Some(_) => {}
464                        None => {
465                            if matches!(self.child.try_wait(), Ok(Some(_))) {
466                                exited_at = Some(now);
467                            }
468                        }
469                    }
470                }
471                Err(RecvTimeoutError::Disconnected) => {
472                    break Err("Node closed its output".to_string());
473                }
474            }
475        };
476        self.slowest = self.slowest.max(start.elapsed());
477        let frame = match reply {
478            Ok(r) => r,
479            Err(why) => return Err(self.fail(&why)),
480        };
481        if frame.head.get("id") != Some(&json!(id)) {
482            let head = frame.head.clone();
483            return Err(self.fail(&format!("a reply out of order: {head}")));
484        }
485        Ok(frame)
486    }
487
488    /// What a reply means.
489    fn interpret(&mut self, frame: Frame, what: &str) -> JsResult<Decoded> {
490        let Frame {
491            head: reply, ok, ..
492        } = frame;
493        if reply.get("changedArgument").is_some() {
494            return JsResult::Failed(self.fail(&format!(
495                "{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"
496            )));
497        }
498        if let Some(p) = reply.get("protocol") {
499            return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
500        }
501        if let Some(t) = reply.get("thrown") {
502            return JsResult::Thrown(js_error(t, &self.root));
503        }
504        if let Some(m) = reply.get("invalid") {
505            return JsResult::Thrown(JsError {
506                message: m.as_str().unwrap_or("").to_string(),
507                invalid: true,
508                ..JsError::default()
509            });
510        }
511        if reply.get("dropShared").is_some() {
512            // The worker forgot them; ids go on rising, so none is reused.
513            self.kept.lists.clear();
514        }
515        if let Some(r) = reply.get("refused") {
516            return JsResult::Refused(Refusal {
517                why: r.as_str().unwrap_or("").to_string(),
518                impure: reply.get("impure").and_then(Json::as_bool) == Some(true),
519            });
520        }
521        let earlier = self.earlier.take();
522        if reply.get("same").is_some() {
523            return match earlier {
524                Some(d) => JsResult::Ok(d),
525                None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
526            };
527        }
528        match ok {
529            Some(Ok(d)) => JsResult::Ok(d),
530            Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
531            None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
532        }
533    }
534
535    /// The worker can't go on: say why, with Node's exit status when it
536    /// exited, and the last lines of its stderr.
537    fn fail(&mut self, why: &str) -> RuntimeFailure {
538        drop(self.stdin.take());
539        let deadline = Instant::now() + Duration::from_secs(2);
540        let status = loop {
541            match self.child.try_wait() {
542                Ok(Some(s)) => break Some(s),
543                Ok(None) if Instant::now() < deadline => {
544                    std::thread::sleep(Duration::from_millis(10))
545                }
546                _ => {
547                    let _ = self.child.kill();
548                    break self.child.wait().ok();
549                }
550            }
551        };
552        self.stop_group();
553        self.finish_stderr();
554        let message = match status {
555            Some(s) => match (s.code(), signal_of(&s)) {
556                (Some(code), _) => format!("Node exited with status {code} ({why})"),
557                (None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
558                _ => why.to_string(),
559            },
560            None => why.to_string(),
561        };
562        let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
563        let message = if stopped {
564            "Brrrty was stopped, and stopped Node with it".to_string()
565        } else {
566            message
567        };
568        let failure = RuntimeFailure {
569            stopped,
570            message,
571            stderr_tail: self
572                .stderr_tail
573                .lock()
574                .map(|t| t.iter().cloned().collect())
575                .unwrap_or_default(),
576        };
577        self.failed = Some(failure.clone());
578        failure
579    }
580
581    /// Kill what is left of Node's process group: processes the site's
582    /// code started and left running. One started in a session of its
583    /// own (`detached`) is out of reach and keeps running, as under 11ty.
584    fn stop_group(&mut self) {
585        #[cfg(unix)]
586        kill_group(self.child.id());
587        live(self.child.id(), false);
588    }
589
590    /// Wait briefly for the rest of Node's stderr, then stop waiting: a
591    /// process Node started may hold it open for as long as it runs.
592    fn finish_stderr(&mut self) {
593        if let Some(t) = self.stderr_thread.take() {
594            let deadline = Instant::now() + STDERR_GRACE;
595            while !t.is_finished() && Instant::now() < deadline {
596                std::thread::sleep(Duration::from_millis(5));
597            }
598            if t.is_finished() {
599                let _ = t.join();
600            }
601        }
602    }
603
604    fn shown(&self, file: &Path) -> String {
605        file.strip_prefix(&self.root)
606            .unwrap_or(file)
607            .display()
608            .to_string()
609    }
610}
611
612impl JsRuntime for Worker {
613    fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
614        match self.request(
615            json!({"op": "setArg", "value": encode(arg)}),
616            "the data argument",
617        ) {
618            JsResult::Ok(_) => JsResult::Ok(()),
619            JsResult::Thrown(e) => JsResult::Thrown(e),
620            JsResult::Refused(r) => JsResult::Refused(r),
621            JsResult::Failed(f) => JsResult::Failed(f),
622        }
623    }
624
625    fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
626        let what = self.shown(file);
627        let key = (call, file.to_path_buf());
628        // The worker says `same` when the value is the one it sent last
629        // time for this file, and the decoded value is used again: equal
630        // data, and the same objects, which Brrrty compares cheaply.
631        self.earlier = self.last_loaded.get(&key).cloned();
632        let r = self.request(
633            json!({"op": "load", "path": file.to_string_lossy(), "call": call}),
634            &what,
635        );
636        if let JsResult::Ok(d) = &r {
637            self.last_loaded.insert(key, d.clone());
638        }
639        r
640    }
641
642    fn call(
643        &mut self,
644        f: FnHandle,
645        this: This<'_>,
646        args: &[Value],
647        settle: Settle,
648    ) -> JsResult<Decoded> {
649        let mut req = json!({"op": "call", "handle": f.0, "await": settle == Settle::Await});
650        let encoded = match this {
651            This::Value(v) => encode_all(std::iter::once(v).chain(args), Some(&mut self.kept)),
652            This::Opaque(what) => {
653                req["opaque"] = json!(what);
654                encode_all(args.iter(), Some(&mut self.kept))
655            }
656        };
657        let mut encoded = match encoded {
658            Ok(e) => e,
659            Err(why) => return JsResult::Refused(Refusal::new(why)),
660        };
661        if let This::Value(_) = this {
662            req["this"] = encoded.remove(0);
663        }
664        req["args"] = Json::Array(encoded);
665        self.request(req, "a data function")
666    }
667
668    fn page_open(
669        &mut self,
670        data: &Value,
671        traps: &[(String, String)],
672        defaults: &[String],
673    ) -> JsResult<PageId> {
674        let data = match encode_page(data, &mut self.kept) {
675            Ok(e) => e,
676            Err(why) => return JsResult::Refused(Refusal::new(why)),
677        };
678        let r = self.request(
679            json!({"op": "pageOpen", "data": data, "traps": traps, "defaults": defaults}),
680            "a page's data",
681        );
682        match r {
683            JsResult::Ok(d) => match d.value {
684                Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => JsResult::Ok(PageId(n as u64)),
685                other => JsResult::Failed(self.fail(&format!("pageOpen gave {other:?}"))),
686            },
687            JsResult::Thrown(e) => JsResult::Thrown(e),
688            JsResult::Refused(r) => JsResult::Refused(r),
689            JsResult::Failed(f) => JsResult::Failed(f),
690        }
691    }
692
693    fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
694        let r = self.request(
695            json!({"op": "pageVars", "page": page.0, "handle": f.0, "keys": keys}),
696            "a computed data function",
697        );
698        match r {
699            JsResult::Ok(d) => match strings(&d.value) {
700                Some(list) => JsResult::Ok(list),
701                None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
702            },
703            JsResult::Thrown(e) => JsResult::Thrown(e),
704            JsResult::Refused(r) => JsResult::Refused(r),
705            JsResult::Failed(f) => JsResult::Failed(f),
706        }
707    }
708
709    fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
710        self.request(
711            json!({"op": "pageCall", "page": page.0, "handle": f.0, "set": set}),
712            "a computed data function",
713        )
714    }
715
716    fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
717        let value = match encode_all(std::iter::once(value), Some(&mut self.kept)) {
718            Ok(mut e) => e.remove(0),
719            Err(why) => return JsResult::Refused(Refusal::new(why)),
720        };
721        match self.request(
722            json!({"op": "pageSet", "page": page.0, "key": key, "value": value}),
723            "a page's data",
724        ) {
725            JsResult::Ok(_) => JsResult::Ok(()),
726            JsResult::Thrown(e) => JsResult::Thrown(e),
727            JsResult::Refused(r) => JsResult::Refused(r),
728            JsResult::Failed(f) => JsResult::Failed(f),
729        }
730    }
731
732    fn page_close(&mut self, page: PageId) {
733        let _ = self.request(json!({"op": "pageClose", "page": page.0}), "a page's data");
734    }
735
736    fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
737        self.global_end = self.load_log.len();
738        let d = match self.request(json!({"op": "loadsChanged"}), "the data files") {
739            JsResult::Ok(d) => d,
740            JsResult::Thrown(e) => return JsResult::Thrown(e),
741            JsResult::Refused(r) => return JsResult::Refused(r),
742            JsResult::Failed(f) => return JsResult::Failed(f),
743        };
744        let Value::Array(items) = &d.value else {
745            return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
746        };
747        let mut out = Vec::new();
748        for (i, item) in items.iter().enumerate() {
749            let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
750                return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
751            };
752            let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
753                match at {
754                    [PathPart::Index(j), PathPart::Key(k), rest @ ..]
755                        if *j == i && k == "value" =>
756                    {
757                        Some(rest.to_vec())
758                    }
759                    _ => None,
760                }
761            };
762            out.push((
763                PathBuf::from(&*p),
764                Decoded {
765                    value,
766                    functions: d
767                        .functions
768                        .iter()
769                        .filter_map(|(at, h)| under(at).map(|a| (a, *h)))
770                        .collect(),
771                    refused: d
772                        .refused
773                        .iter()
774                        .filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
775                        .collect(),
776                },
777            ));
778        }
779        JsResult::Ok(out)
780    }
781
782    fn begin_calls(&mut self) -> JsResult<()> {
783        self.keep_raw
784            .store(KEEP_RAW, std::sync::atomic::Ordering::SeqCst);
785        let frame = match self.exchange(json!({"op": "callsBegin"}), "the data files") {
786            Ok(f) => f,
787            Err(f) => return JsResult::Failed(f),
788        };
789        let raw = frame.raw.unwrap_or(Json::Null);
790        self.load_handles = raw.get("handles").and_then(Json::as_u64).unwrap_or(0);
791        self.calls_begun = true;
792        let changed: Vec<&str> = raw
793            .get("changed")
794            .and_then(Json::as_array)
795            .map(|a| a.iter().filter_map(Json::as_str).collect())
796            .unwrap_or_default();
797        if !changed.is_empty() {
798            return JsResult::Refused(Refusal {
799                why: format!(
800                    "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",
801                    if changed.len() == 1 { "file" } else { "files" },
802                    changed.join(", ")
803                ),
804                impure: true,
805            });
806        }
807        if raw.get("protos").and_then(Json::as_bool) == Some(true) {
808            return JsResult::Refused(Refusal {
809                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(),
810                impure: true,
811            });
812        }
813        JsResult::Ok(())
814    }
815
816    fn set_filters(&mut self, filters: Filters) {
817        self.filters = Some(filters);
818    }
819
820    fn template_setup(&mut self, filters: &[String]) -> JsResult<()> {
821        match self.request(
822            json!({"op": "templateSetup", "filters": filters}),
823            "the JavaScript templates' setup",
824        ) {
825            JsResult::Ok(_) => JsResult::Ok(()),
826            JsResult::Thrown(e) => JsResult::Thrown(e),
827            JsResult::Refused(r) => JsResult::Refused(r),
828            JsResult::Failed(f) => JsResult::Failed(f),
829        }
830    }
831
832    fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate> {
833        let what = self.shown(file);
834        let r = self.request(
835            json!({"op": "templateLoad", "path": file.to_string_lossy(), "layout": layout}),
836            &what,
837        );
838        match r {
839            JsResult::Ok(data) => match self.last_head.get("template").and_then(Json::as_u64) {
840                Some(id) => JsResult::Ok(LoadedTemplate {
841                    id: TemplateId(id),
842                    data,
843                }),
844                None => JsResult::Failed(self.fail("templateLoad gave no template id")),
845            },
846            JsResult::Thrown(e) => JsResult::Thrown(e),
847            JsResult::Refused(r) => JsResult::Refused(r),
848            JsResult::Failed(f) => JsResult::Failed(f),
849        }
850    }
851
852    fn render(
853        &mut self,
854        template: TemplateId,
855        data: &Value,
856        first: Option<&Value>,
857        traps: &[(String, String)],
858        filters: &mut FilterCall<'_>,
859    ) -> JsResult<Decoded> {
860        let (data, first) = match encode_render(data, first, &mut self.kept) {
861            Ok(e) => e,
862            Err(why) => return JsResult::Refused(Refusal::new(why)),
863        };
864        let mut req = json!({"op": "render", "template": template.0, "data": data, "traps": traps});
865        if let Some(first) = first {
866            req["first"] = first;
867        }
868        self.request_with(req, "a JavaScript template", filters)
869    }
870
871    fn verify(&mut self) -> JsResult<()> {
872        // What the calls changed of the data files' values comes first: it
873        // explains whatever the replay would find.
874        match self.request(json!({"op": "exportsFinal"}), "the data files' values") {
875            JsResult::Ok(_) => {}
876            other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
877                return match other {
878                    JsResult::Refused(r) => JsResult::Refused(r),
879                    JsResult::Failed(f) => JsResult::Failed(f),
880                    _ => JsResult::Ok(()),
881                };
882            }
883            JsResult::Thrown(e) => return JsResult::Thrown(e),
884        }
885        let log = crate::replay::Log {
886            node: &self.node,
887            root: &self.root,
888            run_mode: self.run_mode,
889            loads: &self.load_log,
890            global_end: self.global_end,
891            load_handles: self.load_handles,
892            calls: &self.call_log,
893            slowest: self.slowest,
894        };
895        match log.check() {
896            Ok(()) => JsResult::Ok(()),
897            Err(crate::replay::Failure::Differs(why, handle)) => {
898                let named = handle
899                    .and_then(|h| {
900                        self.exchange(json!({"op": "describe", "handle": h}), "a function's name")
901                            .ok()
902                    })
903                    .and_then(|f| f.raw)
904                    .and_then(|r| r.as_str().map(str::to_string))
905                    .unwrap_or_else(|| "a function from JavaScript data".to_string());
906                JsResult::Refused(Refusal {
907                    why: why.replace("{fn}", &named),
908                    impure: true,
909                })
910            }
911            Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
912        }
913    }
914
915    fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
916        match self.request(json!({"op": "reads"}), "the list of files read") {
917            JsResult::Ok(d) => match strings(&d.value) {
918                Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
919                None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
920            },
921            JsResult::Thrown(e) => JsResult::Thrown(e),
922            JsResult::Refused(r) => JsResult::Refused(r),
923            JsResult::Failed(f) => JsResult::Failed(f),
924        }
925    }
926}
927
928impl Drop for Worker {
929    fn drop(&mut self) {
930        if let Some(mut stdin) = self.stdin.take() {
931            let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
932        }
933        let deadline = Instant::now() + Duration::from_secs(2);
934        loop {
935            match self.child.try_wait() {
936                Ok(Some(_)) => break,
937                Ok(None) if Instant::now() < deadline => {
938                    std::thread::sleep(Duration::from_millis(5))
939                }
940                _ => {
941                    let _ = self.child.kill();
942                    let _ = self.child.wait();
943                    break;
944                }
945            }
946        }
947        self.stop_group();
948        self.finish_stderr();
949    }
950}
951
952/// The process ids of the workers running now. Each leads its own process
953/// group, so a terminal's Ctrl-C doesn't reach it: [`stop_all`] does.
954static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
955
956/// Set once [`stop_all`] ran: a worker failing after that was stopped.
957static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
958
959fn live(pid: u32, running: bool) {
960    let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
961    l.retain(|p| *p != pid);
962    if running {
963        l.push(pid);
964    }
965}
966
967/// Kill every running worker and what it started, at once: for Ctrl-C,
968/// SIGTERM and a panic. Safe to call from a signal handler thread.
969pub fn stop_all() {
970    STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
971    let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
972    #[cfg(unix)]
973    for pid in l.iter() {
974        kill_group(*pid);
975    }
976}
977
978#[cfg(unix)]
979fn kill_group(pid: u32) {
980    if let Ok(pid) = i32::try_from(pid) {
981        // SAFETY: killpg only sends a signal, to the group Node leads.
982        unsafe {
983            libc::killpg(pid, libc::SIGKILL);
984        }
985    }
986}
987
988/// Start the worker. Its replies come on a pipe of their own, which Node
989/// inherits under the descriptor number it has here, and its stdout joins
990/// its stderr: a child process or logger writing to fd 1 is only noise, as
991/// it is under 11ty.
992#[cfg(unix)]
993fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
994    use std::os::fd::AsRawFd;
995    use std::os::unix::process::CommandExt;
996    let (frames_r, frames_w) = std::io::pipe()?;
997    // A copy is numbered 3 or above, clear of the standard three.
998    let frames_w = frames_w.try_clone()?;
999    let (answers_r, answers_w) = std::io::pipe()?;
1000    let answers_r = answers_r.try_clone()?;
1001    let (err_r, err_w) = std::io::pipe()?;
1002    let fd = frames_w.as_raw_fd();
1003    let answers_fd = answers_r.as_raw_fd();
1004    cmd.stdout(err_w.try_clone()?)
1005        .stderr(err_w)
1006        .env("BRRRTY_FRAMES_FD", fd.to_string())
1007        .env("BRRRTY_ANSWERS_FD", answers_fd.to_string())
1008        // A group of its own, so what Node starts can be stopped with it.
1009        .process_group(0);
1010    // SAFETY: fcntl is async-signal-safe, and the descriptor is this
1011    // process's own, open until after the spawn.
1012    unsafe {
1013        cmd.pre_exec(move || {
1014            // Keep it open across exec in Node only.
1015            if libc::fcntl(fd, libc::F_SETFD, 0) == -1
1016                || libc::fcntl(answers_fd, libc::F_SETFD, 0) == -1
1017            {
1018                return Err(std::io::Error::last_os_error());
1019            }
1020            Ok(())
1021        });
1022    }
1023    let child = cmd.spawn();
1024    // The parent's write ends close here, so the reads end when Node's do.
1025    drop(cmd);
1026    drop(frames_w);
1027    drop(answers_r);
1028    Ok((
1029        child?,
1030        Box::new(frames_r),
1031        Box::new(err_r),
1032        Some(Box::new(answers_w)),
1033    ))
1034}
1035
1036/// A started Node: the process, its replies, its stderr, and where
1037/// Brrrty answers its questions (none where that pipe can't be passed).
1038type Spawned = (
1039    Child,
1040    Box<dyn Read + Send>,
1041    Box<dyn Read + Send>,
1042    Option<Box<dyn Write + Send>>,
1043);
1044
1045/// Start the worker, its replies on stdout.
1046#[cfg(not(unix))]
1047fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
1048    let mut child = cmd
1049        .stdout(Stdio::piped())
1050        .stderr(Stdio::piped())
1051        .env("BRRRTY_FRAMES_FD", "1")
1052        .spawn()?;
1053    let stdout = child.stdout.take().expect("piped stdout");
1054    let stderr = child.stderr.take().expect("piped stderr");
1055    Ok((child, Box::new(stdout), Box::new(stderr), None))
1056}
1057
1058#[cfg(unix)]
1059fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
1060    use std::os::unix::process::ExitStatusExt;
1061    s.signal()
1062}
1063
1064#[cfg(not(unix))]
1065fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
1066    None
1067}
1068
1069/// Read `\x1eBRRRTY <len>\n<json>` frames until Node closes stdout.
1070/// Anything else is a protocol error, sent once.
1071fn read_frames(
1072    stdout: impl Read,
1073    tx: mpsc::Sender<Reply>,
1074    keep_raw: Arc<std::sync::atomic::AtomicU8>,
1075) {
1076    let mut r = BufReader::new(stdout);
1077    loop {
1078        let mut header = Vec::new();
1079        match r.read_until(b'\n', &mut header) {
1080            Ok(0) => return,
1081            Ok(_) => {}
1082            Err(e) => {
1083                let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
1084                return;
1085            }
1086        }
1087        let len = header
1088            .strip_prefix(b"\x1eBRRRTY ")
1089            .and_then(|h| h.strip_suffix(b"\n"))
1090            .and_then(|n| std::str::from_utf8(n).ok())
1091            .and_then(|n| n.parse::<usize>().ok());
1092        let Some(len) = len else {
1093            let shown = String::from_utf8_lossy(&header);
1094            let _ = tx.send(Err(format!(
1095                "something other than the worker wrote to its output: {:?}",
1096                shown.chars().take(80).collect::<String>()
1097            )));
1098            return;
1099        };
1100        let mut body = vec![0; len];
1101        if let Err(e) = r.read_exact(&mut body) {
1102            let _ = tx.send(Err(format!("a cut-off reply: {e}")));
1103            return;
1104        }
1105        let keep = keep_raw.load(std::sync::atomic::Ordering::SeqCst);
1106        let parsed = parse_reply(&body).map(|mut head| {
1107            let value = head.as_object_mut().and_then(|o| o.remove("ok"));
1108            let ok = value.as_ref().map(decode);
1109            let raw = if keep == KEEP_RAW { value } else { None };
1110            let text = (keep == KEEP_TEXT)
1111                .then(|| String::from_utf8_lossy(&body).into_owned().into_boxed_str());
1112            Frame {
1113                head,
1114                ok,
1115                raw,
1116                text,
1117            }
1118        });
1119        if tx.send(parsed).is_err() {
1120            return;
1121        }
1122    }
1123}
1124
1125/// A list of strings, as `reads` and `varsUsed` reply.
1126fn strings(v: &Value) -> Option<Vec<String>> {
1127    match v {
1128        Value::Array(a) => a
1129            .iter()
1130            .map(|s| match s {
1131                Value::String(s) => Some(s.to_string()),
1132                _ => None,
1133            })
1134            .collect(),
1135        _ => None,
1136    }
1137}
1138
1139/// One reply body, without serde's nesting limit (see [`REPLY_STACK`]).
1140pub(crate) fn parse_reply(body: &[u8]) -> Result<Json, String> {
1141    let mut de = serde_json::Deserializer::from_slice(body);
1142    de.disable_recursion_limit();
1143    let v = serde::Deserialize::deserialize(&mut de)
1144        .and_then(|v: Json| de.end().map(|()| v))
1145        .map_err(|e| format!("a reply that isn't JSON: {e}"))?;
1146    Ok(v)
1147}
1148
1149/// Pass Node's stderr through to Brrrty's, as it comes, keeping the last
1150/// lines for a failure report.
1151fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
1152    let mut r = BufReader::new(stderr);
1153    let mut line = Vec::new();
1154    let mut err = std::io::stderr();
1155    loop {
1156        line.clear();
1157        match r.read_until(b'\n', &mut line) {
1158            Ok(0) | Err(_) => return,
1159            Ok(_) => {
1160                let _ = err.write_all(&line);
1161                if let Ok(mut t) = tail.lock() {
1162                    if t.len() == STDERR_TAIL {
1163                        t.pop_front();
1164                    }
1165                    t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
1166                }
1167            }
1168        }
1169    }
1170}
1171
1172/// The site's error, placed: a SyntaxError at the header Node prints for
1173/// it, anything else at the first stack frame inside the project and
1174/// outside `node_modules`.
1175fn js_error(t: &Json, root: &Path) -> JsError {
1176    let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
1177    let stack = s("stack");
1178    let place = crate::stack::syntax_header(&s("inspect"))
1179        .or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
1180    JsError {
1181        name: s("name"),
1182        message: s("message"),
1183        file: place.as_ref().map(|p| p.file.clone()),
1184        line: place.as_ref().map(|p| p.line),
1185        column: place.and_then(|p| p.column),
1186        stack,
1187        invalid: false,
1188    }
1189}
1190
1191/// Values in the worker's wire forms, for a call: an object or array
1192/// that appears more than once is sent once (`{"$s": [id, value]}`, then
1193/// `{"$r": id}`), so data shared between pages, as 11ty shares it, stays
1194/// one object; and a property Brrrty doesn't have the value of (a
1195/// collection item's content, a key it withholds) is sent as a trap,
1196/// `{"$t": why}`, which refuses the call when the function reads it. `Err`
1197/// when a value can't be handed over at all.
1198///
1199/// With `kept`, a list of [`KEPT_LEN`] items or more is kept by the worker
1200/// between requests (`{"$S": [id, value]}`, then `{"$R": id}`): the lists
1201/// global data gives every page cross once, and stay one list, as in 11ty.
1202pub fn encode_all<'v>(
1203    values: impl Iterator<Item = &'v Value> + Clone,
1204    kept: Option<&mut Kept>,
1205) -> Result<Vec<Json>, String> {
1206    let mut counts: HashMap<usize, u32> = HashMap::new();
1207    for v in values.clone() {
1208        count(v, &mut counts, kept.as_deref());
1209    }
1210    let mut e = Encoder {
1211        counts,
1212        ids: HashMap::new(),
1213        kept,
1214        no_keep: None,
1215        in_kept: 0,
1216        guard: false,
1217    };
1218    values.map(|v| e.encode(v)).collect()
1219}
1220
1221/// [`encode_all`] of a page's data, whose top object is the page's own:
1222/// what is inside it may be kept, the object itself isn't.
1223fn encode_page(data: &Value, kept: &mut Kept) -> Result<Json, String> {
1224    let mut counts: HashMap<usize, u32> = HashMap::new();
1225    count(data, &mut counts, Some(kept));
1226    let mut e = Encoder {
1227        counts,
1228        ids: HashMap::new(),
1229        kept: Some(kept),
1230        no_keep: ptr_of(data),
1231        in_kept: 0,
1232        guard: false,
1233    };
1234    e.encode(data)
1235}
1236
1237/// A render's data and `first` page in the worker's wire forms: the data's
1238/// own top object isn't kept, `first` is page 0's `page` (the same object
1239/// as the data's `page` on page 0, sent once), and a `collections` object
1240/// Brrrty can't answer everything about crosses guarded (see
1241/// [`Encoder::guard`]).
1242fn encode_render(
1243    data: &Value,
1244    first: Option<&Value>,
1245    kept: &mut Kept,
1246) -> Result<(Json, Option<Json>), String> {
1247    let mut counts: HashMap<usize, u32> = HashMap::new();
1248    count(data, &mut counts, Some(kept));
1249    if let Some(f) = first {
1250        count(f, &mut counts, Some(kept));
1251    }
1252    let mut e = Encoder {
1253        counts,
1254        ids: HashMap::new(),
1255        kept: Some(kept),
1256        no_keep: ptr_of(data),
1257        in_kept: 0,
1258        guard: true,
1259    };
1260    let data = e.encode(data)?;
1261    let first = first.map(|f| e.encode(f)).transpose()?;
1262    Ok((data, first))
1263}
1264
1265/// How many items or keys a list or object must have for the worker to
1266/// keep it between requests.
1267pub const KEPT_LEN: usize = 8;
1268
1269/// The lists the worker keeps, by address, each held so the address stays
1270/// its own.
1271#[derive(Default)]
1272pub struct Kept {
1273    lists: HashMap<usize, (Value, u64)>,
1274    next: u64,
1275}
1276
1277fn ptr_of(v: &Value) -> Option<usize> {
1278    match v {
1279        Value::Object(o) => Some(Arc::as_ptr(o) as usize),
1280        Value::Array(a) => Some(Arc::as_ptr(a) as usize),
1281        _ => None,
1282    }
1283}
1284
1285/// How often each object and list appears in a request. A list the worker
1286/// keeps already is sent as a reference, so what is inside it doesn't count.
1287fn count(v: &Value, counts: &mut HashMap<usize, u32>, kept: Option<&Kept>) {
1288    let mut stack = vec![v];
1289    while let Some(v) = stack.pop() {
1290        let Some(p) = ptr_of(v) else { continue };
1291        let n = counts.entry(p).or_insert(0);
1292        *n += 1;
1293        if *n > 1 || kept.is_some_and(|k| k.lists.contains_key(&p)) {
1294            continue;
1295        }
1296        match v {
1297            Value::Object(o) => stack.extend(o.values()),
1298            Value::Array(a) => stack.extend(a.iter()),
1299            _ => {}
1300        }
1301    }
1302}
1303
1304struct Encoder<'k> {
1305    counts: HashMap<usize, u32>,
1306    /// The id of each shared object or array sent so far.
1307    ids: HashMap<usize, usize>,
1308    kept: Option<&'k mut Kept>,
1309    /// The one object or list not to keep.
1310    no_keep: Option<usize>,
1311    /// How many kept values the encoder is inside.
1312    in_kept: usize,
1313    /// Send a `collections` object that traps (an open or order-unknown
1314    /// one) as a guarded object instead of refusing it: a render gets the
1315    /// whole page data, `collections` included.
1316    guard: bool,
1317}
1318
1319/// Why a JavaScript template can't read a name an open `collections`
1320/// object doesn't have (`{key}` is the name).
1321const OPEN_MISSING: &str = "reads `collections.{key}`, which Brrrty doesn't have: the site's 11ty config may add it, or a page in it can't be built (see the other problems)";
1322
1323/// Why a JavaScript template can't list an open `collections` object.
1324const OPEN_LIST: &str = "lists the names in `collections`, and the site's 11ty config may add collections Brrrty can't see";
1325
1326/// Why a property Brrrty marks as unknown can't be handed to a function.
1327fn trap_reason(key: &str) -> String {
1328    match key {
1329        "templateContent" | "content" => format!(
1330            "reads `{key}` of a collection item, which 11ty fills in only as it renders pages"
1331        ),
1332        "template" => {
1333            "reads `template` of a collection item, 11ty's internal template object".to_string()
1334        }
1335        "rawInput" => {
1336            "reads `rawInput` of a JavaScript template's page, which in 11ty is its instance object, not text".to_string()
1337        }
1338        _ => format!("reads `{key}`, which Brrrty doesn't hand to JavaScript functions yet"),
1339    }
1340}
1341
1342impl Encoder<'_> {
1343    fn encode(&mut self, v: &Value) -> Result<Json, String> {
1344        let Some(p) = ptr_of(v) else {
1345            return Ok(encode(v));
1346        };
1347        let big = match v {
1348            Value::Array(a) => a.len() >= KEPT_LEN,
1349            Value::Object(o) => o.len() >= KEPT_LEN && !brrrty_js::traps::is_guarded_object(o),
1350            _ => false,
1351        };
1352        if big
1353            && self.no_keep != Some(p)
1354            && let Some(kept) = self.kept.as_deref_mut()
1355        {
1356            if let Some((_, id)) = kept.lists.get(&p) {
1357                return Ok(json!({"$R": id}));
1358            }
1359            let id = kept.next;
1360            kept.next += 1;
1361            kept.lists.insert(p, (v.clone(), id));
1362            // A kept value stands on its own: it may be sent again, by
1363            // itself, in another request (the replay check does), so what
1364            // is inside it never refers to this request's shared values.
1365            self.in_kept += 1;
1366            let inner = self.inner(v);
1367            self.in_kept -= 1;
1368            return Ok(json!({"$S": [id, inner?]}));
1369        }
1370        if self.in_kept > 0 {
1371            return self.inner(v);
1372        }
1373        self.encode_inline(v, p)
1374    }
1375
1376    /// `v` (at address `p`) in full, as a value shared within the request
1377    /// when it appears more than once in it.
1378    fn encode_inline(&mut self, v: &Value, p: usize) -> Result<Json, String> {
1379        if let Some(id) = self.ids.get(&p) {
1380            return Ok(json!({"$r": id}));
1381        }
1382        let shared = self.counts.get(&p).copied().unwrap_or(0) > 1;
1383        let id = self.ids.len();
1384        if shared {
1385            self.ids.insert(p, id);
1386        }
1387        let inner = self.inner(v)?;
1388        Ok(if shared {
1389            json!({"$s": [id, inner]})
1390        } else {
1391            inner
1392        })
1393    }
1394
1395    /// A list or object's own wire form.
1396    fn inner(&mut self, v: &Value) -> Result<Json, String> {
1397        Ok(match v {
1398            Value::Array(a) => Json::Array(
1399                a.iter()
1400                    .map(|x| self.encode(x))
1401                    .collect::<Result<Vec<_>, _>>()?,
1402            ),
1403            Value::Object(o) => {
1404                let open = brrrty_js::traps::is_open_object(o);
1405                let unordered = brrrty_js::traps::unordered_reason(o);
1406                if (open || unordered.is_some()) && !self.guard {
1407                    return Err(
1408                        "passes the whole `collections` object to a function, which Brrrty doesn't do yet; pass one collection, like `collections.post`".to_string(),
1409                    );
1410                }
1411                let mut entries = Vec::with_capacity(o.len());
1412                // A render's own `content` (a layout's, given `undefined` by
1413                // a template's render) is a value, not an item's marker.
1414                let top = self.guard && self.no_keep == ptr_of(v);
1415                for (k, x) in o.iter() {
1416                    let item = if matches!(x, Value::Undefined)
1417                        && brrrty_js::traps::TRAP_KEYS.contains(&k.as_str())
1418                        && !(top && brrrty_js::traps::CONTENT_KEYS.contains(&k.as_str()))
1419                    {
1420                        json!({"$t": trap_reason(k)})
1421                    } else {
1422                        self.encode(x)?
1423                    };
1424                    entries.push(json!([k, item]));
1425                }
1426                if let Some(keys) = brrrty_js::traps::withheld_keys(o) {
1427                    for k in keys.iter().filter(|k| !o.contains_key(k.as_str())) {
1428                        entries.push(json!([k, {"$t": format!("reads `{k}` of another page's `data`, which Brrrty can't supply")}]));
1429                    }
1430                }
1431                if open || unordered.is_some() {
1432                    let mut c = serde_json::Map::new();
1433                    if open {
1434                        c.insert("missing".into(), json!(OPEN_MISSING));
1435                    }
1436                    match (&unordered, open) {
1437                        (Some(why), _) => {
1438                            c.insert(
1439                                "list".into(),
1440                                json!(format!("lists the names in `collections`, {why}")),
1441                            );
1442                        }
1443                        (None, true) => {
1444                            c.insert("list".into(), json!(OPEN_LIST));
1445                        }
1446                        (None, false) => {}
1447                    }
1448                    return Ok(json!({"$o": entries, "$c": c}));
1449                }
1450                json!({"$o": entries})
1451            }
1452            _ => encode(v),
1453        })
1454    }
1455}
1456
1457/// A Brrrty value in the worker's wire forms.
1458pub fn encode(v: &Value) -> Json {
1459    match v {
1460        Value::Undefined => json!({"$u": 1}),
1461        Value::Null => Json::Null,
1462        Value::Bool(b) => Json::Bool(*b),
1463        Value::Number(n) => {
1464            if n.is_nan() {
1465                json!({"$n": "NaN"})
1466            } else if *n == f64::INFINITY {
1467                json!({"$n": "Infinity"})
1468            } else if *n == f64::NEG_INFINITY {
1469                json!({"$n": "-Infinity"})
1470            } else if *n == 0.0 && n.is_sign_negative() {
1471                json!({"$n": "-0"})
1472            } else {
1473                serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
1474            }
1475        }
1476        Value::String(s) => Json::String(s.to_string()),
1477        Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
1478        Value::Object(o) => {
1479            json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
1480        }
1481        Value::Date(d) => json!({"$d": d.timestamp_millis()}),
1482        Value::Function(h) => json!({"$f": h.0}),
1483    }
1484}
1485
1486#[cfg(test)]
1487mod tests {
1488    use super::*;
1489
1490    fn object(n: usize) -> Value {
1491        Value::Object(Arc::new(
1492            (0..n)
1493                .map(|i| (format!("k{i}"), Value::Number(i as f64)))
1494                .collect(),
1495        ))
1496    }
1497
1498    #[test]
1499    fn big_objects_and_lists_cross_once_and_the_page_itself_never_is_kept() {
1500        let mut kept = Kept::default();
1501        let big = object(KEPT_LEN);
1502        let small = object(2);
1503        let first = encode_all([&big, &small].into_iter(), Some(&mut kept)).unwrap();
1504        assert!(first[0].get("$S").is_some(), "{}", first[0]);
1505        assert!(first[1].get("$o").is_some(), "{}", first[1]);
1506        let again = encode_all([&big].into_iter(), Some(&mut kept)).unwrap();
1507        assert_eq!(again[0], json!({"$R": 0}));
1508        // A page's own data object holds kept values but isn't one.
1509        let page = Value::Object(Arc::new(
1510            (0..KEPT_LEN)
1511                .map(|i| (format!("p{i}"), big.clone()))
1512                .collect(),
1513        ));
1514        let p = encode_page(&page, &mut kept).unwrap();
1515        assert!(p.get("$o").is_some(), "{p}");
1516        assert!(p.to_string().contains("\"$R\":0"), "{p}");
1517    }
1518}