get<T> method
The value under key, or null when there is none, it expired, or it is
not a T.
With compute the read goes through: a miss runs compute, stores what
it returns for ttl under tags, and returns it. Concurrent callers of
the same key share one compute -- the stampede a cold cache otherwise
sends at an expensive query -- and a compute that throws stores nothing.
tags are applied on every call, so a key keeps its tags after the
process that set them restarted.
With staleFor, a value older than ttl but inside the stale window
is returned at once while one background compute refreshes it; past
both, the caller waits for a real value. The key still holds the plain
value, so a get without compute reads it.
ttl, tags and staleFor only mean something to a compute, and
staleFor only after a ttl; given without them they are an
ArgumentError rather than silently ignored.
Implementation
Future<T?> get<T>(
String key, {
FutureOr<T> Function()? compute,
Duration? ttl,
List<String>? tags,
Duration? staleFor,
}) async {
if (compute == null) {
final String? orphan = ttl != null
? 'ttl'
: tags != null
? 'tags'
: staleFor != null
? 'staleFor'
: null;
if (orphan != null) {
throw ArgumentError.value(
orphan,
orphan,
'$orphan: applies to what compute: stores, and no compute: was '
'given. Store a value with set(key, value, $orphan: ...).',
);
}
return _typed<T>(await _store.read(_scoped(key)));
}
if (staleFor != null && ttl == null) {
throw ArgumentError.value(
staleFor,
'staleFor',
'staleFor: needs a ttl:, the age after which a value is stale.',
);
}
final DVCacheAdapter store = _store;
final String scoped = _scoped(key);
if (tags != null && tags.isNotEmpty) _tags.tag(scoped, tags);
final Object? raw = await store.read(scoped);
final T? cached = raw == null ? null : _typed<T>(raw);
if (cached != null) {
if (staleFor != null && ttl != null) {
final Object? fresh = await store.read(_freshKey(scoped));
if (fresh == null) {
// Serve the stale value now; exactly one refresh runs behind it.
unawaited(
_compute<T>(
store,
scoped,
compute,
ttl,
staleFor,
).then<void>((_) {}, onError: (Object _) {}),
);
}
}
return cached;
}
return _compute<T>(store, scoped, compute, ttl, staleFor);
}