lruTouchHook function

HiHook lruTouchHook({
  1. String uid = 'lru:touch',
  2. List<String> events = const ['read', 'get'],
  3. String metaKey = 'meta',
  4. String lastAccessedKey = 'last_accessed',
  5. String accessCountKey = 'access_count',
  6. bool trackAccessCount = false,
  7. int nowProvider()?,
  8. HiPhase phase = HiPhase.post,
  9. int priority = 0,
})

Creates an LRU touch hook that updates access metadata on read.

Updates:

  • last_accessed: Current timestamp
  • access_count: Incremented by 1 (if tracking enabled)

Consumer should persist meta after emit if wasWritten('meta').

Parameters

  • uid: Unique hook identifier, defaults to 'lru:touch'
  • events: Events to listen for, defaults to 'read', 'get'
  • metaKey: Key in ctx.data for metadata
  • lastAccessedKey: Key in meta for last access timestamp
  • accessCountKey: Key in meta for access count
  • trackAccessCount: Whether to track access count
  • nowProvider: Function to get current time

Example

engine.register(lruTouchHook());

// Or with custom configuration
engine.register(lruTouchHook(
  events: ['read'],
  trackAccessCount: true,
));

Implementation

HiHook<dynamic, dynamic> lruTouchHook({
  String uid = 'lru:touch',
  List<String> events = const ['read', 'get'],
  String metaKey = 'meta',
  String lastAccessedKey = 'last_accessed',
  String accessCountKey = 'access_count',
  bool trackAccessCount = false,
  int Function()? nowProvider,
  HiPhase phase = HiPhase.post,
  int priority = 0,
}) {
  return HiHook<dynamic, dynamic>(
    uid: uid,
    events: events,
    phase: phase,
    priority: priority,
    handler: (payload, ctx) {
      final context = ctx as HiContext;
      final meta = Map<String, dynamic>.from(
        context.dataTracked[metaKey] as Map<String, dynamic>? ?? {},
      );

      // Update last accessed timestamp
      meta[lastAccessedKey] = nowProvider?.call() ??
          DateTime.now().millisecondsSinceEpoch;

      // Optionally track access count
      if (trackAccessCount) {
        final currentCount = meta[accessCountKey] as int? ?? 0;
        meta[accessCountKey] = currentCount + 1;
      }

      context.dataTracked[metaKey] = meta;
      return const HiContinue();
    },
  );
}