use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use brrrty_js::Value;
use brrrty_js::runtime::{
Begun, Decoded, FilterCall, Filters, Finished, FnHandle, JsError, JsResult, JsRuntime,
LoadedTemplate, Op, PageId, PageStep, PathPart, Pending, Refusal, RuntimeFailure, Settle,
TemplateId, This, Waited,
};
use serde_json::{Value as Json, json};
use crate::decode::decode;
use crate::find::NodeInfo;
use crate::wire::{Added, Table};
const WORKER_SOURCE: &str = concat!(
include_str!("worker/encode.mjs"),
"\n",
include_str!("worker/proxy.mjs"),
"\n",
include_str!("worker/config.mjs"),
"\n",
include_str!("worker/main.mjs"),
);
pub const SOURCE_FILE: &str = "brrrty-worker-source.mjs";
fn worker_source() -> std::borrow::Cow<'static, str> {
#[cfg(test)]
{
let pad = tests_pad::PAD.with(|p| p.get());
if pad > 0 {
return format!("{}\n//{}\n", base_source(), "x".repeat(pad)).into();
}
}
std::borrow::Cow::Borrowed(base_source())
}
#[cfg(test)]
mod tests_pad {
thread_local! {
pub(super) static PAD: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
}
fn base_source() -> &'static str {
static SOURCE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
let mut out = String::with_capacity(WORKER_SOURCE.len());
for line in WORKER_SOURCE.split('\n') {
if !line.trim_start().starts_with("//") {
out.push_str(line);
}
out.push('\n');
}
out.pop();
out
});
&SOURCE
}
const ELEVENTY_VERSION: &str = "3.1.8";
pub(crate) const REPLY_STACK: usize = 32 * 1024 * 1024;
const STDERR_TAIL: usize = 20;
const STDERR_GRACE: Duration = Duration::from_millis(200);
const AGAIN: usize = 16;
fn logged(op: &str) -> bool {
!matches!(
op,
"reads" | "info" | "callsBegin" | "loadsChanged" | "exportsFinal" | "describe"
)
}
const PIPE_SAFE: usize = 4000;
const SPIN: Duration = Duration::from_micros(60);
const POLL: Duration = Duration::from_millis(100);
const FIRST_NOTE: Duration = Duration::from_secs(10);
const NEXT_NOTE: Duration = Duration::from_secs(30);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunMode {
Build,
Serve,
}
impl RunMode {
pub fn as_str(self) -> &'static str {
match self {
RunMode::Build => "build",
RunMode::Serve => "serve",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerError(pub String);
impl std::fmt::Display for WorkerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
type Reply = Result<Frame, String>;
pub(crate) struct Frame {
pub question: bool,
pub id: u64,
pub head: Json,
ok: Option<Result<Decoded, String>>,
pub body: Box<str>,
pub clock: Option<Box<str>>,
pub made: bool,
pub seq: u64,
}
impl Frame {
pub fn value(&self) -> Option<&Value> {
match &self.ok {
Some(Ok(d)) => Some(&d.value),
_ => None,
}
}
}
pub(crate) struct LoadRecord {
pub text: Box<str>,
pub kind: LoadKind,
pub path: String,
pub body: Box<str>,
pub clock: Option<Box<str>>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum LoadKind {
Data,
Template,
Other,
}
pub(crate) struct Record {
pub unit: u64,
pub label: Arc<str>,
pub op: &'static str,
pub handle: Option<u32>,
pub text: Box<str>,
pub body: Box<str>,
pub clock: Option<Box<str>>,
pub made: bool,
pub dynamic: Vec<u32>,
pub names_made: bool,
pub answers: Vec<(Box<str>, Box<str>)>,
pub one_way: bool,
pub unchecked: bool,
pub at: (u64, u32),
}
type Notes = Box<dyn Fn(&str) + Send>;
type Planned = (Vec<Request<'static>>, Shape, Option<PageId>, &'static str);
pub(crate) struct Mux {
child: Mutex<Child>,
stdin: Mutex<Option<ChildStdin>>,
answers: Mutex<Option<Box<dyn Write + Send>>>,
routes: Mutex<HashMap<u64, mpsc::Sender<Reply>>>,
notes: Mutex<Notes>,
note_times: Mutex<(Duration, Duration)>,
}
fn locked<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
impl Mux {
fn next(
&self,
rx: &Receiver<Reply>,
what: &str,
wait: &mut Wait,
deadline: Option<Duration>,
) -> Result<Frame, String> {
let spun = Instant::now();
loop {
match rx.try_recv() {
Ok(r) => return r,
Err(mpsc::TryRecvError::Disconnected) => break,
Err(mpsc::TryRecvError::Empty) if spun.elapsed() < SPIN => std::hint::spin_loop(),
Err(mpsc::TryRecvError::Empty) => break,
}
}
loop {
match rx.recv_timeout(POLL) {
Ok(r) => return r,
Err(RecvTimeoutError::Timeout) => {
let now = Instant::now();
if let Some(d) = deadline
&& now.duration_since(wait.start) > d
{
return Err(format!(
"{what} took more than {} s, longer than the first run allows",
d.as_secs()
));
}
if now >= wait.next_note {
let waiting = locked(&self.routes).len();
let behind = if waiting > 1 {
format!(
" ({waiting} requests are waiting on Node, which runs one at a time)"
)
} else {
String::new()
};
(locked(&self.notes))(&format!(
"note: still waiting on {what}, {} s{behind}",
wait.start.elapsed().as_secs()
));
wait.next_note = now + locked(&self.note_times).1;
}
match wait.exited_at {
Some(t) if now.duration_since(t) >= POLL => {
return Err("Node exited without replying".to_string());
}
Some(_) => {}
None => {
if matches!(locked(&self.child).try_wait(), Ok(Some(_))) {
wait.exited_at = Some(now);
}
}
}
}
Err(RecvTimeoutError::Disconnected) => {
return Err("Node closed its output".to_string());
}
}
}
}
fn wait(&self) -> Wait {
let start = Instant::now();
Wait {
start,
next_note: start + locked(&self.note_times).0,
exited_at: None,
}
}
fn answer(&self, frame: &Frame, filters: &mut FilterCall<'_>) -> Result<Box<str>, String> {
let name = frame
.head
.get("filter")
.and_then(Json::as_str)
.unwrap_or("")
.to_string();
let args = match &frame.ok {
Some(Ok(d)) if d.is_exact() => match &d.value {
Value::Array(a) => Ok(a.to_vec()),
_ => Err("passes its filter something Brrrty can't read".to_string()),
},
Some(Ok(_)) => Err(format!(
"passes `this.{name}` a function or a value that can't cross from JavaScript to Brrrty exactly"
)),
_ => Err("passes its filter something Brrrty can't read".to_string()),
};
let reply: Box<str> = match args.and_then(|a| filters(&name, &a)) {
Ok(v) => json!({"ok": encode(&v)}),
Err(why) => json!({"refused": why}),
}
.to_string()
.into();
self.send_answer(&reply)?;
Ok(reply)
}
fn send_answer(&self, reply: &str) -> Result<(), String> {
match locked(&self.answers).as_mut() {
Some(w) => w
.write_all(reply.as_bytes())
.and_then(|_| w.write_all(b"\n"))
.and_then(|_| w.flush())
.map_err(|e| format!("cannot answer Node: {e}")),
None => Err("Node asked a question it can't be answered on".to_string()),
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum Shape {
List,
Once,
OpenWithVars,
}
struct Sent {
id: u64,
op: &'static str,
handle: Option<u32>,
text: String,
path: Option<String>,
one_way: bool,
made: bool,
dynamic: Vec<u32>,
}
pub(crate) struct Ticket {
mux: Arc<Mux>,
rx: Receiver<Reply>,
sent: Vec<Sent>,
what: String,
shape: Shape,
page: Option<PageId>,
deadline: Option<Duration>,
}
pub(crate) struct Done {
sent: Vec<Sent>,
frames: Vec<Frame>,
asked: Vec<Vec<(Box<str>, Box<str>)>>,
failure: Option<String>,
what: String,
shape: Shape,
page: Option<PageId>,
waited: Duration,
}
impl Ticket {
fn collect(self, filters: &mut FilterCall<'_>) -> Done {
let started = Instant::now();
let mut frames = Vec::with_capacity(self.sent.len());
let mut asked = Vec::with_capacity(self.sent.len());
let mut failure = None;
'all: for sent in self.sent.iter().filter(|s| !s.one_way) {
let mut wait = self.mux.wait();
let mut questions = Vec::new();
loop {
match self
.mux
.next(&self.rx, &self.what, &mut wait, self.deadline)
{
Ok(f) if f.question => match self.mux.answer(&f, filters) {
Ok(reply) => questions.push((f.body.clone(), reply)),
Err(why) => {
failure = Some(why);
break 'all;
}
},
Ok(f) if f.id != sent.id => {
failure = Some(format!("a reply out of order: {}", f.head));
break 'all;
}
Ok(f) => {
frames.push(f);
asked.push(questions);
break;
}
Err(why) => {
failure = Some(why);
break 'all;
}
}
}
}
let mut routes = locked(&self.mux.routes);
for sent in &self.sent {
routes.remove(&sent.id);
}
drop(routes);
Done {
sent: self.sent,
frames,
asked,
failure,
what: self.what,
shape: self.shape,
page: self.page,
waited: started.elapsed(),
}
}
}
impl Pending for Ticket {
fn wait(self: Box<Self>, filters: &mut FilterCall<'_>) -> Waited {
Waited(Box::new(self.collect(filters)))
}
}
pub struct Worker {
_source_dir: tempfile::TempDir,
mux: Arc<Mux>,
pid: u32,
pub(crate) answers_feed: Option<VecDeque<(Box<str>, Box<str>)>>,
asked: Vec<(Box<str>, Box<str>)>,
filters: Option<Filters>,
replies: Receiver<Reply>,
stderr_tail: Arc<Mutex<VecDeque<String>>>,
stderr_thread: Option<JoinHandle<()>>,
root: PathBuf,
next_id: u64,
next_page: u64,
failed: Option<RuntimeFailure>,
last_loaded: HashMap<(bool, PathBuf), Decoded>,
earlier: Option<Decoded>,
fixed: std::collections::HashSet<(bool, PathBuf)>,
last_fixed: bool,
last_seq: u64,
table: Table,
node: NodeInfo,
run_mode: RunMode,
pub(crate) decode: Arc<AtomicBool>,
load_log: Vec<LoadRecord>,
global_end: usize,
call_log: Vec<Record>,
dropped: bool,
calls_begun: bool,
load_handles: u64,
replays: Option<[crate::replay::Handle; 2]>,
order_check: bool,
slowest: Duration,
pub(crate) deadline: Option<Duration>,
last_template: Option<u64>,
next_ticket: u64,
stats: Stats,
frozen: bool,
walk: Option<String>,
walks: Option<String>,
}
#[derive(Default)]
struct Stats {
started: Option<Instant>,
requests: u64,
sent: u64,
defined: u64,
definitions: u64,
received: u64,
waited: Duration,
}
struct Request<'a> {
op: &'static str,
text: String,
added: Added,
handle: Option<u32>,
path: Option<&'a Path>,
one_way: bool,
}
impl<'a> Request<'a> {
fn new(op: &'static str, text: String) -> Request<'a> {
Request {
op,
text,
added: Added::default(),
handle: None,
path: None,
one_way: false,
}
}
}
pub(crate) struct Wait {
start: Instant,
next_note: Instant,
exited_at: Option<Instant>,
}
impl Worker {
pub fn start(node: &NodeInfo, root: &Path, run_mode: RunMode) -> Result<Worker, WorkerError> {
Worker::start_as(node, root, run_mode, None)
}
pub(crate) fn start_as(
node: &NodeInfo,
root: &Path,
run_mode: RunMode,
replay: Option<&crate::replay::Loads>,
) -> Result<Worker, WorkerError> {
Worker::start_checked(node, root, run_mode, replay, true)
}
pub fn start_with(
node: &NodeInfo,
root: &Path,
run_mode: RunMode,
order_check: bool,
) -> Result<Worker, WorkerError> {
Worker::start_checked(node, root, run_mode, None, order_check)
}
fn start_checked(
node: &NodeInfo,
root: &Path,
run_mode: RunMode,
replay: Option<&crate::replay::Loads>,
order_check: bool,
) -> Result<Worker, WorkerError> {
let walk = match replay {
Some(loads) => loads.walk.clone(),
None => walk_roots().starting(root),
};
let cannot =
|e: std::io::Error| WorkerError(format!("cannot start {}: {e}", node.path.display()));
let source_dir = tempfile::Builder::new()
.prefix("brrrty-worker-")
.tempdir()
.map_err(cannot)?;
let source_file = source_dir.path().join(SOURCE_FILE);
std::fs::write(&source_file, worker_source().as_bytes()).map_err(cannot)?;
let mut cmd = Command::new(&node.path);
cmd.arg(&source_file)
.current_dir(root)
.env("ELEVENTY_ROOT", root)
.env("ELEVENTY_SOURCE", "cli")
.env("ELEVENTY_RUN_MODE", run_mode.as_str())
.env("ELEVENTY_VERSION", ELEVENTY_VERSION)
.stdin(Stdio::piped());
if let Some(why) = &walk {
cmd.env("BRRRTY_JS_EXPORTS", "walk");
cmd.env("BRRRTY_JS_WALK_WHY", why);
} else {
cmd.env_remove("BRRRTY_JS_WALK_WHY");
}
if replay.is_some() {
cmd.env("BRRRTY_ROLE", "replay");
}
let (mut child, frames, stderr, answers) = spawn(cmd).map_err(cannot)?;
let pid = child.id();
live(pid, true);
let (tx, replies) = mpsc::channel();
let decode = Arc::new(AtomicBool::new(true));
let decoding = decode.clone();
let stdin = child.stdin.take();
let mux = Arc::new(Mux {
child: Mutex::new(child),
stdin: Mutex::new(stdin),
answers: Mutex::new(answers),
routes: Mutex::new(HashMap::new()),
notes: Mutex::new(Box::new(|s| eprintln!("{s}"))),
note_times: Mutex::new((FIRST_NOTE, NEXT_NOTE)),
});
let routing = mux.clone();
std::thread::Builder::new()
.name("brrrty-node-replies".into())
.stack_size(REPLY_STACK)
.spawn(move || read_frames(frames, tx, decoding, &routing))
.map_err(|e| {
let mut child = locked(&mux.child);
let _ = child.kill();
let _ = child.wait();
WorkerError(format!("cannot read Node's replies: {e}"))
})?;
let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
let tail = stderr_tail.clone();
let stderr_thread = std::thread::spawn(move || drain_stderr(stderr, tail));
Ok(Worker {
_source_dir: source_dir,
mux,
pid,
answers_feed: None,
asked: Vec::new(),
filters: None,
replies,
stderr_tail,
stderr_thread: Some(stderr_thread),
root: root.to_path_buf(),
next_id: 0,
next_page: 0,
failed: None,
last_loaded: HashMap::new(),
earlier: None,
fixed: std::collections::HashSet::new(),
last_fixed: false,
last_seq: 0,
table: Table::default(),
node: node.clone(),
run_mode,
decode,
load_log: Vec::new(),
global_end: 0,
call_log: Vec::new(),
dropped: false,
calls_begun: false,
load_handles: 0,
replays: None,
order_check,
slowest: Duration::ZERO,
deadline: None,
last_template: None,
next_ticket: 0,
stats: Stats {
started: Some(Instant::now()),
..Stats::default()
},
frozen: false,
walk,
walks: None,
})
}
fn open_request(
&mut self,
data: &Value,
traps: &[(String, String)],
defaults: &[String],
) -> Result<(PageId, Request<'static>), String> {
self.next_page += 1;
let page = self.next_page;
let mut added = Added::default();
let mut text = String::with_capacity(1024);
let _ = write!(text, "{{\"op\":\"pageOpen\",\"page\":{page},\"data\":");
self.table.page_data(data, false, &mut text, &mut added)?;
text.push_str(",\"traps\":");
pairs(&mut text, traps);
text.push_str(",\"defaults\":");
crate::wire::strings(&mut text, defaults);
text.push('}');
Ok((
PageId(page),
Request {
added,
..Request::new("pageOpen", text)
},
))
}
pub fn set_notes(
&mut self,
notes: impl Fn(&str) + Send + 'static,
first: Duration,
next: Duration,
) {
*locked(&self.mux.notes) = Box::new(notes);
*locked(&self.mux.note_times) = (first, next);
}
pub fn exports_frozen(&self) -> Result<(), String> {
if self.frozen {
Ok(())
} else {
Err(self.walks.clone().unwrap_or_default())
}
}
fn trace(&self, at: &str) {
let s = &self.stats;
eprintln!(
"note: {at}, {:.3} s after Node started: {} requests ({:.1} MB) and {} definitions ({:.1} MB) sent, {:.1} MB of replies, {:.3} s waiting on Node",
s.started.map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0),
s.requests,
s.sent as f64 / 1e6,
s.definitions,
s.defined as f64 / 1e6,
s.received as f64 / 1e6,
s.waited.as_secs_f64(),
);
}
pub fn pid(&self) -> u32 {
self.pid
}
pub fn root(&self) -> &Path {
&self.root
}
fn request(&mut self, req: Request<'_>, what: &str) -> JsResult<Decoded> {
let filters = self.filters.clone();
self.request_with(
req,
what,
&mut |name: &str, args: &[Value]| match &filters {
Some(f) => f(name, args),
None => Err(format!(
"calls `this.{name}` where Brrrty has no filters to run it"
)),
},
)
}
fn request_with(
&mut self,
req: Request<'_>,
what: &str,
filters: &mut FilterCall<'_>,
) -> JsResult<Decoded> {
self.requests(vec![req], what, filters)
.pop()
.unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
}
fn requests(
&mut self,
reqs: Vec<Request<'_>>,
what: &str,
filters: &mut FilterCall<'_>,
) -> Vec<JsResult<Decoded>> {
let mut out = Vec::with_capacity(reqs.len());
let mut reqs = reqs.into_iter().peekable();
while reqs.peek().is_some() {
let mut group = Vec::new();
let mut ahead = 0;
while let Some(next) = reqs.peek() {
if !group.is_empty() && ahead + next.text.len() + 48 > PIPE_SAFE {
break;
}
if !group.is_empty() {
ahead += next.text.len() + 48;
}
group.extend(reqs.next());
}
let ticket = match self.send(group, what, Shape::List, None) {
Ok(t) => t,
Err(f) => {
out.push(JsResult::Failed(f));
return out;
}
};
let done = ticket.collect(filters);
match self.settle(done) {
Finished::Results { results, .. } => {
let stop = results.iter().any(|r| !matches!(r, JsResult::Ok(_)));
out.extend(results);
if stop {
return out;
}
}
Finished::Again => {
out.push(JsResult::Failed(
self.fail("the worker lost the values a request referred to"),
));
return out;
}
}
}
out
}
fn fits(reqs: &[Request<'_>]) -> bool {
reqs.iter()
.skip(1)
.map(|r| r.text.len() + 48)
.sum::<usize>()
<= PIPE_SAFE
}
fn send(
&mut self,
reqs: Vec<Request<'_>>,
what: &str,
shape: Shape,
page: Option<PageId>,
) -> Result<Ticket, RuntimeFailure> {
if let Some(f) = &self.failed {
return Err(f.clone());
}
let mut handed = false;
if self.calls_begun && self.replays.is_none() && reqs.iter().any(|r| logged(r.op)) {
self.start_replays();
handed = true;
}
for req in &reqs {
for (line, dynamic) in &req.added.lines {
self.stats.definitions += 1;
self.stats.defined += line.len() as u64;
self.write_line(line)?;
if !dynamic
&& !handed
&& let Some(replays) = &self.replays
{
for r in replays {
r.line(line.clone());
}
}
}
}
let (tx, rx) = mpsc::channel();
self.next_ticket += 1;
let ticket = self.next_ticket;
let mut lines = String::new();
let mut sent = Vec::with_capacity(reqs.len());
{
let mut routes = locked(&self.mux.routes);
for req in reqs {
self.next_id += 1;
let id = self.next_id;
let _ = write!(lines, "{{\"id\":{id},\"t\":{ticket},");
lines.push_str(req.text.strip_prefix('{').unwrap_or(&req.text));
lines.push('\n');
if !req.one_way {
routes.insert(id, tx.clone());
}
sent.push(Sent {
id,
op: req.op,
handle: req.handle,
path: req.path.map(|p| p.to_string_lossy().into_owned()),
one_way: req.one_way,
made: req.added.made,
dynamic: req.added.dynamic,
text: req.text,
});
}
}
self.stats.sent += lines.len() as u64;
let written = locked(&self.mux.stdin)
.as_mut()
.map(|s| s.write_all(lines.as_bytes()).and_then(|_| s.flush()));
if !matches!(written, Some(Ok(()))) {
return Err(self.fail("Node stopped reading requests"));
}
Ok(Ticket {
mux: self.mux.clone(),
rx,
sent,
what: what.to_string(),
shape,
page,
deadline: self.deadline,
})
}
fn settle(&mut self, done: Done) -> Finished {
let Done {
sent,
frames,
asked,
failure,
what,
shape,
page,
waited,
} = done;
self.slowest = self.slowest.max(waited);
self.stats.waited += waited;
let mut results: Vec<JsResult<Decoded>> = Vec::with_capacity(frames.len());
let mut unchecked = false;
let mut last_at = (self.last_seq, 0u32);
let mut frames = frames.into_iter();
let mut asked = asked.into_iter();
for req in sent {
let mut frame = if req.one_way {
None
} else {
match frames.next() {
Some(f) => Some(f),
None => break,
}
};
let answers = if req.one_way {
Vec::new()
} else {
asked.next().unwrap_or_default()
};
if let Some(f) = &frame {
self.stats.requests += 1;
self.stats.received += f.body.len() as u64;
if f.head.get("stale").is_some() {
if results.iter().all(|r| matches!(r, JsResult::Ok(_))) {
self.table.forget();
return Finished::Again;
}
break;
}
if f.head.get("after").is_some() {
break;
}
}
if req.op == "templateLoad" {
self.last_template = frame
.as_ref()
.and_then(|f| f.head.get("template"))
.and_then(Json::as_u64);
}
if req.op == "load" {
self.last_fixed = frame
.as_ref()
.is_some_and(|f| f.head.get("fixed").is_some());
}
let body = frame
.as_mut()
.map(|f| std::mem::take(&mut f.body))
.unwrap_or_default();
let clock = frame.as_mut().and_then(|f| f.clock.take());
if logged(req.op) && !self.calls_begun {
self.load_log.push(LoadRecord {
text: req.text.into_boxed_str(),
kind: match req.op {
"load" => LoadKind::Data,
"templateLoad" => LoadKind::Template,
_ => LoadKind::Other,
},
path: req.path.unwrap_or_default(),
body,
clock,
});
} else if logged(req.op) && !self.order_check {
let dropped = frame
.as_ref()
.is_some_and(|f| f.head.get("dropShared").is_some());
self.dropped |= dropped;
unchecked |= dropped;
} else if logged(req.op) {
let (unit, label) = match brrrty_js::functions::unit() {
Some(u) => u,
None => (u64::MAX - self.call_log.len() as u64, Arc::from("")),
};
let dropped = frame
.as_ref()
.is_some_and(|f| f.head.get("dropShared").is_some());
self.dropped |= dropped;
let at = match &frame {
Some(f) => {
self.last_seq = self.last_seq.max(f.seq);
last_at = (f.seq, 0);
last_at
}
None => {
last_at.1 += 1;
last_at
}
};
self.call_log.push(Record {
at,
unit,
label,
op: req.op,
handle: req.handle,
text: req.text.into_boxed_str(),
body,
clock,
made: frame.as_ref().is_some_and(|f| f.made),
names_made: req.made || req.handle.is_some_and(|h| self.table.made_by_call(h)),
dynamic: req.dynamic,
answers,
one_way: req.one_way,
unchecked,
});
unchecked |= dropped;
}
let Some(frame) = frame else {
continue;
};
let r = self.interpret(frame, &what);
let failed = matches!(r, JsResult::Failed(_));
results.push(r);
if failed {
return Finished::Results {
results: vec![results.pop().expect("just pushed")],
page: None,
};
}
}
if let Some(why) = failure {
return Finished::Results {
results: vec![JsResult::Failed(self.fail(&why))],
page: None,
};
}
self.shape(shape, page, results)
}
fn shaped(&mut self, done: Done, results: Vec<JsResult<Decoded>>) -> Finished {
self.shape(done.shape, done.page, results)
}
fn shape(
&mut self,
shape: Shape,
page: Option<PageId>,
mut results: Vec<JsResult<Decoded>>,
) -> Finished {
let bad = results.iter().position(|r| !matches!(r, JsResult::Ok(_)));
match shape {
Shape::List => {
if let Some(bad) = bad {
results.truncate(bad + 1);
}
Finished::Results { results, page }
}
Shape::Once => {
let result = match bad {
Some(bad) => results.swap_remove(bad),
None if results.len() == 2 => results.swap_remove(1),
None => JsResult::Failed(self.fail("a page's call gave no reply")),
};
Finished::Results {
results: vec![result],
page,
}
}
Shape::OpenWithVars => match bad {
Some(bad) => {
if bad > 0
&& let Some(page) = page
{
self.page_close(page);
}
Finished::Results {
results: vec![results.swap_remove(bad)],
page: None,
}
}
None => Finished::Results { results, page },
},
}
}
fn op_requests(&mut self, op: Op<'_>) -> Result<Planned, String> {
Ok(match op {
Op::Call {
f,
this,
args,
settle,
} => {
let mut added = Added::default();
let mut text = String::with_capacity(128);
let _ = write!(
text,
"{{\"op\":\"call\",\"handle\":{},\"await\":{}",
f.0,
settle == Settle::Await
);
match this {
This::Value(v) => {
text.push_str(",\"this\":");
self.table.argument(v, false, &mut text, &mut added)?;
}
This::Guarded(v, keys) => {
text.push_str(",\"this\":");
self.table.argument(v, false, &mut text, &mut added)?;
text.push_str(",\"guard\":[");
for (i, (k, what)) in keys.iter().enumerate() {
if i > 0 {
text.push(',');
}
text.push('[');
crate::wire::string(&mut text, k);
text.push(',');
crate::wire::string(&mut text, what);
text.push(']');
}
text.push(']');
}
This::Opaque(what) => {
text.push_str(",\"opaque\":");
crate::wire::string(&mut text, what);
}
}
text.push_str(",\"args\":[");
for (i, a) in args.iter().enumerate() {
if i > 0 {
text.push(',');
}
self.table.argument(a, true, &mut text, &mut added)?;
}
text.push(']');
if let Some((page, number)) = brrrty_js::functions::own_page() {
text.push_str(",\"own\":");
self.table.argument(&page, false, &mut text, &mut added)?;
if let Some(n) = number {
text.push_str(",\"ownAt\":");
crate::wire::number(&mut text, n);
}
}
text.push('}');
let req = Request {
added,
handle: Some(f.0),
..Request::new("call", text)
};
(vec![req], Shape::List, None, "a data function")
}
Op::PageOnce {
data,
traps,
defaults,
f,
} => {
let (page, open) = self.open_request(data, traps, defaults)?;
(
vec![open, call_request(page, f, None), close_request(page)],
Shape::Once,
None,
"a permalink function",
)
}
Op::PageOpenWithVars {
data,
traps,
defaults,
functions,
keys,
} => {
let (page, open) = self.open_request(data, traps, defaults)?;
let mut reqs = vec![open];
reqs.extend(functions.iter().map(|f| vars_request(page, *f, keys)));
(
reqs,
Shape::OpenWithVars,
Some(page),
"a computed data function",
)
}
Op::PageRun { page, steps } => {
let mut reqs = Vec::with_capacity(steps.len());
for step in steps {
match step {
PageStep::Call(f, set) => reqs.push(call_request(page, *f, *set)),
PageStep::Set(key, value) => {
let mut added = Added::default();
let mut text = String::with_capacity(128);
let _ =
write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
crate::wire::string(&mut text, key);
text.push_str(",\"value\":");
self.table.argument(value, false, &mut text, &mut added)?;
text.push('}');
reqs.push(Request {
added,
..Request::new("pageSet", text)
});
}
}
}
(reqs, Shape::List, None, "a computed data function")
}
Op::Render {
template,
data,
first,
traps,
} => {
let mut added = Added::default();
let mut text = String::with_capacity(1024);
let _ = write!(
text,
"{{\"op\":\"render\",\"template\":{},\"data\":",
template.0
);
self.table.page_data(data, true, &mut text, &mut added)?;
text.push_str(",\"traps\":");
pairs(&mut text, traps);
if let Some(first) = first {
text.push_str(",\"first\":");
self.table.argument(first, true, &mut text, &mut added)?;
}
text.push('}');
let req = Request {
added,
..Request::new("render", text)
};
(vec![req], Shape::List, None, "a JavaScript template")
}
})
}
fn one(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> JsResult<Decoded> {
self.now(op, filters)
.pop()
.unwrap_or_else(|| JsResult::Failed(self.fail("a request with no reply")))
}
fn now(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Vec<JsResult<Decoded>> {
for _ in 0..AGAIN {
let finished = match self.begin(op, filters) {
Begun::Done(f) => f,
Begun::Sent(pending) => {
let waited = pending.wait(filters);
self.finish(waited)
}
};
if let Finished::Results { results, .. } = finished {
return results;
}
}
vec![JsResult::Failed(self.fail(
"the worker kept losing the values a request referred to",
))]
}
pub(crate) fn write_line(&mut self, line: &str) -> Result<(), RuntimeFailure> {
if let Some(f) = &self.failed {
return Err(f.clone());
}
let mut bytes = Vec::with_capacity(line.len() + 1);
bytes.extend_from_slice(line.as_bytes());
bytes.push(b'\n');
let sent = locked(&self.mux.stdin)
.as_mut()
.map(|s| s.write_all(&bytes).and_then(|_| s.flush()));
if !matches!(sent, Some(Ok(()))) {
return Err(self.fail("Node stopped reading requests"));
}
Ok(())
}
pub(crate) fn take_stdin(&mut self) -> Option<ChildStdin> {
locked(&self.mux.stdin).take()
}
pub(crate) fn line_for(&mut self, text: &str, feed: Option<&str>) -> (u64, String) {
self.next_id += 1;
let id = self.next_id;
let mut line = String::with_capacity(text.len() + 32);
let _ = write!(line, "{{\"id\":{id},");
if let Some(feed) = feed {
line.push_str("\"feed\":");
line.push_str(feed);
line.push(',');
}
line.push_str(text.strip_prefix('{').unwrap_or(text));
(id, line)
}
pub(crate) fn exchange(
&mut self,
text: &str,
feed: Option<&str>,
what: &str,
) -> Result<Frame, RuntimeFailure> {
self.exchange_with(text, feed, what, &mut |name: &str, _: &[Value]| {
Err(format!(
"calls `this.{name}` where Brrrty has no filters to run it"
))
})
}
pub(crate) fn answer(
&mut self,
frame: &Frame,
filters: &mut FilterCall<'_>,
) -> Result<(), String> {
let reply: Box<str> = match self.answers_feed.as_mut() {
Some(feed) => {
let reply: Box<str> = match feed.pop_front() {
Some((q, a)) if q == frame.body => a,
_ => r#"{"refused":"asks for a filter the first run didn't ask for at this point"}"#
.into(),
};
self.mux.send_answer(&reply)?;
reply
}
None => self.mux.answer(frame, filters)?,
};
self.asked.push((frame.body.clone(), reply));
Ok(())
}
pub(crate) fn exchange_with(
&mut self,
text: &str,
feed: Option<&str>,
what: &str,
filters: &mut FilterCall<'_>,
) -> Result<Frame, RuntimeFailure> {
let (id, line) = self.line_for(text, feed);
self.write_line(&line)?;
let mut wait = self.wait();
let frame = loop {
match self.next_frame(what, &mut wait) {
Ok(f) if f.question => {
if let Err(why) = self.answer(&f, filters) {
return Err(self.fail(&why));
}
}
Ok(f) => break f,
Err(f) => return Err(f),
}
};
let took = wait.start.elapsed();
self.slowest = self.slowest.max(took);
self.stats.requests += 1;
self.stats.sent += line.len() as u64;
self.stats.received += frame.body.len() as u64;
self.stats.waited += took;
if frame.id != id {
let head = frame.head.clone();
return Err(self.fail(&format!("a reply out of order: {head}")));
}
Ok(frame)
}
pub(crate) fn wait(&self) -> Wait {
self.mux.wait()
}
pub(crate) fn next_frame(
&mut self,
what: &str,
wait: &mut Wait,
) -> Result<Frame, RuntimeFailure> {
if let Some(f) = &self.failed {
return Err(f.clone());
}
let mux = self.mux.clone();
mux.next(&self.replies, what, wait, self.deadline)
.map_err(|why| self.fail(&why))
}
fn interpret(&mut self, frame: Frame, what: &str) -> JsResult<Decoded> {
let Frame {
head: reply, ok, ..
} = frame;
if reply.get("changedArgument").is_some() {
return JsResult::Failed(self.fail(&format!(
"{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"
)));
}
if let Some(p) = reply.get("protocol") {
return JsResult::Failed(self.fail(&format!("the worker refused a request: {p}")));
}
if let Some(why) = reply.get("again") {
walk_roots().sent_back(&self.root, why.as_str().unwrap_or(""));
let mut f = self.fail(&format!(
"the JavaScript worker has to check the data files' values after every call ({})",
why.as_str().unwrap_or("")
));
f.again = true;
self.failed = Some(f.clone());
return JsResult::Failed(f);
}
if let Some(t) = reply.get("thrown") {
return JsResult::Thrown(js_error(t, &self.root));
}
if let Some(m) = reply.get("invalid") {
return JsResult::Thrown(JsError {
message: m.as_str().unwrap_or("").to_string(),
invalid: true,
..JsError::default()
});
}
if reply.get("dropShared").is_some() {
self.table.forget();
}
if let Some(r) = reply.get("refused") {
return JsResult::Refused(Refusal {
why: r.as_str().unwrap_or("").to_string(),
impure: reply.get("impure").and_then(Json::as_bool) == Some(true),
});
}
let earlier = self.earlier.take();
if reply.get("same").is_some() {
return match earlier {
Some(d) => JsResult::Ok(d),
None => JsResult::Failed(self.fail("a reply that repeats a value never sent")),
};
}
match ok {
Some(Ok(d)) => JsResult::Ok(d),
Some(Err(e)) => JsResult::Failed(self.fail(&format!("a value Brrrty can't read: {e}"))),
None => JsResult::Failed(self.fail(&format!("a reply with no value: {reply}"))),
}
}
fn start_replays(&mut self) {
if !self.order_check {
return;
}
let loads = Arc::new(crate::replay::Loads {
node: self.node.clone(),
root: self.root.clone(),
run_mode: self.run_mode,
loads: std::mem::take(&mut self.load_log),
global_end: self.global_end,
load_handles: self.load_handles,
walk: self.walk.clone(),
took: self.stats.started.map(|t| t.elapsed()).unwrap_or_default(),
});
let replays = [
crate::replay::Handle::start(loads.clone(), true),
crate::replay::Handle::start(loads, false),
];
for (line, dynamic) in &self.table.lines {
if !dynamic {
for r in &replays {
r.line(line.clone());
}
}
}
self.replays = Some(replays);
}
pub(crate) fn fail(&mut self, why: &str) -> RuntimeFailure {
drop(locked(&self.mux.stdin).take());
let deadline = Instant::now() + Duration::from_secs(2);
let status = loop {
let mut child = locked(&self.mux.child);
match child.try_wait() {
Ok(Some(s)) => break Some(s),
Ok(None) if Instant::now() < deadline => {
drop(child);
std::thread::sleep(Duration::from_millis(10))
}
_ => {
let _ = child.kill();
break child.wait().ok();
}
}
};
self.stop_group();
self.finish_stderr();
let message = match status {
Some(s) => match (s.code(), signal_of(&s)) {
(Some(code), _) => format!("Node exited with status {code} ({why})"),
(None, Some(sig)) => format!("Node was killed by signal {sig} ({why})"),
_ => why.to_string(),
},
None => why.to_string(),
};
let stopped = STOPPING.load(std::sync::atomic::Ordering::SeqCst);
let message = if stopped {
"Brrrty was stopped, and stopped Node with it".to_string()
} else {
message
};
let failure = RuntimeFailure {
stopped,
again: false,
message,
stderr_tail: self
.stderr_tail
.lock()
.map(|t| t.iter().cloned().collect())
.unwrap_or_default(),
};
self.failed = Some(failure.clone());
failure
}
pub(crate) fn stop(&mut self) {
{
let mut child = locked(&self.mux.child);
let _ = child.kill();
let _ = child.wait();
}
self.stop_group();
if self.failed.is_none() {
self.failed = Some(RuntimeFailure {
message: "the replay check stopped its Node".into(),
stderr_tail: Vec::new(),
stopped: false,
again: false,
});
}
}
fn stop_group(&mut self) {
#[cfg(unix)]
kill_group(self.pid);
live(self.pid, false);
}
fn finish_stderr(&mut self) {
if let Some(t) = self.stderr_thread.take() {
let deadline = Instant::now() + STDERR_GRACE;
while !t.is_finished() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
if t.is_finished() {
let _ = t.join();
}
}
}
fn shown(&self, file: &Path) -> String {
file.strip_prefix(&self.root)
.unwrap_or(file)
.display()
.to_string()
}
}
fn no_filters() -> impl FnMut(&str, &[Value]) -> Result<Value, String> {
|name: &str, _: &[Value]| {
Err(format!(
"calls `this.{name}` where Brrrty has no filters to run it"
))
}
}
fn close_request(page: PageId) -> Request<'static> {
let text = op_text("pageClose", |t| {
let _ = write!(t, ",\"page\":{}", page.0);
});
Request {
one_way: true,
..Request::new("pageClose", text)
}
}
fn call_request(page: PageId, f: FnHandle, set: Option<&str>) -> Request<'static> {
let text = op_text("pageCall", |t| {
let _ = write!(t, ",\"page\":{},\"handle\":{},\"set\":", page.0, f.0);
match set {
Some(key) => crate::wire::string(t, key),
None => t.push_str("null"),
}
});
Request {
handle: Some(f.0),
..Request::new("pageCall", text)
}
}
fn vars_request(page: PageId, f: FnHandle, keys: &[String]) -> Request<'static> {
let text = op_text("pageVars", |t| {
let _ = write!(t, ",\"page\":{},\"handle\":{},\"keys\":", page.0, f.0);
crate::wire::strings(t, keys);
});
Request {
handle: Some(f.0),
..Request::new("pageVars", text)
}
}
fn op_text(op: &str, rest: impl FnOnce(&mut String)) -> String {
let mut t = String::with_capacity(96);
let _ = write!(t, "{{\"op\":\"{op}\"");
rest(&mut t);
t.push('}');
t
}
fn pairs(out: &mut String, traps: &[(String, String)]) {
out.push('[');
for (i, (k, why)) in traps.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push('[');
crate::wire::string(out, k);
out.push(',');
crate::wire::string(out, why);
out.push(']');
}
out.push(']');
}
fn unit(r: JsResult<Decoded>) -> JsResult<()> {
match r {
JsResult::Ok(_) => JsResult::Ok(()),
JsResult::Thrown(e) => JsResult::Thrown(e),
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
}
}
impl Worker {
fn load_template_as(
&mut self,
file: &Path,
layout: bool,
custom: Option<(&str, &str)>,
) -> JsResult<LoadedTemplate> {
let what = self.shown(file);
let text = op_text("templateLoad", |t| {
t.push_str(",\"path\":");
crate::wire::string(t, &file.to_string_lossy());
let _ = write!(t, ",\"layout\":{layout}");
if let Some((ext, content)) = custom {
t.push_str(",\"custom\":{\"ext\":");
crate::wire::string(t, ext);
t.push_str(",\"content\":");
crate::wire::string(t, content);
t.push('}');
}
});
self.last_template = None;
let r = self.request(
Request {
path: Some(file),
..Request::new("templateLoad", text)
},
&what,
);
match r {
JsResult::Ok(data) => match self.last_template {
Some(id) => JsResult::Ok(LoadedTemplate {
id: TemplateId(id),
data,
}),
None => JsResult::Failed(self.fail("templateLoad gave no template id")),
},
JsResult::Thrown(e) => JsResult::Thrown(e),
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
}
}
}
impl JsRuntime for Worker {
fn set_argument(&mut self, arg: &Value) -> JsResult<()> {
let text = op_text("setArg", |t| {
let _ = write!(t, ",\"value\":{}", encode(arg));
});
unit(self.request(Request::new("setArg", text), "the data argument"))
}
fn load(&mut self, file: &Path, call: bool) -> JsResult<Decoded> {
let what = self.shown(file);
let key = (call, file.to_path_buf());
self.earlier = self.last_loaded.get(&key).cloned();
if self.fixed.contains(&key)
&& let Some(d) = self.earlier.take()
{
return JsResult::Ok(d);
}
let text = op_text("load", |t| {
t.push_str(",\"path\":");
crate::wire::string(t, &file.to_string_lossy());
let _ = write!(t, ",\"call\":{call}");
});
let r = self.request(
Request {
path: Some(file),
..Request::new("load", text)
},
&what,
);
if let JsResult::Ok(d) = &r {
if self.last_fixed {
self.fixed.insert(key.clone());
}
self.last_loaded.insert(key, d.clone());
}
r
}
fn load_config(&mut self, file: &Path) -> JsResult<Decoded> {
let what = self.shown(file);
let text = op_text("configLoad", |t| {
t.push_str(",\"path\":");
crate::wire::string(t, &file.to_string_lossy());
});
self.earlier = None;
self.request(
Request {
path: Some(file),
..Request::new("configLoad", text)
},
&what,
)
}
fn call(
&mut self,
f: FnHandle,
this: This<'_>,
args: &[Value],
settle: Settle,
) -> JsResult<Decoded> {
let op = Op::Call {
f,
this,
args,
settle,
};
self.one(op, &mut no_filters())
}
fn begin(&mut self, op: Op<'_>, filters: &mut FilterCall<'_>) -> Begun {
let (reqs, shape, page, what) = match self.op_requests(op) {
Ok(r) => r,
Err(why) => {
return Begun::Done(Finished::Results {
results: vec![JsResult::Refused(Refusal::new(why))],
page: None,
});
}
};
if !Worker::fits(&reqs) {
let results = self.requests(reqs, what, filters);
let done = Done {
sent: Vec::new(),
frames: Vec::new(),
asked: Vec::new(),
failure: None,
what: what.to_string(),
shape,
page,
waited: Duration::ZERO,
};
return Begun::Done(self.shaped(done, results));
}
match self.send(reqs, what, shape, page) {
Ok(ticket) => Begun::Sent(Box::new(ticket)),
Err(f) => Begun::Done(Finished::Results {
results: vec![JsResult::Failed(f)],
page: None,
}),
}
}
fn finish(&mut self, waited: Waited) -> Finished {
match waited.0.downcast::<Done>() {
Ok(done) => self.settle(*done),
Err(_) => Finished::Results {
results: vec![JsResult::Failed(
self.fail("replies that aren't this worker's"),
)],
page: None,
},
}
}
fn page_open(
&mut self,
data: &Value,
traps: &[(String, String)],
defaults: &[String],
) -> JsResult<PageId> {
let (page, open) = match self.open_request(data, traps, defaults) {
Ok(r) => r,
Err(why) => return JsResult::Refused(Refusal::new(why)),
};
match self.request(open, "a page's data") {
JsResult::Ok(_) => JsResult::Ok(PageId(page.0)),
JsResult::Thrown(e) => JsResult::Thrown(e),
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
}
}
fn page_vars(&mut self, page: PageId, f: FnHandle, keys: &[String]) -> JsResult<Vec<String>> {
let r = self.request(vars_request(page, f, keys), "a computed data function");
match r {
JsResult::Ok(d) => match strings(&d.value) {
Some(list) => JsResult::Ok(list),
None => JsResult::Failed(self.fail(&format!("pageVars gave {:?}", d.value))),
},
JsResult::Thrown(e) => JsResult::Thrown(e),
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
}
}
fn page_call(&mut self, page: PageId, f: FnHandle, set: Option<&str>) -> JsResult<Decoded> {
self.request(call_request(page, f, set), "a computed data function")
}
fn page_set(&mut self, page: PageId, key: &str, value: &Value) -> JsResult<()> {
let mut added = Added::default();
let mut text = String::with_capacity(128);
let _ = write!(text, "{{\"op\":\"pageSet\",\"page\":{},\"key\":", page.0);
crate::wire::string(&mut text, key);
text.push_str(",\"value\":");
if let Err(why) = self.table.argument(value, false, &mut text, &mut added) {
return JsResult::Refused(Refusal::new(why));
}
text.push('}');
unit(self.request(
Request {
added,
..Request::new("pageSet", text)
},
"a page's data",
))
}
fn page_close(&mut self, page: PageId) {
let _ = self.requests(
vec![close_request(page)],
"a page's data",
&mut no_filters(),
);
}
fn page_once(
&mut self,
data: &Value,
traps: &[(String, String)],
defaults: &[String],
f: FnHandle,
) -> JsResult<Decoded> {
let op = Op::PageOnce {
data,
traps,
defaults,
f,
};
self.one(op, &mut no_filters())
}
fn page_run(&mut self, page: PageId, steps: &[PageStep<'_>]) -> Vec<JsResult<Decoded>> {
let filters = self.filters.clone();
self.now(
Op::PageRun { page, steps },
&mut |name: &str, args: &[Value]| match &filters {
Some(f) => f(name, args),
None => Err(format!(
"calls `this.{name}` where Brrrty has no filters to run it"
)),
},
)
}
fn loads_changed(&mut self) -> JsResult<Vec<(PathBuf, Decoded)>> {
self.global_end = self.load_log.len();
let d = match self.request(
Request::new("loadsChanged", op_text("loadsChanged", |_| {})),
"the data files",
) {
JsResult::Ok(d) => d,
JsResult::Thrown(e) => return JsResult::Thrown(e),
JsResult::Refused(r) => return JsResult::Refused(r),
JsResult::Failed(f) => return JsResult::Failed(f),
};
let Value::Array(items) = &d.value else {
return JsResult::Failed(self.fail("loadsChanged gave something other than a list"));
};
let mut out = Vec::new();
for (i, item) in items.iter().enumerate() {
let (Value::String(p), value) = (item.get("path"), item.get("value")) else {
return JsResult::Failed(self.fail("loadsChanged gave an item without a path"));
};
let under = |at: &[PathPart]| -> Option<Vec<PathPart>> {
match at {
[PathPart::Index(j), PathPart::Key(k), rest @ ..]
if *j == i && k == "value" =>
{
Some(rest.to_vec())
}
_ => None,
}
};
out.push((
PathBuf::from(&*p),
Decoded {
value,
functions: d
.functions
.iter()
.filter_map(|(at, h)| under(at).map(|a| (a, *h)))
.collect(),
refused: d
.refused
.iter()
.filter_map(|(at, w)| under(at).map(|a| (a, w.clone())))
.collect(),
},
));
}
JsResult::Ok(out)
}
fn begin_calls(&mut self) -> JsResult<()> {
let frame = match self.exchange(&op_text("callsBegin", |_| {}), None, "the data files") {
Ok(f) => f,
Err(f) => return JsResult::Failed(f),
};
let head = &frame.head;
self.load_handles = head.get("handles").and_then(Json::as_u64).unwrap_or(0);
self.frozen = head.get("exports").and_then(Json::as_str) == Some("frozen");
self.walks = head.get("walks").and_then(Json::as_str).map(str::to_string);
self.table.load_handles = Some(u32::try_from(self.load_handles).unwrap_or(u32::MAX));
self.calls_begun = true;
if trace() {
self.trace("the data files loaded");
match self.exports_frozen() {
Ok(()) => {
eprintln!("note: the data files' values are frozen while pages call functions")
}
Err(why) => {
eprintln!("note: the data files' values are walked after every call ({why})")
}
}
}
let changed: Vec<&str> = head
.get("changed")
.and_then(Json::as_array)
.map(|a| a.iter().filter_map(Json::as_str).collect())
.unwrap_or_default();
if !changed.is_empty() {
return JsResult::Refused(Refusal {
why: format!(
"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",
if changed.len() == 1 { "file" } else { "files" },
changed.join(", ")
),
impure: true,
});
}
if head.get("protos").and_then(Json::as_bool) == Some(true) {
return JsResult::Refused(Refusal {
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(),
impure: true,
});
}
if self.load_log.len() > self.global_end {
self.start_replays();
}
JsResult::Ok(())
}
fn set_filters(&mut self, filters: Filters) {
self.filters = Some(filters);
}
fn template_setup(&mut self, filters: &[String], node: &[(String, u32)]) -> JsResult<()> {
let text = op_text("templateSetup", |t| {
t.push_str(",\"filters\":");
crate::wire::strings(t, filters);
t.push_str(",\"node\":[");
for (i, (name, handle)) in node.iter().enumerate() {
if i > 0 {
t.push(',');
}
t.push('[');
crate::wire::string(t, name);
let _ = write!(t, ",{handle}]");
}
t.push(']');
});
unit(self.request(
Request::new("templateSetup", text),
"the JavaScript templates' setup",
))
}
fn load_template(&mut self, file: &Path, layout: bool) -> JsResult<LoadedTemplate> {
self.load_template_as(file, layout, None)
}
fn load_custom_template(
&mut self,
file: &Path,
ext: &str,
content: &str,
) -> JsResult<LoadedTemplate> {
self.load_template_as(file, false, Some((ext, content)))
}
fn render(
&mut self,
template: TemplateId,
data: &Value,
first: Option<&Value>,
traps: &[(String, String)],
filters: &mut FilterCall<'_>,
) -> JsResult<Decoded> {
let op = Op::Render {
template,
data,
first,
traps,
};
self.one(op, filters)
}
fn verify(&mut self) -> JsResult<()> {
match self.request(
Request::new("exportsFinal", op_text("exportsFinal", |_| {})),
"the data files' values",
) {
JsResult::Ok(_) => {}
other @ (JsResult::Refused(_) | JsResult::Failed(_)) => {
return match other {
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
_ => JsResult::Ok(()),
};
}
JsResult::Thrown(e) => return JsResult::Thrown(e),
}
if self.frozen {
walk_roots().froze(&self.root);
}
let Some(replays) = self.replays.take() else {
return JsResult::Ok(());
};
let calls = Arc::new(crate::replay::Calls {
records: {
let mut records = std::mem::take(&mut self.call_log);
records.sort_by_key(|r| r.at);
records
},
load_handles: self.load_handles,
slowest: self.slowest,
dynamic: std::mem::take(&mut self.table.dynamic),
lines: self.table.lines.clone(),
dropped: self.dropped,
});
if trace() {
self.trace("the pages' calls ended");
}
let checking = Instant::now();
let [a, b] = replays;
a.run(calls.clone());
b.run(calls);
let (a, b) = (a.finish(), b.finish());
if trace() {
eprintln!(
"note: the replay check took {:.3} s after the build's own calls",
checking.elapsed().as_secs_f64()
);
}
match a.and(b) {
Ok(()) => JsResult::Ok(()),
Err(crate::replay::Failure::Differs(why, handle)) => {
let named = handle
.and_then(|h| {
let text = op_text("describe", |t| {
let _ = write!(t, ",\"handle\":{h}");
});
self.exchange(&text, None, "a function's name").ok()
})
.and_then(|f| match f.value() {
Some(Value::String(s)) => Some(s.to_string()),
_ => None,
})
.unwrap_or_else(|| "a function from JavaScript data".to_string());
JsResult::Refused(Refusal {
why: why.replace("{fn}", &named),
impure: true,
})
}
Err(crate::replay::Failure::Runtime(f)) => JsResult::Failed(f),
Err(crate::replay::Failure::Again(why)) => {
walk_roots().sent_back(&self.root, &why);
let mut f = self.fail(&format!(
"the JavaScript worker has to check the data files' values after every call ({why})"
));
f.again = true;
self.failed = Some(f.clone());
JsResult::Failed(f)
}
}
}
fn reads(&mut self) -> JsResult<Vec<PathBuf>> {
match self.request(
Request::new("reads", op_text("reads", |_| {})),
"the list of files read",
) {
JsResult::Ok(d) => match strings(&d.value) {
Some(list) => JsResult::Ok(list.into_iter().map(PathBuf::from).collect()),
None => JsResult::Failed(self.fail(&format!("reads gave {:?}", d.value))),
},
JsResult::Thrown(e) => JsResult::Thrown(e),
JsResult::Refused(r) => JsResult::Refused(r),
JsResult::Failed(f) => JsResult::Failed(f),
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
if let Some(mut stdin) = locked(&self.mux.stdin).take() {
let _ = stdin.write_all(b"{\"op\":\"bye\"}\n");
}
let deadline = Instant::now() + Duration::from_secs(20);
loop {
let mut child = locked(&self.mux.child);
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if Instant::now() < deadline => {
drop(child);
std::thread::sleep(Duration::from_millis(5))
}
_ => {
let _ = child.kill();
let _ = child.wait();
break;
}
}
}
self.stop_group();
self.finish_stderr();
}
}
fn walk_roots() -> MutexGuard<'static, WalkMemo> {
static ROOTS: std::sync::LazyLock<Mutex<WalkMemo>> =
std::sync::LazyLock::new(|| Mutex::new(WalkMemo::default()));
ROOTS.lock().unwrap_or_else(|e| e.into_inner())
}
#[derive(Default)]
pub(crate) struct WalkMemo {
roots: HashMap<PathBuf, Walks>,
}
struct Walks {
why: String,
left: u32,
last: u32,
}
impl WalkMemo {
const MOST: u32 = 64;
pub(crate) fn sent_back(&mut self, root: &Path, why: &str) {
let w = self.roots.entry(root.to_path_buf()).or_insert(Walks {
why: String::new(),
left: 0,
last: 0,
});
if w.left > 0 {
return;
}
w.why = why.to_string();
w.last = (w.last * 2).clamp(1, Self::MOST);
w.left = w.last;
}
pub(crate) fn starting(&mut self, root: &Path) -> Option<String> {
let w = self.roots.get_mut(root)?;
if w.left == 0 {
return None;
}
w.left -= 1;
Some(w.why.clone())
}
pub(crate) fn froze(&mut self, root: &Path) {
self.roots.remove(root);
}
}
fn trace() -> bool {
static ON: std::sync::LazyLock<bool> =
std::sync::LazyLock::new(|| std::env::var_os("BRRRTY_JS_TRACE").is_some());
*ON
}
static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new());
static STOPPING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn live(pid: u32, running: bool) {
let mut l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
l.retain(|p| *p != pid);
if running {
l.push(pid);
}
}
pub fn stop_all() {
STOPPING.store(true, std::sync::atomic::Ordering::SeqCst);
let l = LIVE.lock().unwrap_or_else(|e| e.into_inner());
#[cfg(unix)]
for pid in l.iter() {
kill_group(*pid);
}
}
pub(crate) fn stop_pid(pid: u32) {
#[cfg(unix)]
kill_group(pid);
#[cfg(windows)]
{
let _ = Command::new("taskkill")
.args(["/PID", &pid.to_string(), "/T", "/F"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
#[cfg(not(any(unix, windows)))]
let _ = pid;
}
#[cfg(unix)]
fn kill_group(pid: u32) {
if let Ok(pid) = i32::try_from(pid) {
unsafe {
libc::killpg(pid, libc::SIGKILL);
}
}
}
#[cfg(unix)]
fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
use std::os::fd::AsRawFd;
use std::os::unix::process::CommandExt;
let (frames_r, frames_w) = std::io::pipe()?;
let frames_w = frames_w.try_clone()?;
let (answers_r, answers_w) = std::io::pipe()?;
let answers_r = answers_r.try_clone()?;
let (err_r, err_w) = std::io::pipe()?;
let fd = frames_w.as_raw_fd();
let answers_fd = answers_r.as_raw_fd();
cmd.stdout(err_w.try_clone()?)
.stderr(err_w)
.env("BRRRTY_FRAMES_FD", fd.to_string())
.env("BRRRTY_ANSWERS_FD", answers_fd.to_string())
.process_group(0);
unsafe {
cmd.pre_exec(move || {
if libc::fcntl(fd, libc::F_SETFD, 0) == -1
|| libc::fcntl(answers_fd, libc::F_SETFD, 0) == -1
{
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let child = cmd.spawn();
drop(cmd);
drop(frames_w);
drop(answers_r);
Ok((
child?,
Box::new(frames_r),
Box::new(err_r),
Some(Box::new(answers_w)),
))
}
type Spawned = (
Child,
Box<dyn Read + Send>,
Box<dyn Read + Send>,
Option<Box<dyn Write + Send>>,
);
#[cfg(not(unix))]
fn spawn(mut cmd: Command) -> std::io::Result<Spawned> {
let mut child = cmd
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env("BRRRTY_FRAMES_FD", "1")
.spawn()?;
let stdout = child.stdout.take().expect("piped stdout");
let stderr = child.stderr.take().expect("piped stderr");
Ok((child, Box::new(stdout), Box::new(stderr), None))
}
#[cfg(unix)]
fn signal_of(s: &std::process::ExitStatus) -> Option<i32> {
use std::os::unix::process::ExitStatusExt;
s.signal()
}
#[cfg(not(unix))]
fn signal_of(_: &std::process::ExitStatus) -> Option<i32> {
None
}
fn read_frames(stdout: impl Read, tx: mpsc::Sender<Reply>, decoding: Arc<AtomicBool>, mux: &Mux) {
read_frames_to(stdout, &tx, decoding, mux);
locked(&mux.routes).clear();
}
fn read_frames_to(
stdout: impl Read,
tx: &mpsc::Sender<Reply>,
decoding: Arc<AtomicBool>,
mux: &Mux,
) {
let mut r = BufReader::with_capacity(1 << 16, stdout);
let mut seq = 0u64;
loop {
seq += 1;
let mut header = Vec::new();
match r.read_until(b'\n', &mut header) {
Ok(0) => return,
Ok(_) => {}
Err(e) => {
let _ = tx.send(Err(format!("cannot read Node's output: {e}")));
return;
}
}
let fields = header
.strip_prefix(b"\x1eBRRRTY ")
.and_then(|h| h.strip_suffix(b"\n"))
.and_then(|h| std::str::from_utf8(h).ok())
.and_then(|h| {
let mut it = h.split(' ');
let kind = it.next()?;
let id = it.next()?.parse::<u64>().ok()?;
let clock = it.next()?.parse::<usize>().ok()?;
let body = it.next()?.parse::<usize>().ok()?;
(it.next().is_none() && matches!(kind, "r" | "f" | "q"))
.then_some((kind, id, clock, body))
});
let Some((kind, id, clock_len, body_len)) = fields else {
let shown = String::from_utf8_lossy(&header);
let _ = tx.send(Err(format!(
"something other than the worker wrote to its output: {:?}",
shown.chars().take(80).collect::<String>()
)));
return;
};
let mut read = |len: usize| -> Result<String, String> {
let mut bytes = vec![0; len];
r.read_exact(&mut bytes)
.map_err(|e| format!("a cut-off reply: {e}"))?;
String::from_utf8(bytes).map_err(|_| "a reply that isn't UTF-8".to_string())
};
let parts = read(clock_len).and_then(|c| read(body_len).map(|b| (c, b)));
let (clock, body) = match parts {
Ok(p) => p,
Err(e) => {
let _ = tx.send(Err(e));
return;
}
};
let decode_ok = decoding.load(std::sync::atomic::Ordering::Relaxed);
let parsed = parse_reply(body.as_bytes()).map(|mut head| {
let value = head.as_object_mut().and_then(|o| o.remove("ok"));
let ok = if decode_ok || kind == "q" {
value.as_ref().map(decode)
} else {
None
};
Frame {
question: kind == "q",
id,
head,
ok,
body: body.into_boxed_str(),
clock: (!clock.is_empty()).then(|| clock.into_boxed_str()),
made: kind == "f",
seq,
}
});
let route = match &parsed {
Ok(f) => locked(&mux.routes).get(&f.id).cloned(),
Err(_) => None,
};
let sent = match route {
Some(to) => to.send(parsed).is_ok(),
None => tx.send(parsed).is_ok(),
};
if !sent && locked(&mux.routes).is_empty() {
return;
}
}
}
fn strings(v: &Value) -> Option<Vec<String>> {
match v {
Value::Array(a) => a
.iter()
.map(|s| match s {
Value::String(s) => Some(s.to_string()),
_ => None,
})
.collect(),
_ => None,
}
}
pub(crate) fn parse_reply(body: &[u8]) -> Result<Json, String> {
let mut de = serde_json::Deserializer::from_slice(body);
de.disable_recursion_limit();
let v = serde::Deserialize::deserialize(&mut de)
.and_then(|v: Json| de.end().map(|()| v))
.map_err(|e| format!("a reply that isn't JSON: {e}"))?;
Ok(v)
}
fn drain_stderr(stderr: impl Read, tail: Arc<Mutex<VecDeque<String>>>) {
let mut r = BufReader::new(stderr);
let mut line = Vec::new();
let mut err = std::io::stderr();
loop {
line.clear();
match r.read_until(b'\n', &mut line) {
Ok(0) | Err(_) => return,
Ok(_) => {
let _ = err.write_all(&line);
if let Ok(mut t) = tail.lock() {
if t.len() == STDERR_TAIL {
t.pop_front();
}
t.push_back(String::from_utf8_lossy(&line).trim_end().to_string());
}
}
}
}
}
fn js_error(t: &Json, root: &Path) -> JsError {
let s = |k: &str| t.get(k).and_then(Json::as_str).unwrap_or("").to_string();
let stack = s("stack");
let place = crate::stack::syntax_header(&s("inspect"))
.or_else(|| crate::stack::pick(&crate::stack::frames(&stack), root));
JsError {
name: s("name"),
message: s("message"),
file: place.as_ref().map(|p| p.file.clone()),
line: place.as_ref().map(|p| p.line),
column: place.and_then(|p| p.column),
stack,
invalid: false,
}
}
pub fn encode(v: &Value) -> Json {
match v {
Value::Undefined => json!({"$u": 1}),
Value::Null => Json::Null,
Value::Bool(b) => Json::Bool(*b),
Value::Number(n) => {
if n.is_nan() {
json!({"$n": "NaN"})
} else if *n == f64::INFINITY {
json!({"$n": "Infinity"})
} else if *n == f64::NEG_INFINITY {
json!({"$n": "-Infinity"})
} else if *n == 0.0 && n.is_sign_negative() {
json!({"$n": "-0"})
} else {
serde_json::Number::from_f64(*n).map_or(Json::Null, Json::Number)
}
}
Value::String(s) => Json::String(s.to_string()),
Value::Array(a) => Json::Array(a.iter().map(encode).collect()),
Value::Object(o) => {
json!({"$o": o.iter().map(|(k, v)| json!([k, encode(v)])).collect::<Vec<_>>()})
}
Value::Date(d) => json!({"$d": d.timestamp_millis()}),
Value::Function(h) => json!({"$f": h.0}),
}
}
#[cfg(test)]
mod source {
#[test]
fn the_worker_source_keeps_the_files_line_numbers() {
let source = super::worker_source();
assert_eq!(source.lines().count(), super::WORKER_SOURCE.lines().count());
assert!(!source.lines().any(|l| l.trim_start().starts_with("//")));
}
}
#[cfg(test)]
mod source_size {
use super::*;
#[test]
fn a_worker_larger_than_one_argument_starts() {
let node = match crate::find::find_node(None) {
Ok(n) => n,
Err(e) => {
assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
eprintln!("skipped: {e}");
return;
}
};
tests_pad::PAD.with(|p| p.set(200 * 1024));
let t = tempfile::tempdir().unwrap();
let file = t.path().join("h.js");
std::fs::write(&file, "module.exports = { a() { return 'ok'; } };").unwrap();
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
}
}
#[cfg(test)]
mod walk_memo {
use super::WalkMemo;
use std::path::Path;
#[test]
fn a_folder_sent_back_walks_for_a_while_not_for_good() {
let root = Path::new("/site");
let mut m = WalkMemo::default();
assert_eq!(m.starting(root), None);
m.sent_back(root, "why");
m.sent_back(root, "another request");
assert_eq!(m.starting(root).as_deref(), Some("why"));
assert_eq!(m.starting(root), None);
m.sent_back(root, "again");
assert_eq!(m.starting(root).as_deref(), Some("again"));
assert_eq!(m.starting(root).as_deref(), Some("again"));
assert_eq!(m.starting(root), None);
m.sent_back(root, "third");
let walked = std::iter::from_fn(|| m.starting(root)).count();
assert_eq!(walked, 4);
for _ in 0..10 {
m.sent_back(root, "more");
while m.starting(root).is_some() {}
}
m.sent_back(root, "most");
assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 64);
m.froze(root);
m.sent_back(root, "new");
assert_eq!(std::iter::from_fn(|| m.starting(root)).count(), 1);
}
}
#[cfg(test)]
mod skipped_definition {
use super::*;
#[test]
fn a_skipped_definition_leaves_none_of_its_values_behind() {
let node = match crate::find::find_node(None) {
Ok(n) => n,
Err(e) => {
assert!(std::env::var_os("CI").is_none(), "CI needs Node: {e}");
eprintln!("skipped: {e}");
return;
}
};
let t = tempfile::tempdir().unwrap();
let file = t.path().join("h.js");
std::fs::write(
&file,
"module.exports = { poke(o) { o.k = 2; return ''; }, show(v) { return JSON.stringify(v); } };",
)
.unwrap();
let mut w = Worker::start(&node, t.path(), RunMode::Build).expect("starts");
assert!(matches!(w.load(&file, true), JsResult::Ok(_)));
w.exchange(r#"{"op":"callsBegin"}"#, None, "the calls' start")
.expect("begins");
let call = |w: &mut Worker, handle: u32, arg: u32| {
w.exchange(
&format!(
r#"{{"op":"call","handle":{handle},"await":false,"this":{{"$u":1}},"args":[{{"$R":{arg}}}]}}"#
),
None,
"a call",
)
.expect("answers")
};
w.write_line(r#"{"op":"def","id":50,"v":{"k":1},"n":1}"#)
.unwrap();
let poked = call(&mut w, 0, 50);
assert!(poked.head.get("dropShared").is_some(), "{}", poked.body);
w.write_line(r#"{"op":"def","id":60,"v":{"a":{"x":1},"o":{"$R":50}},"n":2}"#)
.unwrap();
for id in [60, 61, 50] {
let shown = call(&mut w, 1, id);
assert_eq!(
shown.head.get("stale"),
Some(&Json::Bool(true)),
"value {id}: {}",
shown.body
);
}
w.write_line(r#"{"op":"def","id":70,"v":{"a":{"x":1},"o":{"k":1}},"n":3}"#)
.unwrap();
let shown = call(&mut w, 1, 70);
assert!(
shown.body.contains(r#"{\"a\":{\"x\":1},\"o\":{\"k\":1}}"#),
"{}",
shown.body
);
}
}