writeIfAbsent method

  1. @override
Future<bool> writeIfAbsent(
  1. String key,
  2. Object? value,
  3. Duration? ttl
)
override

Writes only when key is absent. Returns whether the write happened.

Implementation

@override
Future<bool> writeIfAbsent(String key, Object? value, Duration? ttl) async {
  // The primary alone. Asking every replica would let two callers each win
  // on a different node -- a lock that does not lock -- and a node that
  // cannot be reached must refuse rather than hand out a lock nobody holds.
  final String primary = nodesFor(key).first;
  final DVCacheAdapter node = nodes[primary]!;
  if (node is! DVAtomicCacheAdapter) {
    throw StateError(
      'The node "$primary" does not implement compare-and-set, so a '
      'distributed lock over it would not be atomic. Use Redis or '
      'Memcached nodes for a cache that takes locks.',
    );
  }
  try {
    return await (node as DVAtomicCacheAdapter)
        .writeIfAbsent(key, value, ttl);
  } on Object {
    return false;
  }
}