1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
#![cfg_attr(test, allow(clippy::expect_used))]
use camino::Utf8Path;
use mlua::ErrorContext as _;
use mlua::Function;
use mlua::Lua;
use mlua::LuaSerdeExt as _;
use mlua::Table;
use mlua::Value;
use mlua::serde::Deserializer;
use crate::Error;
use crate::server::Server;
use crate::spec::ServerSpec;
use crate::spec::Spec;
use crate::spec::Variant;
const FENNEL_LUA: &str = include_str!("../vendor/fennel.lua");
#[derive(Debug)]
struct Config {
server: Function,
flow: Function,
spec: Spec,
}
impl Config {
/// The chunk has already returned, so key paths stand in for Lua positions.
fn from_value(path: &Utf8Path, value: Value) -> Result<Config, Error> {
let invalid = |message: String| Error::ConfigInvalid {
path: path.to_owned(),
message,
};
let Value::Table(table) = value else {
return Err(invalid(format!(
"the config must return a table, not {}",
value.type_name()
)));
};
let server = take_function(&table, "server")?
.ok_or_else(|| invalid("server must be a function".to_owned()))?;
let flow = take_function(&table, "flow")?
.ok_or_else(|| invalid("flow must be a function".to_owned()))?;
let spec: Spec = serde_path_to_error::deserialize(Deserializer::new(Value::Table(table)))
.map_err(|error| {
let key_path = error.path().to_string();
match error.into_inner() {
mlua::Error::DeserializeError(message) if key_path == "." => invalid(message),
mlua::Error::DeserializeError(message) => invalid(format!("{key_path}: {message}")),
other => Error::Config(other),
}
})?;
Ok(Config { server, flow, spec })
}
}
/// Removed before deserializing so unknown-field validation still catches typos.
fn take_function(table: &Table, key: &str) -> Result<Option<Function>, mlua::Error> {
let value = table.raw_get::<Value>(key)?;
table.raw_set(key, Value::Nil)?;
Ok(match value {
Value::Function(call) => Some(call),
_ => None,
})
}
pub struct Parallax {
server: Function,
#[expect(dead_code, reason = "run once the browser driver lands")]
flow: Function,
spec: Spec,
name: String,
// The function handles are weak; this keeps the VM alive.
lua: Lua,
}
impl Parallax {
pub fn load(path: &Utf8Path) -> Result<Parallax, Error> {
let source = fs_err::read_to_string(path)?;
// Fennel needs the debug library, and configs are the user's own trusted files.
let lua = unsafe { Lua::unsafe_new() };
let value =
run_config(&lua, &source, path.as_str()).with_context(|_| format!("loading {path}"))?;
let config = Config::from_value(path, value)?;
let name = config
.spec
.name
.clone()
.unwrap_or_else(|| default_name(path));
Ok(Parallax {
server: config.server,
flow: config.flow,
spec: config.spec,
name,
lua,
})
}
pub fn variants(&self) -> &[Variant] {
&self.spec.variants
}
pub fn name(&self) -> &str {
&self.name
}
pub async fn run(&self, output: Option<&Utf8Path>) -> Result<(), Error> {
let scratch;
let root = match output {
Some(path) => path,
None => {
scratch = camino_tempfile::tempdir().map_err(Error::Io)?;
scratch.path()
}
};
for variant in &self.spec.variants {
let server_spec = self.call_server()?;
let server = Server::start(&server_spec, variant.name.as_str(), root).await?;
// The flow runs here once the browser driver lands.
server.stop().await?;
}
Ok(())
}
/// Called per variant, so a config can vary the command per run.
fn call_server(&self) -> Result<ServerSpec, Error> {
let value: Value = self.server.call(()).map_err(Error::ServerFunction)?;
self.lua.from_value(value).map_err(Error::ServerFunction)
}
}
fn default_name(path: &Utf8Path) -> String {
path.parent()
.and_then(Utf8Path::file_name)
.unwrap_or("parallax")
.to_owned()
}
fn run_config(lua: &Lua, source: &str, filename: &str) -> Result<Value, mlua::Error> {
let fennel: Table = lua.load(FENNEL_LUA).set_name("fennel.lua").eval()?;
// `correlate` keeps errors on the config's own line numbers.
let compile: Function = fennel.get("compile-string")?;
let options = lua.create_table()?;
options.set("filename", filename)?;
options.set("correlate", true)?;
let compiled: String = compile.call((source, options))?;
lua.load(compiled).set_name(format!("@{filename}")).eval()
}
#[cfg(test)]
mod tests {
use super::*;
use camino::Utf8Path;
struct FailsSerialize;
impl serde::Serialize for FailsSerialize {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom("boom"))
}
}
#[test]
fn non_validation_deserialization_errors_become_config_errors() {
let lua = Lua::new();
let table = lua.create_table().expect("root table");
let variants = lua.create_table().expect("variants table");
let desktop = lua.create_table().expect("variant table");
let viewport = lua.create_table().expect("viewport table");
viewport.push(1280).expect("width");
viewport.push(900).expect("height");
desktop.set("viewport", viewport).expect("viewport");
variants.set("desktop", desktop).expect("variant");
table.set("variants", variants).expect("variants");
table
.set(
"name",
lua.create_ser_any_userdata(FailsSerialize)
.expect("userdata"),
)
.expect("name");
table
.set(
"server",
lua.create_function(|_, ()| Ok(()))
.expect("server function"),
)
.expect("server");
table
.set(
"flow",
lua.create_function(|_, ()| Ok(())).expect("flow function"),
)
.expect("flow");
let error = Config::from_value(Utf8Path::new("config.fnl"), Value::Table(table))
.expect_err("deserialization must fail");
assert!(matches!(error, Error::Config(_)));
}
}