mlua-isle 0.4.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#![cfg(feature = "tokio")]

use mlua_isle::{AsyncIsle, IsleError};
use std::time::{Duration, Instant};

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

#[tokio::test]
async fn async_eval_string() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.eval("return 'hello world'").await.unwrap();
    assert_eq!(result, "hello world");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_eval_nil() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.eval("return nil").await.unwrap();
    assert_eq!(result, "");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_eval_lua_error() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.eval("error('boom')").await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("boom"));
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_init_sets_globals() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.globals().set("my_val", 42)?;
        Ok(())
    })
    .await
    .unwrap();

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

#[tokio::test]
async fn async_call_global_function() {
    let (isle, driver) = AsyncIsle::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(())
    })
    .await
    .unwrap();

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

#[tokio::test]
async fn async_exec_closure() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();

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

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

#[tokio::test]
async fn async_spawn_eval_cancel() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let task = isle.spawn_eval("while true do end");

    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();
    });

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

    assert!(result.is_err());
    assert_eq!(result.unwrap_err(), IsleError::Cancelled);
    assert!(
        elapsed < Duration::from_secs(2),
        "cancel took too long: {elapsed:?}"
    );

    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_spawn_call_cancel() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.load("function spin() while true do end end").exec()?;
        Ok(())
    })
    .await
    .unwrap();

    let task = isle.spawn_call("spin", &[]);
    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();
    });

    let result = task.await;
    assert_eq!(result.unwrap_err(), IsleError::Cancelled);
    driver.shutdown().await.unwrap();
}

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

    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();
    });

    let result = task.await;
    assert_eq!(result.unwrap_err(), IsleError::Cancelled);
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_multiple_sequential_evals() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.globals().set("counter", 0)?;
        Ok(())
    })
    .await
    .unwrap();

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

    driver.shutdown().await.unwrap();
}

/// Clone the handle freely — no Arc needed.
#[tokio::test]
async fn async_concurrent_evals_from_multiple_tasks() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let task_count = 10;

    let mut handles = Vec::with_capacity(task_count);
    for i in 0..task_count {
        let isle = isle.clone();
        handles.push(tokio::spawn(async move {
            let code = format!("return {i} * 3");
            let result = isle.eval(&code).await.unwrap();
            assert_eq!(result, (i * 3).to_string());
        }));
    }

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

    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_init_error_propagates() {
    let result = AsyncIsle::spawn(|lua| {
        lua.load("this is not valid lua").exec()?;
        Ok(())
    })
    .await;

    assert!(result.is_err());
    match result.err().unwrap() {
        IsleError::Init(msg) => {
            assert!(!msg.is_empty());
        }
        other => panic!("expected Init error, got: {other}"),
    }
}

#[tokio::test]
async fn async_is_alive_handle() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    assert!(isle.is_alive());
    driver.shutdown().await.unwrap();
    assert!(!isle.is_alive());
}

#[tokio::test]
async fn async_is_alive_driver() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    assert!(driver.is_alive());
    drop(isle);
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_drop_without_shutdown() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let _ = isle.eval("return 1").await;
    drop(isle);
    drop(driver);
    // Should not panic or hang
}

#[tokio::test]
async fn async_still_works_after_cancel() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();

    // Cancel a long-running task
    let task = isle.spawn_eval("while true do end");
    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(30)).await;
        token.cancel();
    });
    let _ = task.await;

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

    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn async_channel_full_returns_correct_error() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();

    // Block the Lua thread so it never drains the channel.
    let blocker = isle.spawn_eval("while true do end");
    let blocker_token = blocker.cancel_token().clone();

    // Give the Lua thread time to start the infinite loop.
    tokio::time::sleep(Duration::from_millis(20)).await;

    // Fill the channel (capacity = 256) then expect ChannelFull.
    let mut last_task = None;
    for _ in 0..300 {
        last_task = Some(isle.spawn_eval("return 1"));
    }

    // The last task should be ChannelFull (channel was full).
    let result = last_task.unwrap().await;
    assert_eq!(result, Err(IsleError::ChannelFull));

    blocker_token.cancel();
    let _ = blocker.await;
    driver.shutdown().await.unwrap();
}

/// Cloned handles work independently; dropping one does not affect others.
#[tokio::test]
async fn async_clone_independence() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let isle2 = isle.clone();

    let r1 = isle.eval("return 1").await.unwrap();
    drop(isle);

    // isle2 still works after isle is dropped.
    let r2 = isle2.eval("return 2").await.unwrap();
    assert_eq!(r1, "1");
    assert_eq!(r2, "2");

    driver.shutdown().await.unwrap();
}

/// Dropping the Driver does NOT kill the Lua thread while Handle clones exist.
/// "In Rust, cancellation is drop" — the thread lives until all senders are gone.
#[tokio::test]
async fn async_driver_drop_does_not_kill_handles() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let isle2 = isle.clone();

    // Drop the driver without shutdown.
    drop(driver);

    // Both handles should still work — the Lua thread is alive.
    let r1 = isle.eval("return 'from isle'").await.unwrap();
    let r2 = isle2.eval("return 'from isle2'").await.unwrap();
    assert_eq!(r1, "from isle");
    assert_eq!(r2, "from isle2");

    // Drop all handles → channel disconnects → thread exits naturally.
    drop(isle);
    drop(isle2);
}

/// When all handles AND driver are dropped, the thread exits via channel disconnect.
#[tokio::test]
async fn async_natural_shutdown_via_channel_disconnect() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();

    let _ = isle.eval("return 1").await.unwrap();

    // Drop everything — no explicit shutdown.
    // Thread exits because blocking_recv returns None.
    drop(isle);
    drop(driver);

    // Brief pause to let the detached thread clean up.
    tokio::time::sleep(Duration::from_millis(50)).await;
}

// ── Builder tests ────────────────────────────────────────────────────

#[tokio::test]
async fn builder_default_works() {
    let (isle, driver) = AsyncIsle::builder().spawn(|_lua| Ok(())).await.unwrap();

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

#[tokio::test]
async fn builder_custom_capacity() {
    let (isle, driver) = AsyncIsle::builder()
        .channel_capacity(8)
        .spawn(|_lua| Ok(()))
        .await
        .unwrap();

    let result = isle.eval("return 'ok'").await.unwrap();
    assert_eq!(result, "ok");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn builder_custom_thread_name() {
    let (isle, driver) = AsyncIsle::builder()
        .thread_name("my-lua-worker")
        .spawn(|_lua| Ok(()))
        .await
        .unwrap();

    let result = isle.eval("return 'named'").await.unwrap();
    assert_eq!(result, "named");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn builder_small_capacity_triggers_channel_full() {
    let (isle, driver) = AsyncIsle::builder()
        .channel_capacity(2)
        .spawn(|_lua| Ok(()))
        .await
        .unwrap();

    // Block the Lua thread.
    let blocker = isle.spawn_eval("while true do end");
    let blocker_token = blocker.cancel_token().clone();
    tokio::time::sleep(Duration::from_millis(20)).await;

    // With capacity 2, filling should be fast.
    let mut last_task = None;
    for _ in 0..10 {
        last_task = Some(isle.spawn_eval("return 1"));
    }

    let result = last_task.unwrap().await;
    assert_eq!(result, Err(IsleError::ChannelFull));

    blocker_token.cancel();
    let _ = blocker.await;
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn builder_all_options() {
    let (isle, driver) = AsyncIsle::builder()
        .channel_capacity(32)
        .thread_name("custom-isle")
        .spawn(|lua| {
            lua.globals().set("x", 99)?;
            Ok(())
        })
        .await
        .unwrap();

    let result = isle.eval("return x").await.unwrap();
    assert_eq!(result, "99");
    driver.shutdown().await.unwrap();
}

// ── Coroutine tests ─────────────────────────────────────────────────

#[tokio::test]
async fn coroutine_eval_simple() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.coroutine_eval("return 1 + 2").await.unwrap();
    assert_eq!(result, "3");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_eval_string() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.coroutine_eval("return 'hello'").await.unwrap();
    assert_eq!(result, "hello");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_eval_nil() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.coroutine_eval("return nil").await.unwrap();
    assert_eq!(result, "");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_eval_error() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let result = isle.coroutine_eval("error('boom')").await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("boom"));
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_eval_accesses_globals() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.globals().set("val", 42)?;
        Ok(())
    })
    .await
    .unwrap();

    let result = isle.coroutine_eval("return val * 2").await.unwrap();
    assert_eq!(result, "84");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_call_simple() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.load("function add(a, b) return a .. b end").exec()?;
        Ok(())
    })
    .await
    .unwrap();

    let result = isle
        .coroutine_call("add", &["hello", " world"])
        .await
        .unwrap();
    assert_eq!(result, "hello world");
    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_eval_cancel() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();
    let task = isle.spawn_coroutine_eval("while true do end");

    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();
    });

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

    assert_eq!(result.unwrap_err(), IsleError::Cancelled);
    assert!(
        start.elapsed() < Duration::from_secs(2),
        "cancel took too long"
    );

    driver.shutdown().await.unwrap();
}

#[tokio::test]
async fn coroutine_still_works_after_cancel() {
    let (isle, driver) = AsyncIsle::spawn(|_lua| Ok(())).await.unwrap();

    // Cancel a coroutine
    let task = isle.spawn_coroutine_eval("while true do end");
    let token = task.cancel_token().clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(30)).await;
        token.cancel();
    });
    let _ = task.await;

    // Isle should still work
    let result = isle.coroutine_eval("return 'ok'").await.unwrap();
    assert_eq!(result, "ok");

    driver.shutdown().await.unwrap();
}

/// Multiple coroutines can interleave on the same VM when one yields.
#[tokio::test]
async fn coroutine_concurrent_with_async_function() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        // Register an async Rust function that sleeps briefly.
        let sleep_fn = lua.create_async_function(|_, ms: u64| async move {
            tokio::time::sleep(Duration::from_millis(ms)).await;
            Ok(ms)
        })?;
        lua.globals().set("async_sleep", sleep_fn)?;
        Ok(())
    })
    .await
    .unwrap();

    let start = Instant::now();

    // Launch two coroutines that each sleep 50ms.
    // If they run sequentially: ~100ms.  If cooperative: ~50ms.
    let t1 = isle.spawn_coroutine_eval("return async_sleep(50)");
    let t2 = isle.spawn_coroutine_eval("return async_sleep(50)");

    let (r1, r2) = tokio::join!(t1, t2);
    let elapsed = start.elapsed();

    assert_eq!(r1.unwrap(), "50");
    assert_eq!(r2.unwrap(), "50");

    // With cooperative scheduling, both should complete in ~50-80ms,
    // not ~100ms.  Use a generous threshold to avoid flaky CI.
    assert!(
        elapsed < Duration::from_millis(90),
        "coroutines ran sequentially ({elapsed:?}), expected cooperative interleaving"
    );

    driver.shutdown().await.unwrap();
}

/// Mixing sync eval and coroutine eval works correctly.
#[tokio::test]
async fn coroutine_mixed_with_sync() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        lua.globals().set("counter", 0)?;
        Ok(())
    })
    .await
    .unwrap();

    // Sync eval
    let r1 = isle
        .eval("counter = counter + 1; return counter")
        .await
        .unwrap();
    assert_eq!(r1, "1");

    // Coroutine eval
    let r2 = isle
        .coroutine_eval("counter = counter + 10; return counter")
        .await
        .unwrap();
    assert_eq!(r2, "11");

    // Sync eval again — state should persist
    let r3 = isle.eval("return counter").await.unwrap();
    assert_eq!(r3, "11");

    driver.shutdown().await.unwrap();
}

/// Pending coroutines are drained (not aborted) on shutdown.
#[tokio::test]
async fn coroutine_pending_drained_on_shutdown() {
    let (isle, driver) = AsyncIsle::spawn(|lua| {
        let sleep_fn = lua.create_async_function(|_, ms: u64| async move {
            tokio::time::sleep(Duration::from_millis(ms)).await;
            Ok(ms)
        })?;
        lua.globals().set("async_sleep", sleep_fn)?;
        Ok(())
    })
    .await
    .unwrap();

    // Spawn a coroutine that takes 80ms.
    let task = isle.spawn_coroutine_eval("return async_sleep(80)");

    // Immediately request shutdown — the coroutine is still running.
    tokio::time::sleep(Duration::from_millis(10)).await;
    driver.shutdown().await.unwrap();

    // The coroutine should have been drained (completed), not aborted.
    let result = task.await;
    assert_eq!(result.unwrap(), "80");
}