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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! Scoped-borrow bridge between [`kevy_lua::Bridge`] and a host-owned
//! mutable shard state (`Store`, `KeyspaceStore`, anything `'static`).
//!
//! `kevy-lua`'s dispatch closure type is
//! `Fn(&[&[u8]], bool) -> Vec<u8> + 'static`. The `'static` bound is
//! mandatory — luna-core stores the closure as Vm userdata (`Any + 'static`).
//! That makes it impossible to capture `&mut T` directly. This crate
//! offers a tiny `LuaHost<T>` wrapper that re-introduces the borrow via
//! a scoped thread-local pointer set inside `LuaHost::eval` and cleared
//! right after. The dispatch closure consults the pointer.
//!
//! ```
//! use kevy_lua_host::LuaHost;
//!
//! // the host state the script's redis.call reaches: here, a call counter
//! let mut host = LuaHost::<u32>::new(|calls, _argv, _read_only| {
//! *calls += 1;
//! b":7\r\n".to_vec()
//! });
//! let mut calls = 0;
//! host.eval(&mut calls, b"return redis.call('GET', KEYS[1])", &[b"k"], &[]);
//! assert_eq!(calls, 1);
//! ```
//!
//! ## Safety contract (read this if you touch the unsafe)
//!
//! - `LuaHost<T>` parameterises over the host context type `T` (kevy's
//! `Store` for the production wiring; an arbitrary type in tests).
//! - `LuaHost::new(dispatch_fn)` builds a kevy-lua `Bridge` whose
//! dispatch closure does `with_current::<T>(|t| dispatch_fn(t, argv, ro))`.
//! The closure carries NO captured state of its own — it just reads
//! the scoped pointer.
//! - `LuaHost::eval(&mut self, &mut T, …)` (and friends) install
//! `(ctx as *mut T, TypeId::of::<T>())` BEFORE delegating to
//! `Bridge::eval`, and restore the previous slot after. A `Drop`
//! guard ensures the restore even on panic.
//! - `with_current::<T>` dereferences the pointer only when the slot's
//! type id is `T`'s, and empties the slot while its closure runs. The
//! pointer is only ever installed while the outer `&mut T` is borrowed
//! mutably by `LuaHost::eval`, and lent to one closure at a time, so
//! no aliasing exists.
//! - kevy is single-threaded per-shard — every shard owns its own
//! `LuaHost<T>` and runs on a dedicated thread. The thread-local
//! gives correct isolation without any synchronisation overhead.
//!
//! The unsafe footprint is **one** `unsafe { &mut *p }` inside
//! `with_current` plus the `Cell::set(ptr)` ergonomics. Audit it on
//! every commit touching this file.
use ;
use TypeId;
use Cell;
use PhantomData;
/// The host context installed for the running eval: its address and the
/// type it was installed as. `None` outside an eval, and while
/// [`with_current`] has the context lent out.
type Current = ;
thread_local!
/// Puts back what [`CURRENT`] held before, on every exit path.
thread_local!
/// Run `f` against this thread's lazily-built [`LuaHost<T>`].
///
/// A `LuaHost` is `!Send` — luna-core's `Vm` holds `Rc`s and raw GC
/// pointers — so a thread-per-core server cannot park it inside its
/// `Send` per-shard command value. This slot keeps one host per shard
/// *thread* instead: identical isolation (thread == shard), owned by
/// the crate that knows why the type can't travel.
///
/// `build` runs once, on the first call on this thread. Returns
/// `None` when the slot is already borrowed — a re-entrant eval on
/// the same thread; callers surface their nested-eval error. A parked
/// host of a *different* `T` (mixed test harnesses; production uses
/// one `T` per process) is dropped and rebuilt.
///
/// ```
/// use kevy_lua_host::{LuaHost, with_thread_host};
/// let build = || LuaHost::<u32>::new(|n, _argv, _ro| format!(":{n}\r\n").into_bytes());
/// let mut ctx = 5;
/// let load = |h: &mut LuaHost<u32>| h.script_load(b"return redis.call('GET', 'k')");
/// let sha = with_thread_host(build, load).ok_or("re-entrant eval")?;
/// // the second call finds the same host, script cache included
/// let reply = with_thread_host(build, |h| h.evalsha(&mut ctx, sha, &[], &[]));
/// assert_eq!(reply.ok_or("re-entrant eval")?, b":5\r\n");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
/// Run `f` with a mutable borrow of the currently-set host context.
///
/// Returns `None` when no `LuaHost::eval` is on the stack, when the
/// running eval's context is not a `T`, or when an enclosing
/// `with_current` already holds it — the context is lent to one caller
/// at a time, so two `&mut T` to it never exist.
///
/// Used inside the dispatch fn passed to [`LuaHost::new`] — call once
/// per `redis.call`, do the kevy dispatch, return RESP bytes.
///
/// ```
/// use kevy_lua_host::{LuaHost, with_current};
/// assert_eq!(with_current::<u32, _>(|n| *n), None, "no eval is running");
/// let mut host = LuaHost::<u32>::new(|n, _argv, _ro| {
/// *n += 1;
/// assert_eq!(with_current::<u32, _>(|_| ()), None, "already lent to this call");
/// b"+OK\r\n".to_vec()
/// });
/// let mut calls = 0u32;
/// host.eval(&mut calls, b"return redis.call('PING')", &[], &[]);
/// assert_eq!(calls, 1);
/// ```
/// kevy-side per-shard Lua host. Wraps a [`kevy_lua::Bridge`] plus
/// the scoped-pointer plumbing.
///
/// `T` is whatever shard state the dispatch closure needs (`Store`,
/// `KeyspaceStore`, …). It must outlive every `LuaHost::eval` call
/// (trivially true: kevy holds the `&mut T` while delegating).
///
/// ```
/// use std::collections::HashMap;
/// use kevy_lua_host::LuaHost;
///
/// type Keyspace = HashMap<Vec<u8>, Vec<u8>>;
/// let mut host = LuaHost::<Keyspace>::new(|ks, argv, _ro| {
/// ks.insert(argv[1].to_vec(), argv[2].to_vec());
/// b"+OK\r\n".to_vec()
/// });
/// let mut shard = Keyspace::new();
/// host.eval(&mut shard, b"return redis.call('SET', KEYS[1], ARGV[1])", &[b"k"], &[b"v"]);
/// assert_eq!(shard.get(&b"k"[..]), Some(&b"v".to_vec()));
/// ```