mlua-isle 0.7.0

Thread-isolated Lua VM with cancellation, async coroutines, and connection pool for mlua
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use mlua_isle::{Isle, IsleError};
use std::sync::Arc;
use std::time::{Duration, Instant};

#[test]
fn eval_simple_expression() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let result = isle.eval("return 1 + 2").unwrap();
    assert_eq!(result, "3");
    isle.shutdown().unwrap();
}

#[test]
fn eval_string_result() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let result = isle.eval("return 'hello world'").unwrap();
    assert_eq!(result, "hello world");
    isle.shutdown().unwrap();
}

#[test]
fn eval_nil_returns_empty() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let result = isle.eval("return nil").unwrap();
    assert_eq!(result, "");
    isle.shutdown().unwrap();
}

#[test]
fn eval_lua_error_propagates() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let result = isle.eval("error('boom')");
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.to_string().contains("boom"),
        "expected 'boom' in error, got: {err}"
    );
    isle.shutdown().unwrap();
}

#[test]
fn init_sets_globals() {
    let isle = Isle::spawn(|lua| {
        lua.globals().set("my_val", 42)?;
        Ok(())
    })
    .unwrap();

    let result = isle.eval("return my_val").unwrap();
    assert_eq!(result, "42");
    isle.shutdown().unwrap();
}

#[test]
fn call_global_function() {
    let isle = Isle::spawn(|lua| {
        let f = lua.create_function(|_lua, args: mlua::MultiValue| {
            let mut parts = Vec::new();
            for v in args {
                match v {
                    mlua::Value::String(s) => parts.push(s.to_str().unwrap().to_string()),
                    _ => parts.push(format!("{v:?}")),
                }
            }
            Ok(parts.join(", "))
        })?;
        lua.globals().set("greet", f)?;
        Ok(())
    })
    .unwrap();

    let result = isle.call("greet", &["hello", "world"]).unwrap();
    assert_eq!(result, "hello, world");
    isle.shutdown().unwrap();
}

#[test]
fn spawn_eval_cancel_infinite_loop() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let task = isle.spawn_eval("while true do end");

    // Cancel after a short delay
    std::thread::sleep(Duration::from_millis(50));
    task.cancel();

    let start = Instant::now();
    let result = task.wait();
    let elapsed = start.elapsed();

    assert!(result.is_err());
    match result.unwrap_err() {
        IsleError::Cancelled => {}
        other => panic!("expected Cancelled, got: {other}"),
    }
    // Should resolve quickly after cancel (not hang)
    assert!(
        elapsed < Duration::from_secs(2),
        "cancel took too long: {elapsed:?}"
    );

    isle.shutdown().unwrap();
}

#[test]
fn multiple_sequential_evals() {
    let isle = Isle::spawn(|lua| {
        lua.globals().set("counter", 0)?;
        Ok(())
    })
    .unwrap();

    for i in 1..=5 {
        let result = isle.eval("counter = counter + 1; return counter").unwrap();
        assert_eq!(result, i.to_string());
    }

    isle.shutdown().unwrap();
}

#[test]
fn exec_closure() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();

    let result = isle
        .exec(|lua| {
            let val: i64 = lua.load("return 7 * 6").eval().map_err(IsleError::from)?;
            Ok(val.to_string())
        })
        .unwrap();

    assert_eq!(result, "42");
    isle.shutdown().unwrap();
}

#[test]
fn shutdown_after_drop_is_safe() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let _ = isle.eval("return 1");
    // Drop without explicit shutdown — should not panic
    drop(isle);
}

#[test]
fn is_alive_check() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    assert!(isle.is_alive());
    isle.shutdown().unwrap();
}

#[test]
fn init_error_propagates() {
    let result = Isle::spawn(|lua| {
        lua.load("this is not valid lua").exec()?;
        Ok(())
    });
    assert!(result.is_err());
    match result.err().unwrap() {
        IsleError::Init(msg) => {
            assert!(!msg.is_empty(), "init error message should not be empty");
        }
        other => panic!("expected Init error, got: {other}"),
    }
}

#[test]
fn spawn_eval_after_drop_returns_shutdown() {
    // Create Isle, drop it to close the channel, then use a leaked sender
    // to verify the send-failure path.
    //
    // We can't call methods after shutdown (consumes self), so we test the
    // drop path: spawn_eval should return a Task that yields Shutdown.
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    // Use spawn_eval before dropping — but we need to test the failure path.
    // The only way to exercise it without unsafe is to race: drop on another thread.
    let task = isle.spawn_eval("return 1");
    let result = task.wait();
    // This should succeed since we haven't dropped yet
    assert!(result.is_ok());
    drop(isle);
}

#[test]
fn spawn_call_returns_correct_result_after_init() {
    let isle = Isle::spawn(|lua| {
        lua.load("function add(a, b) return tostring(tonumber(a) + tonumber(b)) end")
            .exec()?;
        Ok(())
    })
    .unwrap();

    let result = isle.call("add", &["3", "4"]).unwrap();
    assert_eq!(result, "7");
    isle.shutdown().unwrap();
}

#[test]
fn spawn_exec_cancel() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let task = isle.spawn_exec(|lua| {
        let _: () = lua
            .load("while true do end")
            .exec()
            .map_err(IsleError::from)?;
        Ok("done".to_string())
    });

    std::thread::sleep(Duration::from_millis(50));
    task.cancel();

    let result = task.wait();
    assert!(result.is_err());
    assert_eq!(result.unwrap_err(), IsleError::Cancelled);

    isle.shutdown().unwrap();
}

#[test]
fn try_recv_returns_none_then_some() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let task = isle.spawn_eval("return 'async'");

    // Poll until result arrives (should be fast)
    let mut result = None;
    for _ in 0..100 {
        if let Some(r) = task.try_recv() {
            result = Some(r);
            break;
        }
        std::thread::sleep(Duration::from_millis(5));
    }

    assert_eq!(result.unwrap().unwrap(), "async");
    isle.shutdown().unwrap();
}

#[test]
fn cancel_token_accessor() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let task = isle.spawn_eval("return 1");

    let token = task.cancel_token();
    assert!(!token.is_cancelled());

    task.cancel();
    assert!(task.cancel_token().is_cancelled());

    let _ = task.wait();
    isle.shutdown().unwrap();
}

// ---------------------------------------------------------------------------
// Concurrency tests
// ---------------------------------------------------------------------------

#[test]
fn concurrent_evals_from_multiple_threads() {
    let isle = Arc::new(Isle::spawn(|_lua| Ok(())).unwrap());
    let thread_count = 8;
    let evals_per_thread = 10;

    let handles: Vec<_> = (0..thread_count)
        .map(|t| {
            let isle = Arc::clone(&isle);
            std::thread::spawn(move || {
                for i in 0..evals_per_thread {
                    let code = format!("return {} + {}", t, i);
                    let result = isle.eval(&code).unwrap();
                    let expected = (t + i).to_string();
                    assert_eq!(result, expected, "thread {t}, iter {i}");
                }
            })
        })
        .collect();

    for h in handles {
        h.join().expect("worker thread panicked");
    }

    // Isle processes requests sequentially — all should have completed
    Arc::try_unwrap(isle)
        .unwrap_or_else(|_| panic!("other Arc references remain"))
        .shutdown()
        .unwrap();
}

#[test]
fn concurrent_spawn_eval_with_cancel() {
    let isle = Arc::new(Isle::spawn(|_lua| Ok(())).unwrap());

    // Spawn a long-running task and several quick tasks concurrently
    let isle_c = Arc::clone(&isle);
    let long_handle = std::thread::spawn(move || {
        let task = isle_c.spawn_eval("while true do end");
        std::thread::sleep(Duration::from_millis(30));
        task.cancel();
        let result = task.wait();
        assert_eq!(result.unwrap_err(), IsleError::Cancelled);
    });

    long_handle.join().expect("long task thread panicked");

    // After cancel, Isle should still accept new requests
    let result = isle.eval("return 'still alive'").unwrap();
    assert_eq!(result, "still alive");

    Arc::try_unwrap(isle)
        .unwrap_or_else(|_| panic!("other Arc references remain"))
        .shutdown()
        .unwrap();
}

// ---------------------------------------------------------------------------
// Tokio integration tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn eval_from_tokio_spawn_blocking() {
    let isle = Arc::new(Isle::spawn(|_lua| Ok(())).unwrap());

    let isle_c = Arc::clone(&isle);
    let result = tokio::task::spawn_blocking(move || isle_c.eval("return 1 + 1"))
        .await
        .expect("spawn_blocking panicked")
        .unwrap();

    assert_eq!(result, "2");

    Arc::try_unwrap(isle)
        .unwrap_or_else(|_| panic!("other Arc references remain"))
        .shutdown()
        .unwrap();
}

#[tokio::test]
async fn multiple_tokio_tasks_share_isle() {
    let isle = Arc::new(Isle::spawn(|_lua| Ok(())).unwrap());
    let task_count = 10;

    let mut join_handles = Vec::with_capacity(task_count);
    for i in 0..task_count {
        let isle_c = Arc::clone(&isle);
        join_handles.push(tokio::task::spawn_blocking(move || {
            let code = format!("return {i} * 2");
            let result = isle_c.eval(&code).unwrap();
            assert_eq!(result, (i * 2).to_string());
        }));
    }

    for h in join_handles {
        h.await.expect("tokio task panicked");
    }

    Arc::try_unwrap(isle)
        .unwrap_or_else(|_| panic!("other Arc references remain"))
        .shutdown()
        .unwrap();
}

#[tokio::test]
async fn cancel_from_tokio_task() {
    let isle = Arc::new(Isle::spawn(|_lua| Ok(())).unwrap());

    let isle_c = Arc::clone(&isle);
    let result = tokio::task::spawn_blocking(move || {
        let task = isle_c.spawn_eval("while true do end");
        std::thread::sleep(Duration::from_millis(50));
        task.cancel();
        task.wait()
    })
    .await
    .expect("spawn_blocking panicked");

    assert_eq!(result.unwrap_err(), IsleError::Cancelled);

    // Isle still functional after cancel
    let isle_c = Arc::clone(&isle);
    let result = tokio::task::spawn_blocking(move || isle_c.eval("return 'ok'"))
        .await
        .expect("spawn_blocking panicked")
        .unwrap();
    assert_eq!(result, "ok");

    Arc::try_unwrap(isle)
        .unwrap_or_else(|_| panic!("other Arc references remain"))
        .shutdown()
        .unwrap();
}

#[tokio::test]
async fn shutdown_from_tokio() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();

    let result = tokio::task::spawn_blocking(move || {
        let _ = isle.eval("return 1");
        isle.shutdown()
    })
    .await
    .expect("spawn_blocking panicked");

    assert!(result.is_ok());
}

/// The cancel hook reaches coroutines created by the Lua code itself.
#[test]
fn spawn_eval_cancel_loop_in_lua_created_coroutine() {
    let isle = Isle::spawn(|_lua| Ok(())).unwrap();
    let task = isle.spawn_eval("coroutine.wrap(function() while true do end end)()");

    std::thread::sleep(Duration::from_millis(50));
    task.cancel();

    let start = Instant::now();
    let result = loop {
        if let Some(r) = task.try_recv() {
            break r;
        }
        assert!(
            start.elapsed() < Duration::from_secs(2),
            "cancel did not reach the nested coroutine"
        );
        std::thread::sleep(Duration::from_millis(5));
    };
    assert_eq!(result.unwrap_err(), IsleError::Cancelled);

    // The isle is still usable.
    assert_eq!(isle.eval("return 1").unwrap(), "1");
    isle.shutdown().unwrap();
}