drainWithLease function

Future<LeasedDrainResult> drainWithLease({
  1. required QueueLease lease,
  2. required FutureOr<DurableQueue> openQueue(),
  3. Duration? timeLimit,
  4. bool waitForScheduled = false,
  5. Future<void> closeQueue(
    1. DurableQueue queue
    )?,
  6. 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.

  • openQueue builds the queue: storage, handlers, gates and limits, the same way the app does. It is called only after the lease is taken.
  • timeLimit and waitForScheduled are passed to DurableQueue.drain. Running handlers are allowed to finish after the limit, so leave headroom below what the platform allows.
  • closeQueue runs when the drain is over, also after errors. It defaults to queue.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();
  }
}