createTTLSetHook function

PVCacheHook createTTLSetHook({
  1. int priority = 0,
})

TTL (Time-To-Live) Hook System

Implements cache expiration:

  1. Converts 'ttl' metadata to expiration timestamp
  2. Checks expiration on get
  3. Auto-removes expired entries

Usage:

final cache = PVCache(
  env: 'myCache',
  hooks: [createTTLSetHook(), createTTLCheckHook()],
  defaultMetadata: {},
);
await cache.put('key', 'value', metadata: {'ttl': 3600}); // 1 hour

Creates a hook that converts 'ttl' seconds to '_ttl_timestamp'.

Implementation

/// Creates a hook that converts 'ttl' seconds to '_ttl_timestamp'.
PVCacheHook createTTLSetHook({int priority = 0}) {
  return PVCacheHook(
    eventString: 'ttl_set',
    eventFlow: EventFlow.metaUpdatePriorEntry,
    priority: priority,
    actionTypes: [ActionType.put],
    hookFunction: (ctx) async {
      // Check if TTL is provided in metadata
      final ttl = ctx.initialMeta['ttl'];
      if (ttl == null) return; // No TTL specified

      // Convert TTL seconds to timestamp
      final ttlSeconds = ttl is int ? ttl : int.tryParse(ttl.toString());
      if (ttlSeconds == null || ttlSeconds <= 0) return; // Invalid TTL

      // Calculate expiration timestamp
      final expiresAt = DateTime.now()
          .add(Duration(seconds: ttlSeconds))
          .millisecondsSinceEpoch;

      // Set the timestamp in runtime metadata (this gets saved)
      ctx.runtimeMeta['_ttl_timestamp'] = expiresAt;
    },
  );
}