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