#![cfg(feature = "async")]
use htl::config::AsyncConfig;
use htl::mlua_isle::runtime::CancelToken;
use htl::{Htl, host_module};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
struct DropGuard {
flag: Arc<AtomicBool>,
finished: bool,
}
impl Drop for DropGuard {
fn drop(&mut self) {
if !self.finished {
self.flag.store(true, Ordering::SeqCst);
}
}
}
pub struct Api {
dropped: Arc<AtomicBool>,
}
#[host_module(name = "api")]
impl Api {
pub async fn get(&self, path: String, ms: u64) -> String {
tokio::time::sleep(Duration::from_millis(ms)).await;
path
}
pub async fn watched(&self, ms: u64) -> String {
let mut guard = DropGuard {
flag: self.dropped.clone(),
finished: false,
};
tokio::time::sleep(Duration::from_millis(ms)).await;
guard.finished = true;
"done".to_string()
}
}
fn host() -> (Htl, Htl, Arc<AtomicBool>) {
let checker = Htl::new().unwrap();
let h = Htl::with_checker(&checker).unwrap();
let dropped = Arc::new(AtomicBool::new(false));
Api {
dropped: dropped.clone(),
}
.htl_preload(&h)
.unwrap();
h.install_task_lib().unwrap();
(checker, h, dropped)
}
fn run(h: &Htl, src: &str) -> (anyhow::Result<()>, Duration) {
let token = CancelToken::new();
let started = Instant::now();
let out = h.run_blocking(src, "=test", &[], &token);
(out, started.elapsed())
}
fn global<T: htl::mlua::FromLua>(h: &Htl, name: &str) -> T {
h.lua().globals().get(name).unwrap()
}
#[test]
fn two_children_wait_together_and_each_hands_back_its_value() {
let (_c, h, _) = host();
let (out, took) = run(
&h,
"local task = require('htl.task') \
local api = require('api') \
local a = task.spawn(function() return api:get('/a', 300) end) \
local b = task.spawn(function() return api:get('/b', 300) end) \
GOT = task.await(a) .. ' ' .. task.await(b)",
);
out.unwrap();
eprintln!("S1 wall: {took:?}");
assert_eq!(global::<String>(&h, "GOT"), "/a /b");
assert!(
took >= Duration::from_millis(300) && took < Duration::from_millis(450),
"600 ms of sleep, overlapped: {took:?}"
);
}
#[test]
fn a_child_left_sleeping_is_dropped_before_the_run_returns() {
let (_c, h, dropped) = host();
let (out, _) = run(
&h,
"local task = require('htl.task') \
local api = require('api') \
task.spawn(function() return api:watched(5000) end) \
api:get('', 20) \
DONE = true",
);
out.unwrap();
assert!(global::<bool>(&h, "DONE"));
assert!(
dropped.load(Ordering::SeqCst),
"the child's future was dropped"
);
}
#[test]
fn a_childs_error_reaches_the_parent_as_the_value_it_raised() {
let (_c, h, _) = host();
let (out, _) = run(
&h,
"local task = require('htl.task') \
local t = task.spawn(function() error({ code = 42 }) end) \
local ok, err = pcall(task.await, t) \
OK = ok \
CODE = type(err) == 'table' and err.code or nil \
CANCELLED = task.is_cancelled(err)",
);
out.unwrap();
assert!(!global::<bool>(&h, "OK"));
assert_eq!(global::<i64>(&h, "CODE"), 42);
assert!(!global::<bool>(&h, "CANCELLED"));
}
#[test]
fn awaiting_a_cancelled_child_raises_a_cancellation() {
let (_c, h, dropped) = host();
let (out, took) = run(
&h,
"local task = require('htl.task') \
local api = require('api') \
local t = task.spawn(function() return api:watched(5000) end) \
api:get('', 20) \
t:cancel() \
local ok, err = pcall(task.await, t) \
OK = ok \
CANCELLED = task.is_cancelled(err) \
AFTER = true",
);
out.unwrap();
assert!(!global::<bool>(&h, "OK"));
assert!(global::<bool>(&h, "CANCELLED"));
assert!(global::<bool>(&h, "AFTER"));
assert!(dropped.load(Ordering::SeqCst));
assert!(took < Duration::from_millis(500), "{took:?}");
}
#[test]
fn a_close_handle_cancels_its_child_when_the_scope_ends() {
let (_c, h, dropped) = host();
let (out, took) = run(
&h,
"local task = require('htl.task') \
local api = require('api') \
do \
local h <close> = task.spawn(function() return api:watched(5000) end) \
api:get('', 20) \
BEFORE = h:done() \
end \
AFTER = true",
);
out.unwrap();
assert!(
!global::<bool>(&h, "BEFORE"),
"still running inside the scope"
);
assert!(global::<bool>(&h, "AFTER"));
assert!(dropped.load(Ordering::SeqCst), "dropped at the scope's end");
assert!(took < Duration::from_millis(500), "{took:?}");
}
#[test]
fn spawn_under_exec_raises_rather_than_hanging() {
let (_c, h, _) = host();
let err = h
.exec(
"local task = require('htl.task') \
task.spawn(function() return 1 end)",
"=test",
&[],
)
.unwrap_err();
let text = format!("{err:#}");
assert!(
text.contains("sync requests cannot spawn"),
"mlua-isle names the reason: {text}"
);
}
#[test]
fn a_second_await_of_one_task_is_an_error_that_says_so() {
let (_c, h, _) = host();
let (out, _) = run(
&h,
"local task = require('htl.task') \
local t = task.spawn(function() return 7 end) \
FIRST = t:await() \
local ok, err = pcall(task.await, t) \
OK = ok \
ERR = tostring(err)",
);
out.unwrap();
assert_eq!(global::<i64>(&h, "FIRST"), 7);
assert!(!global::<bool>(&h, "OK"));
assert_eq!(
global::<String>(&h, "ERR"),
"htl.task: task already awaited"
);
}
#[test]
fn the_projects_grace_applies_to_a_childs_cancel() {
let (_c, h, dropped) = host();
h.configure_async(&AsyncConfig {
grace_ms: Some(0),
preempt: None,
})
.unwrap();
let (out, took) = run(
&h,
"local task = require('htl.task') \
local api = require('api') \
task.spawn(function() return api:watched(5000) end) \
api:get('', 20)",
);
out.unwrap();
assert!(dropped.load(Ordering::SeqCst));
assert!(took < Duration::from_millis(200), "{took:?}");
}
#[test]
fn channels_timers_and_select_run() {
let (_c, h, _) = host();
let (out, _) = run(
&h,
"local task = require('htl.task') \
local ch = task.channel(2) \
local producer = task.spawn(function() \
for i = 1, 3 do ch:send(i) end \
ch:close() \
return 3 \
end) \
local sum = 0 \
while task.select({ ch:on(function(v, ok) if ok then sum = sum + v end return ok end) }) do end \
SUM = sum \
TASK = task.select({ producer:on(function(ok, n) return tostring(ok) .. ' ' .. n end) }) \
local tk = task.ticker(5) \
TICK = task.select({ \
tk:on(function(ms, ok) return ok and ms > 0 and 'tick' or 'closed' end), \
task.after(5000):on(function() return 'timeout' end), \
}) \
tk:stop() \
task.after(1):wait() \
local r = task.channel(0) \
RAW = task.select_raw({ r:arm_recv(), task.after(0):arm() }) \
DEFAULT = task.select({ r:on(function(s) return s end) }, { default = function() return 'default' end })",
);
out.unwrap();
assert_eq!(global::<i64>(&h, "SUM"), 6);
assert_eq!(global::<String>(&h, "TASK"), "true 3");
assert_eq!(global::<String>(&h, "TICK"), "tick");
assert_eq!(global::<i64>(&h, "RAW"), 2);
assert_eq!(global::<String>(&h, "DEFAULT"), "default");
}
#[test]
fn select_case_then_await() {
let (_c, h, _) = host();
let (out, _) = run(
&h,
"local task = require('htl.task') \
local t = task.spawn(function() return 7 end) \
GOT = task.select({ t:on(function(ok, v) return v end) }) \
local ok, err = pcall(t.await, t) \
OK = ok ERR = tostring(err) \
local ok2, err2 = pcall(t.on, t, function() end) \
ERR2 = tostring(err2) \
local gate = task.channel(1) \
local slow = task.spawn(function() local v = gate:recv() return v end) \
OTHER = task.select({ slow:on(function() return 'task' end), task.after(0):on(function() return 'timer' end) }, { biased = true }) \
gate:send('later') \
LATER = slow:await()",
);
out.unwrap();
assert_eq!(global::<i64>(&h, "GOT"), 7);
assert!(!global::<bool>(&h, "OK"));
assert_eq!(
global::<String>(&h, "ERR"),
"htl.task: task already awaited"
);
assert!(
global::<String>(&h, "ERR2").contains("htl.task: task already awaited"),
"{}",
global::<String>(&h, "ERR2")
);
assert_eq!(global::<String>(&h, "OTHER"), "timer");
assert_eq!(global::<String>(&h, "LATER"), "later");
}