drainWithLease function
Future<LeasedDrainResult>
drainWithLease({
- required QueueLease lease,
- required FutureOr<
DurableQueue> openQueue(), - Duration? timeLimit,
- bool waitForScheduled = false,
- Future<
void> closeQueue(- DurableQueue queue
- QueueClock clock = const SystemQueueClock(),
Takes lease, opens a queue with openQueue, drains it, closes it, and
gives the lease back.
This is the body of a background job. If the lease is held, for example by the app's foreground queue or by another job, it returns LeasedDrainResult.skipped without opening the queue.
openQueuebuilds the queue: storage, handlers, gates and limits, the same way the app does. It is called only after the lease is taken.timeLimitandwaitForScheduledare passed toDurableQueue.drain. Running handlers are allowed to finish after the limit, so leave headroom below what the platform allows.closeQueueruns when the drain is over, also after errors. It defaults toqueue.close(). Use it to close the storage as well.- The lease is renewed every quarter of its ttl while the drain runs, by
clock. If it cannot be renewed, another runner may own the storage now: the queue is stopped, so no further task starts, and the result reports LeasedDrainResult.leaseLost.
Errors from openQueue, the drain, and closeQueue are passed on; the
lease is released either way.
Implementation
Future<LeasedDrainResult> drainWithLease({
required QueueLease lease,
required FutureOr<DurableQueue> Function() openQueue,
Duration? timeLimit,
bool waitForScheduled = false,
Future<void> Function(DurableQueue queue)? closeQueue,
QueueClock clock = const SystemQueueClock(),
}) async {
if (!await lease.tryAcquire()) return const LeasedDrainResult.skipped();
var lost = false;
DurableQueue? opened;
final keeper = LeaseKeeper(lease, clock, () {
lost = true;
// Another runner may own the storage now: start nothing new. The drain
// ends once running handlers finish.
final queue = opened;
if (queue != null && !queue.isClosed) unawaited(queue.stop());
})..start();
try {
final queue = opened = await openQueue();
final DrainResult drain;
try {
drain = await queue.drain(
timeLimit: timeLimit,
waitForScheduled: waitForScheduled,
);
} finally {
await (closeQueue ?? _close)(queue);
}
return LeasedDrainResult._(drain, leaseLost: lost);
} finally {
keeper.stop();
if (!lost) await lease.release();
}
}