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
42/// SHA-1 digest helpers. Exposed because the operator-side wire
43/// layer (kevy-rt's SCRIPT LOAD / EVALSHA codec) needs to convert
44/// between the 20-byte digest used as a cache key and the 40-char
45/// ASCII hex Redis uses on the wire.
46pub mod sha1;
47mod cmsgpack;
48mod cjson;
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::{DispatchHandle, DispatchSlot, DISPATCH_KEY};
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!(
242 "dialect {} disabled by [lua] allow_dialects",
243 version_tag(sh.version)
244 )
245 .as_bytes(),
246 );
247 }
248 let src = match std::str::from_utf8(body) {
249 Ok(s) => s,
250 Err(_) => return resp::err(b"script body is not valid UTF-8"),
251 };
252 // Redis EVAL semantics: every script that successfully runs
253 // (or even compiles) is added to the SCRIPT cache so a later
254 // EVALSHA can find it. We insert before running so a script
255 // that runs forever still gets a SCRIPT EXISTS hit (matches
256 // Redis behaviour).
257 let digest = sha1::sha1(script);
258 self.script_cache.entry(digest).or_insert_with(|| script.to_vec());
259 let vm = self.vm_for(sh.version);
260 // Bind KEYS / ARGV freshly per invocation. The `redis` host
261 // table was installed once when the Vm was constructed.
262 host::bind_keys_argv(vm, keys, args);
263 match vm.eval(src) {
264 Ok(results) => {
265 let first = results.first().copied().unwrap_or(Value::Nil);
266 marshal::value(vm, first)
267 }
268 Err(e) => resp::err(format_lua_error(&e).as_bytes()),
269 }
270 }
271
272 /// Read-only variant of [`Bridge::eval`]. The dispatcher receives
273 /// `read_only = true` for every `redis.call` from this script;
274 /// kevy-rt rejects write commands with
275 /// `-READONLY can't write against a read-only script\r\n`.
276 /// Redis 7.0+ `EVAL_RO`.
277 ///
278 /// All other semantics (KEYS / ARGV / SHA1 cache fill /
279 /// dialect routing) are identical to `eval`.
280 pub fn eval_ro(&mut self, script: &[u8], keys: &[&[u8]], args: &[&[u8]]) -> Reply {
281 self.read_only.set(true);
282 let r = self.eval(script, keys, args);
283 self.read_only.set(false);
284 r
285 }
286
287 /// Read-only variant of [`Bridge::evalsha`]. Redis 7.0+ `EVALSHA_RO`.
288 pub fn evalsha_ro(&mut self, sha1: ScriptSha1, keys: &[&[u8]], args: &[&[u8]]) -> Reply {
289 self.read_only.set(true);
290 let r = self.evalsha(sha1, keys, args);
291 self.read_only.set(false);
292 r
293 }
294
295 /// Run a previously-cached script by SHA1 hex.
296 ///
297 /// Returns `-NOSCRIPT ...` if the script isn't in the cache.
298 /// Identical to running `eval` with the cached bytes — the same
299 /// shebang routing, KEYS/ARGV binding, and redis.* host plumbing
300 /// apply.
301 pub fn evalsha(&mut self, sha1: ScriptSha1, keys: &[&[u8]], args: &[&[u8]]) -> Reply {
302 let Some(script) = self.script_cache.get(&sha1).cloned() else {
303 return resp::err(b"NOSCRIPT No matching script. Please use EVAL.");
304 };
305 self.eval(&script, keys, args)
306 }
307
308 /// Cache a script without running it. Returns the SHA1 digest;
309 /// the operator-side wire layer hex-encodes it for the Redis
310 /// SCRIPT LOAD reply.
311 pub fn script_load(&mut self, script: &[u8]) -> ScriptSha1 {
312 let digest = sha1::sha1(script);
313 self.script_cache.insert(digest, script.to_vec());
314 digest
315 }
316
317 /// Test which of the given SHA1s are in the cache. Returns a
318 /// vector with `true`/`false` for each input SHA1 in order.
319 #[must_use]
320 pub fn script_exists(&self, sha1s: &[ScriptSha1]) -> Vec<bool> {
321 sha1s.iter().map(|s| self.script_cache.contains_key(s)).collect()
322 }
323
324 /// Drop the SHA1 cache + all per-dialect VMs. `ASYNC` and `SYNC`
325 /// are currently both implemented as synchronous; the tag is
326 /// preserved for future differentiation.
327 pub fn script_flush(&mut self, _mode: FlushMode) {
328 for slot in &mut self.vms {
329 *slot = None;
330 }
331 self.script_cache.clear();
332 }
333
334
335 /// Number of dialect VMs currently spawned. Test-only helper —
336 /// production code doesn't need to inspect the pool.
337 #[cfg(test)]
338 fn vm_count(&self) -> usize {
339 self.vms.iter().filter(|s| s.is_some()).count()
340 }
341
342 /// Lazily build the sandbox Vm for `version`. Conservative
343 /// default: base + math + string + table libraries, no JIT,
344 /// no bytecode loading, 200M instruction budget (~5 s on modern
345 /// hardware — Redis's default `lua-time-limit`). The `redis`
346 /// host table is installed once at Vm-construction time; KEYS /
347 /// ARGV are re-bound per `eval` call (see [`Bridge::eval`]).
348 fn vm_for(&mut self, version: LuaVersion) -> &mut Vm {
349 let slot = &mut self.vms[dialect_slot(version)];
350 if slot.is_none() {
351 let mut builder = Vm::sandbox(version)
352 .open_base()
353 .open_math()
354 .open_string()
355 .open_table();
356 if self.instr_budget > 0 {
357 builder = builder.with_instr_budget(self.instr_budget);
358 }
359 let mut vm = builder.build();
360 host::install_redis_table(&mut vm);
361 // BullMQ + Sidekiq Pro require the `cmsgpack` global.
362 cmsgpack::install_cmsgpack(&mut vm);
363 cjson::install_cjson(&mut vm);
364 // Install the dispatch handle as a userdata global.
365 // `redis.call` retrieves it via
366 // `vm.userdata_borrow::<DispatchSlot>(DISPATCH_KEY)`. We
367 // clone the Rc so each Vm holds an independent handle
368 // pointing at the shared closure.
369 let _ = vm.set_userdata(
370 DISPATCH_KEY,
371 DispatchSlot {
372 f: Rc::clone(&self.dispatch),
373 read_only: Rc::clone(&self.read_only),
374 },
375 );
376 *slot = Some(vm);
377 }
378 slot.as_mut().expect("just-inserted Vm")
379 }
380}
381
382impl Default for Bridge {
383 /// Equivalent to [`Bridge::with_no_dispatch`] — the safe default
384 /// for embedders that don't have a host dispatch wired yet.
385 fn default() -> Self {
386 Self::with_no_dispatch()
387 }
388}
389
390fn format_lua_error(e: &luna_core::vm::error::LuaError) -> String {
391 // luna-core impls `Display for LuaError` — embedders don't
392 // need to case-split on the inner Value type.
393 format!("{e}")
394}
395
396fn version_tag(v: LuaVersion) -> &'static str {
397 match v {
398 LuaVersion::Lua51 => "5.1",
399 LuaVersion::Lua52 => "5.2",
400 LuaVersion::Lua53 => "5.3",
401 LuaVersion::Lua54 => "5.4",
402 LuaVersion::MacroLua => "macro",
403 LuaVersion::Lua55 => "5.5",
404 }
405}
406
407
408// Most public-surface tests live in `tests/integration.rs` (the
409// house-rule 500 LOC limit on src/*.rs is preserved that way). The
410// few unit tests below need `Bridge::vm_count`, which is
411// `#[cfg(test)]`-gated and therefore not visible from
412// integration tests.
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 #[test]
418 fn eval_reuses_vm_across_calls() {
419 let mut b = Bridge::with_no_dispatch();
420 assert_eq!(b.eval(b"return 1", &[], &[]), b":1\r\n");
421 assert_eq!(b.eval(b"return 2", &[], &[]), b":2\r\n");
422 // One VM should be cached for the 5.1 default dialect.
423 assert_eq!(b.vm_count(), 1);
424 }
425
426 #[test]
427 fn script_flush_drops_vm_pool() {
428 let mut b = Bridge::with_no_dispatch();
429 let _ = b.eval(b"return 1", &[], &[]);
430 assert_eq!(b.vm_count(), 1);
431 b.script_flush(FlushMode::Sync);
432 assert_eq!(b.vm_count(), 0);
433 }
434}