Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 48 additions & 12 deletions src/hxcoro/Coro.hx
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ class Coro {

A timeout of 0 throws the `TimeoutException` immediately without running `lambda`,
and a negative timeout throws a `haxe.exceptions.ArgumentException`.

If the caller is cancelled by an enclosing time limit, this call throws the
`TimeoutException` of that limit.
**/
@:coroutine public static function timeout<T>(ms:Int, lambda:NodeLambda<T>#if coro.stack_traces, ?startPos:haxe.PosInfos#end):T {
if (ms < 0) {
Expand All @@ -121,18 +124,51 @@ class Coro {
if (ms == 0) {
throw exception;
}
return suspend(cont -> {
final context = cont.context;
final scope = new CoroTaskWithLambda(context, lambda, Sequential#if coro.stack_traces, startPos#end);
scope.onDispatch();
final handle = context.scheduleFunction(ms, () -> {
#if coro.stack_traces
context.setExceptionStack(cast cont, exception);
#end
scope.cancel(exception);
});

scope.awaitContinuation(new TimeoutContinuation(cont, handle));
return suspend(cont -> timeoutImpl(cont, ms, exception, lambda#if coro.stack_traces, startPos#end));
}

/**
Like `scope`, executes `lambda` in a new task and returns its result once the task and
all its children have completed. If this takes longer than `ms` milliseconds, the task
is cancelled and the result of `fallback` is returned instead.

A timeout of 0 returns the result of `fallback` immediately without running `lambda`,
and a negative timeout throws a `haxe.exceptions.ArgumentException`.

If the caller is cancelled by an enclosing time limit, `fallback` is not called and
this call throws the `hxcoro.TimeoutException` of that limit.
**/
@:coroutine public static function timeoutOr<T>(ms:Int, fallback:() -> T, lambda:NodeLambda<T>#if coro.stack_traces, ?startPos:haxe.PosInfos#end):T {
if (ms < 0) {
throw new ArgumentException('timeout must be positive');
}
if (ms == 0) {
return fallback();
}
final exception = new TimeoutException();
try {
return suspend(cont -> timeoutImpl(cont, ms, exception, lambda#if coro.stack_traces, startPos#end));
} catch (e:TimeoutException) {
// The scope is cancelled with the cause of whoever cancelled it first, so any
// other instance is the expiry of an enclosing time limit and not ours to handle.
if (e != exception) {
throw e;
}
}
return fallback();
}

static function timeoutImpl<T>(cont:IContinuation<T>, ms:Int, exception:TimeoutException, lambda:NodeLambda<T>#if coro.stack_traces, ?startPos:haxe.PosInfos#end) {
final context = cont.context;
final scope = new CoroTaskWithLambda(context, lambda, Sequential#if coro.stack_traces, startPos#end);
scope.onDispatch();
final handle = context.scheduleFunction(ms, () -> {
#if coro.stack_traces
context.setExceptionStack(cast cont, exception);
#end
scope.cancel(exception);
});

scope.awaitContinuation(new TimeoutContinuation(cont, handle));
}
}
129 changes: 128 additions & 1 deletion tests/src/structured/TestTimeout.hx
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,131 @@ class TestTimeout extends atest.Test {
Assert.isFalse(task.isActive());
Assert.equals(10, task.get());
}
}

function test_timeoutOr_result() {
final task = VirtualRun.run(_ -> {
return timeoutOr(1000, () -> -1, _ -> {
delay(500);
return 10;
});
});
Assert.equals(10, task.get());
}

function test_timeoutOr_fallback() {
final task = VirtualRun.run(_ -> {
return timeoutOr(500, () -> -1, _ -> {
delay(1000);
return 10;
});
});
Assert.equals(-1, task.get());
}

function test_timeoutOr_zero() {
var ran = false;
final task = VirtualRun.run(_ -> {
return timeoutOr(0, () -> -1, _ -> {
ran = true;
return 10;
});
});
Assert.equals(-1, task.get());
Assert.isFalse(ran);
}

function test_timeoutOr_negative() {
final task = VirtualRun.run(_ -> {
return timeoutOr(-1, () -> -1, _ -> 10);
});
Assert.isOfType(task.getError(), ArgumentException);
}

function test_timeoutOr_exception() {
final task = VirtualRun.run(_ -> {
return timeoutOr(500, () -> -1, _ -> {
throw new Exception("boom");
});
});
Assert.equals("boom", task.getError().message);
}

function test_timeoutOr_fallback_throws() {
final task = VirtualRun.run(_ -> {
return timeoutOr(500, () -> throw new Exception("no reply"), _ -> {
delay(1000);
return 10;
});
});
Assert.equals("no reply", task.getError().message);
}

/**
The expiry of an enclosing time limit is not the inner call's own, so its fallback
must not run. See https://github.com/HaxeFoundation/hxcoro/issues/259.
**/
function test_timeoutOr_enclosing_timeout() {
var innerFallback = false;
final task = VirtualRun.run(_ -> {
return timeoutOr(100, () -> "outer", _ -> {
return timeoutOr(1000, () -> {
innerFallback = true;
"inner";
}, _ -> {
delay(3000);
return "done";
});
});
});
Assert.equals("outer", task.get());
Assert.isFalse(innerFallback);
}

function test_timeoutOr_enclosing_timeout_throws() {
var innerFallback = false;
final task = VirtualRun.run(_ -> {
return timeout(100, _ -> {
return timeoutOr(1000, () -> {
innerFallback = true;
"inner";
}, _ -> {
delay(3000);
return "done";
});
});
});
Assert.isOfType(task.getError(), TimeoutException);
Assert.isFalse(innerFallback);
}

function test_timeoutOr_inner_expires_first() {
final task = VirtualRun.run(_ -> {
return timeoutOr(1000, () -> "outer", _ -> {
return timeoutOr(100, () -> "inner", _ -> {
delay(3000);
return "done";
});
});
});
Assert.equals("inner", task.get());
}

/**
A retry loop under an enclosing time limit ends with that limit, instead of handling
its expiry as the inner one on every iteration.
**/
function test_timeoutOr_loop_ends_with_enclosing_timeout() {
var iterations = 0;
final task = VirtualRun.run(_ -> {
return timeoutOr(250, () -> "outer", _ -> {
while (iterations < 1000) {
timeoutOr(100, () -> {}, _ -> delay(3000));
iterations++;
}
return "loop ended";
});
});
Assert.equals("outer", task.get());
Assert.equals(2, iterations);
}
}
Loading