exclusive static method

Future<WayfinderFileLock> exclusive(
  1. File file, {
  2. Duration timeout = const Duration(seconds: 120),
  3. WayfinderCancellation? cancel,
})

Takes the lock, polling until it is free. Throws a TimeoutException after timeout, and WayfinderException.cancelled() when cancel fires first.

Implementation

static Future<WayfinderFileLock> exclusive(
  File file, {
  Duration timeout = const Duration(seconds: 120),
  WayfinderCancellation? cancel,
}) async {
  // One listener per wait, removed after it, so a long-lived cancellation
  // does not collect one per poll.
  final cancelled = Completer<void>();
  final listening = cancel?.whenCancelled.asStream().listen((_) {
    if (!cancelled.isCompleted) cancelled.complete();
  });
  try {
    final watch = Stopwatch()..start();
    var delay = const Duration(milliseconds: 5);
    while (true) {
      throwIfCancelled(cancel);
      if (await _attempt(file) case final lock?) return lock;
      final left = timeout - watch.elapsed;
      if (left <= Duration.zero) {
        throw TimeoutException(
          'Timed out waiting for the lock ${file.path}.',
          timeout,
        );
      }
      final wait = delay < left ? delay : left;
      await Future.any([Future<void>.delayed(wait), cancelled.future]);
      if (delay < const Duration(milliseconds: 200)) delay *= 2;
    }
  } finally {
    await listening?.cancel();
  }
}