lruRecentlyAccessedCondition function

HiCond lruRecentlyAccessedCondition({
  1. String name = 'lru:recentlyAccessed',
  2. String metaKey = 'meta',
  3. String lastAccessedKey = 'last_accessed',
  4. required int thresholdMs,
  5. int nowProvider()?,
})

Creates an LRU condition that checks if an entry was accessed recently.

Returns true (allow) when:

  • No meta in context
  • Meta exists but missing LRU fields
  • Entry was accessed within the threshold

Returns false (block) when:

  • Entry hasn't been accessed within the threshold

Parameters

  • name: Optional condition name, defaults to 'lru:recentlyAccessed'
  • metaKey: Key in ctx.data to read metadata from, defaults to 'meta'
  • lastAccessedKey: Key in meta for last access timestamp
  • thresholdMs: Maximum age in milliseconds to be considered "recent"
  • nowProvider: Function to get current time

Example

// Consider entries older than 1 hour as stale
final isRecent = lruRecentlyAccessedCondition(
  thresholdMs: 60 * 60 * 1000,
);

Implementation

HiCond<dynamic> lruRecentlyAccessedCondition({
  String name = 'lru:recentlyAccessed',
  String metaKey = 'meta',
  String lastAccessedKey = 'last_accessed',
  required int thresholdMs,
  int Function()? nowProvider,
}) {
  return HiCond<dynamic>(
    name: name,
    isStable: false, // Depends on current time
    predicate: (payload, data) {
      final meta = data[metaKey] as Map<String, dynamic>?;
      if (meta == null) return true; // No meta = allow

      final lastAccessed = meta[lastAccessedKey] as int?;
      if (lastAccessed == null) return true; // No timestamp = allow

      final now = nowProvider?.call() ?? DateTime.now().millisecondsSinceEpoch;
      final age = now - lastAccessed;
      return age < thresholdMs;
    },
  );
}