Skip to main content

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