timeboxed<T> static method
Runs body for at most limit. Past it the part is cancelled: its next checkAlive throws, the subprocesses it started are stopped, and after at most unwind for the body to finish this throws CallTimeboxExceeded.
Implementation
static Future<T> timeboxed<T>(Duration limit, Future<T> Function() body,
{Duration unwind = const Duration(seconds: 1)}) {
final box = _Timebox();
final done = Completer<T>();
final finished = Completer<void>();
final timer = Timer(limit, () async {
box.expired = true;
for (final p in box.processes.keys.toList()) {
unawaited(killProcessTree(p));
}
box.processes.clear();
await finished.future.timeout(unwind, onTimeout: () {});
if (!done.isCompleted) {
done.completeError(CallTimeboxExceeded(limit,
elapsedMs: box.clock.elapsedMilliseconds,
phase: box.phase,
trail: box.trailText,
unwound: finished.isCompleted));
}
});
runZoned(() async {
try {
final value = await body();
if (!done.isCompleted) done.complete(value);
} on Object catch (e, st) {
if (!done.isCompleted && !(box.expired && e is CallAbandoned)) done.completeError(e, st);
} finally {
if (!finished.isCompleted) finished.complete();
}
}, zoneValues: {_boxKey: box});
return done.future.whenComplete(timer.cancel);
}