kevy_lua/lib.rs
1//! kevy-lua — Redis EVAL / EVALSHA / SCRIPT surface backed by luna-core.
2//!
3//! kevy's script-host layer. Thin "cement" crate (per the
4//! stone-cement-stone model) — it carries no algorithmic content, only
5//! the bridge between kevy-rt's command dispatch path, kevy-resp's
6//! wire codec, and luna-core's sandboxed `Vm`.
7//!
8//! Design lock-in:
9//!
10//! - **Default Lua 5.1** — preserves the Redis Lua ecosystem (BullMQ,
11//! Redlock, rate limiters, anything copied from Redis docs).
12//! - **Per-script dialect opt-in via `#!lua version=N`** — scripts
13//! opt into 5.2 / 5.3 / 5.4 / 5.5 with a single shebang line.
14//! SHA1 cache key is the raw script bytes, so EVALSHA is
15//! version-aware for free.
16//! - **VM per-shard, per-dialect, lazily spawned** — first EVAL
17//! hitting a dialect on a shard constructs the VM; reused
18//! afterwards. Idle RSS scales with dialects actually used.
19//! - **Atomic execution** — entering EVAL pauses other dispatch on
20//! that shard until the script returns. Matches Redis semantics.
21//!
22//! `Bridge` holds a per-dialect Vm pool (lazy-spawned); `eval()` runs
23//! the script under the sandbox and marshals the first returned
24//! `Value` into a RESP reply. Shebang parsing, SHA1 cache, EVALSHA,
25//! SCRIPT LOAD/EXISTS/FLUSH, and the `redis.call` host plumbing all
26//! live here.
27
28#![forbid(unsafe_code)]
29#![warn(missing_docs)]
30
31use luna_core::runtime::value::Value;
32use luna_core::vm::exec::Vm;
33use std::cell::Cell;
34use std::rc::Rc;
35
36mod dispatch;
37mod host;
38mod marshal;
39mod resp;
40mod shebang;
41
42mod cjson;
43mod cmsgpack;
44/// SHA-1 digest helpers. Exposed because the operator-side wire
45/// layer (kevy-rt's SCRIPT LOAD / EVALSHA codec) needs to convert
46/// between the 20-byte digest used as a cache key and the 40-char
47/// ASCII hex Redis uses on the wire.
48pub mod sha1;
49
50/// Re-export so callers can name the dialect without depending on
51/// luna-core directly.
52pub use luna_core::version::LuaVersion;
53
54pub(crate) use dispatch::{DISPATCH_KEY, DispatchHandle, DispatchSlot};
55
56/// Lua 5.1 / 5.2 / 5.3 / 5.4 / MacroLua / 5.5 — six fixed slots.
57/// `MacroLua` sits between `Lua54` and `Lua55` (it's a 5.4-superset
58/// compile-time-macro dialect). luna-core does not promise
59/// append-only variant ordering, so we explicitly map every variant
60/// to a stable slot via [`dialect_slot`] — an upstream variant
61/// insert can't silently re-index the VM pool.
62const N_DIALECTS: usize = 6;
63
64/// 200 M ≈ 5 s on modern hardware; matches Redis's default
65/// `lua-time-limit`. Overridable via [`Bridge::set_instr_budget`].
66/// `0` = unlimited (no budget cap).
67const DEFAULT_INSTR_BUDGET: i64 = 200_000_000;
68
69fn dialect_slot(v: LuaVersion) -> usize {
70 match v {
71 LuaVersion::Lua51 => 0,
72 LuaVersion::Lua52 => 1,
73 LuaVersion::Lua53 => 2,
74 LuaVersion::Lua54 => 3,
75 LuaVersion::MacroLua => 4,
76 LuaVersion::Lua55 => 5,
77 }
78}
79
80/// A wire-level reply: just the encoded RESP bytes.
81pub type Reply = Vec<u8>;
82
83/// SCRIPT FLUSH mode (Redis 6.2+ semantics).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum FlushMode {
86 /// Synchronous — drop the cache before returning.
87 Sync,
88 /// Asynchronous — schedule the cache drop. Currently both
89 /// modes run as Sync; we keep the tag for future
90 /// differentiation (and Redis-compat replies).
91 Async,
92}
93
94/// A SHA1 hash of a script's source bytes. Used as the EVALSHA cache
95/// key. Includes any `#!lua version=N` shebang in the input, so a
96/// 5.1 script and the same script with a 5.3 shebang have distinct
97/// SHA1s and never collide in the cache.
98pub type ScriptSha1 = [u8; 20];
99
100/// kevy-lua per-shard bridge. One `Bridge` lives in each shard's
101/// runtime; it owns the per-dialect VM pool, the SHA1 cache, and
102/// the kevy-side dispatch callback that `redis.call` invokes.
103///
104/// The bridge is intentionally NOT `Send` / `Sync` — same constraint
105/// as luna-core's `Vm`, which is `!Send + !Sync` by design. kevy's
106/// thread-per-core model means every shard owns its bridge
107/// exclusively.
108pub struct Bridge {
109 /// Lazily-spawned VM per dialect. First EVAL hitting a dialect
110 /// creates the VM; reused for every subsequent script on that
111 /// dialect. Six fixed slots indexed by [`dialect_slot`].
112 vms: [Option<Vm>; N_DIALECTS],
113 /// Host dispatch closure invoked by `redis.call` / `redis.pcall`.
114 /// `Rc` so cheaply cloned into per-Vm userdata at construction
115 /// time without consuming the original.
116 dispatch: DispatchHandle,
117 /// Read-only mode flag set by [`Bridge::eval_ro`] /
118 /// [`Bridge::evalsha_ro`] before running the script and cleared
119 /// right after. `Rc<Cell<...>>` so every per-dialect Vm's
120 /// dispatch userdata sees the same bit without us having to
121 /// walk the pool. Shared with each `DispatchSlot`.
122 read_only: Rc<Cell<bool>>,
123 /// Per-Vm instruction budget applied at construction time
124 /// (`Vm::sandbox(...).with_instr_budget(N)`). Default 200 M
125 /// (the original hard-coded value). The kevy
126 /// operator wires `[lua] time_limit_ms` through here via
127 /// [`Bridge::set_instr_budget`].
128 ///
129 /// Changes only affect VMs spawned **after** the setter call;
130 /// the kevy-side wiring sets it before any EVAL so this is fine
131 /// in practice. If a config reload needs to take effect on
132 /// in-flight VMs, call `script_flush` afterwards.
133 instr_budget: i64,
134 /// Allow-mask, one bit per [`dialect_slot`]. `true` at slot `i`
135 /// means dialect `i` is permitted; an EVAL whose shebang asks
136 /// for a denied dialect gets a wire `-ERR` reply. All-true by
137 /// default.
138 allow: [bool; N_DIALECTS],
139 /// SHA1 → raw script bytes (including shebang). Populated by
140 /// `script_load` and by every successful `eval`. EVALSHA reads
141 /// from here; SCRIPT FLUSH empties it; SCRIPT EXISTS probes it.
142 ///
143 /// Per-shard cache: kevy runs thread-per-core and each shard
144 /// owns its own Bridge, so we don't share a global cache. The
145 /// trade-off (cache miss on first hit per shard) is dwarfed by
146 /// the locking we'd otherwise need.
147 script_cache: std::collections::HashMap<ScriptSha1, Vec<u8>>,
148}
149
150impl Bridge {
151 /// Create a fresh bridge with `dispatch` as the host callback
152 /// behind `redis.call`. No Vms are spawned until the first
153 /// EVAL.
154 ///
155 /// The dispatch closure receives the script's argv (`&[&[u8]]`,
156 /// command name at index 0) plus a `read_only` flag and must
157 /// return RESP reply bytes. When `read_only` is true the
158 /// dispatcher MUST reject write commands with
159 /// `-READONLY can't write against a read-only script\r\n` so
160 /// `EVAL_RO` / `EVALSHA_RO` deliver Redis semantics. kevy-rt
161 /// owns the canonical command-flag table and does this check
162 /// natively in production; tests provide a stub dispatcher
163 /// hard-coding a few write commands (see `tests/integration.rs`).
164 ///
165 /// For embedders that don't need real keyspace access (e.g.
166 /// pure-computation EVAL), [`Bridge::with_no_dispatch`] installs
167 /// a default that returns `-ERR redis.call: no dispatch wired`
168 /// for every call.
169 pub fn new<F>(dispatch: F) -> Self
170 where
171 F: Fn(&[&[u8]], bool) -> Vec<u8> + 'static,
172 {
173 Self {
174 vms: [const { None }; N_DIALECTS],
175 dispatch: Rc::new(dispatch),
176 read_only: Rc::new(Cell::new(false)),
177 allow: [true; N_DIALECTS],
178 script_cache: std::collections::HashMap::new(),
179 instr_budget: DEFAULT_INSTR_BUDGET,
180 }
181 }
182
183 /// Override the per-Vm instruction budget (~5 s ≈ 200 M instr by
184 /// default). `0` disables the cap (unlimited execution).
185 ///
186 /// Setting it does NOT affect already-spawned VMs in the pool —
187 /// you can pair the call with [`Bridge::script_flush`] to force
188 /// a respawn under the new budget, or leave existing VMs as-is
189 /// and only catch new dialects.
190 pub fn set_instr_budget(&mut self, n: i64) {
191 self.instr_budget = n;
192 }
193
194 /// Bridge with a no-op dispatcher: every `redis.call` returns a
195 /// RESP error. Convenience for embedders that want EVAL but
196 /// don't have the host dispatch wired yet (e.g. pure-computation
197 /// scripts during early development).
198 #[must_use]
199 pub fn with_no_dispatch() -> Self {
200 Self::new(|_argv: &[&[u8]], _ro: bool| {
201 b"-ERR redis.call: no host dispatch wired\r\n".to_vec()
202 })
203 }
204
205 /// Restrict which Lua dialects this bridge will spawn VMs for.
206 /// An EVAL with `#!lua version=N` for a non-allowed dialect is
207 /// rejected with a `-ERR` reply. The 5.1 default is always
208 /// accessible via scripts with no shebang regardless of this
209 /// setting (you can't disable the ecosystem-default dialect
210 /// without taking a different `with_allowed_dialects` API).
211 ///
212 /// Passing an empty slice = no restriction = all five dialects
213 /// permitted (the constructor default).
214 pub fn set_allowed_dialects(&mut self, versions: &[LuaVersion]) {
215 if versions.is_empty() {
216 self.allow = [true; N_DIALECTS];
217 return;
218 }
219 self.allow = [false; N_DIALECTS];
220 for v in versions {
221 self.allow[dialect_slot(*v)] = true;
222 }
223 }
224
225 /// Compile-or-execute a script and marshal its first return value
226 /// into a RESP reply.
227 ///
228 /// P1 scope: default to Lua 5.1, ignore KEYS/ARGV (P3 binds them
229 /// to globals), no `redis.call` (P3), no shebang parsing (P4),
230 /// no SHA1 cache (P5). The point is to confirm
231 /// `EVAL "return 1" 0` produces `:1\r\n`.
232 pub fn eval(&mut self, script: &[u8], keys: &[&[u8]], args: &[&[u8]]) -> Reply {
233 // P4: peel off the `#!lua version=N` shebang first so we know
234 // which dialect Vm to route to before parsing the body.
235 let (sh, body) = match shebang::parse(script) {
236 Ok(t) => t,
237 Err(e) => return resp::err(format!("{e}").as_bytes()),
238 };
239 if !self.allow[dialect_slot(sh.version)] {
240 return resp::err(
241 format!("dialect {} disabled by [lua] allow_dialects", version_tag(sh.version))
242 .as_bytes(),
243 );
244 }
245 let src = match std::str::from_utf8(body) {
246 Ok(s) => s,
247 Err(_) => return resp::err(b"script body is not valid UTF-8"),
248 };
249 // Redis EVAL semantics: every script that successfully runs
250 // (or even compiles) is added to the SCRIPT cache so a later
251 // EVALSHA can find it. We insert before running so a script
252 // that runs forever still gets a SCRIPT EXISTS hit (matches
253 // Redis behaviour).
254 let digest = sha1::sha1(script);
255 self.script_cache.entry(digest).or_insert_with(|| script.to_vec());
256 let vm = self.vm_for(sh.version);
257 // Bind KEYS / ARGV freshly per invocation. The `redis` host
258 // table was installed once when the Vm was constructed.
259 host::bind_keys_argv(vm, keys, args);
260 match vm.eval(src) {
261 Ok(results) => {
262 let first = results.first().copied().unwrap_or(Value::Nil);
263 marshal::value(vm, first)
264 }
265 Err(e) => resp::err(format_lua_error(&e).as_bytes()),
266 }
267 }
268
269 /// Read-only variant of [`Bridge::eval`]. The dispatcher receives
270 /// `read_only = true` for every `redis.call` from this script;
271 /// kevy-rt rejects write commands with
272 /// `-READONLY can't write against a read-only script\r\n`.
273 /// Redis 7.0+ `EVAL_RO`.
274 ///
275 /// All other semantics (KEYS / ARGV / SHA1 cache fill /
276 /// dialect routing) are identical to `eval`.
277 pub fn eval_ro(&mut self, script: &[u8], keys: &[&[u8]], args: &[&[u8]]) -> Reply {
278 self.read_only.set(true);
279 let r = self.eval(script, keys, args);
280 self.read_only.set(false);
281 r
282 }
283
284 /// Read-only variant of [`Bridge::evalsha`]. Redis 7.0+ `EVALSHA_RO`.
285 pub fn evalsha_ro(&mut self, sha1: ScriptSha1, keys: &[&[u8]], args: &[&[u8]]) -> Reply {
286 self.read_only.set(true);
287 let r = self.evalsha(sha1, keys, args);
288 self.read_only.set(false);
289 r
290 }
291
292 /// Run a previously-cached script by SHA1 hex.
293 ///
294 /// Returns `-NOSCRIPT ...` if the script isn't in the cache.
295 /// Identical to running `eval` with the cached bytes — the same
296 /// shebang routing, KEYS/ARGV binding, and redis.* host plumbing
297 /// apply.
298 pub fn evalsha(&mut self, sha1: ScriptSha1, keys: &[&[u8]], args: &[&[u8]]) -> Reply {
299 let Some(script) = self.script_cache.get(&sha1).cloned() else {
300 return resp::err(b"NOSCRIPT No matching script. Please use EVAL.");
301 };
302 self.eval(&script, keys, args)
303 }
304
305 /// Cache a script without running it. Returns the SHA1 digest;
306 /// the operator-side wire layer hex-encodes it for the Redis
307 /// SCRIPT LOAD reply.
308 pub fn script_load(&mut self, script: &[u8]) -> ScriptSha1 {
309 let digest = sha1::sha1(script);
310 self.script_cache.insert(digest, script.to_vec());
311 digest
312 }
313
314 /// Test which of the given SHA1s are in the cache. Returns a
315 /// vector with `true`/`false` for each input SHA1 in order.
316 #[must_use]
317 pub fn script_exists(&self, sha1s: &[ScriptSha1]) -> Vec<bool> {
318 sha1s.iter().map(|s| self.script_cache.contains_key(s)).collect()
319 }
320
321 /// Drop the SHA1 cache + all per-dialect VMs. `ASYNC` and `SYNC`
322 /// are currently both implemented as synchronous; the tag is
323 /// preserved for future differentiation.
324 pub fn script_flush(&mut self, _mode: FlushMode) {
325 for slot in &mut self.vms {
326 *slot = None;
327 }
328 self.script_cache.clear();
329 }
330
331 /// Number of dialect VMs currently spawned. Test-only helper —
332 /// production code doesn't need to inspect the pool.
333 #[cfg(test)]
334 fn vm_count(&self) -> usize {
335 self.vms.iter().filter(|s| s.is_some()).count()
336 }
337
338 /// Lazily build the sandbox Vm for `version`. Conservative
339 /// default: base + math + string + table libraries, no JIT,
340 /// no bytecode loading, 200M instruction budget (~5 s on modern
341 /// hardware — Redis's default `lua-time-limit`). The `redis`
342 /// host table is installed once at Vm-construction time; KEYS /
343 /// ARGV are re-bound per `eval` call (see [`Bridge::eval`]).
344 fn vm_for(&mut self, version: LuaVersion) -> &mut Vm {
345 let slot = &mut self.vms[dialect_slot(version)];
346 if slot.is_none() {
347 let mut builder =
348 Vm::sandbox(version).open_base().open_math().open_string().open_table();
349 if self.instr_budget > 0 {
350 builder = builder.with_instr_budget(self.instr_budget);
351 }
352 let mut vm = builder.build();
353 host::install_redis_table(&mut vm);
354 // BullMQ + Sidekiq Pro require the `cmsgpack` global.
355 cmsgpack::install_cmsgpack(&mut vm);
356 cjson::install_cjson(&mut vm);
357 // Install the dispatch handle as a userdata global.
358 // `redis.call` retrieves it via
359 // `vm.userdata_borrow::<DispatchSlot>(DISPATCH_KEY)`. We
360 // clone the Rc so each Vm holds an independent handle
361 // pointing at the shared closure.
362 let _ = vm.set_userdata(
363 DISPATCH_KEY,
364 DispatchSlot {
365 f: Rc::clone(&self.dispatch),
366 read_only: Rc::clone(&self.read_only),
367 },
368 );
369 *slot = Some(vm);
370 }
371 slot.as_mut().expect("just-inserted Vm")
372 }
373}
374
375impl Default for Bridge {
376 /// Equivalent to [`Bridge::with_no_dispatch`] — the safe default
377 /// for embedders that don't have a host dispatch wired yet.
378 fn default() -> Self {
379 Self::with_no_dispatch()
380 }
381}
382
383fn format_lua_error(e: &luna_core::vm::error::LuaError) -> String {
384 // luna-core impls `Display for LuaError` — embedders don't
385 // need to case-split on the inner Value type.
386 format!("{e}")
387}
388
389fn version_tag(v: LuaVersion) -> &'static str {
390 match v {
391 LuaVersion::Lua51 => "5.1",
392 LuaVersion::Lua52 => "5.2",
393 LuaVersion::Lua53 => "5.3",
394 LuaVersion::Lua54 => "5.4",
395 LuaVersion::MacroLua => "macro",
396 LuaVersion::Lua55 => "5.5",
397 }
398}
399
400// Most public-surface tests live in `tests/integration.rs` (the
401// house-rule 500 LOC limit on src/*.rs is preserved that way). The
402// few unit tests below need `Bridge::vm_count`, which is
403// `#[cfg(test)]`-gated and therefore not visible from
404// integration tests.
405#[cfg(test)]
406mod tests {
407 use super::*;
408
409 #[test]
410 fn eval_reuses_vm_across_calls() {
411 let mut b = Bridge::with_no_dispatch();
412 assert_eq!(b.eval(b"return 1", &[], &[]), b":1\r\n");
413 assert_eq!(b.eval(b"return 2", &[], &[]), b":2\r\n");
414 // One VM should be cached for the 5.1 default dialect.
415 assert_eq!(b.vm_count(), 1);
416 }
417
418 #[test]
419 fn script_flush_drops_vm_pool() {
420 let mut b = Bridge::with_no_dispatch();
421 let _ = b.eval(b"return 1", &[], &[]);
422 assert_eq!(b.vm_count(), 1);
423 b.script_flush(FlushMode::Sync);
424 assert_eq!(b.vm_count(), 0);
425 }
426}