ttlNotExpiredCondition function

HiCond ttlNotExpiredCondition({
  1. String name = 'ttl:notExpired',
  2. String metaKey = 'meta',
  3. String createdAtKey = 'created_at',
  4. String ttlSecondsKey = 'ttl_seconds',
  5. int nowProvider()?,
})

Creates a TTL condition that checks if an entry is not expired.

Returns true (allow) when:

  • No meta in context
  • Meta exists but missing TTL fields (created_at, ttl_seconds)
  • Entry is not yet expired

Returns false (block) when:

  • Entry has expired based on created_at + ttl_seconds

The condition is marked as unstable (isStable: false) because expiration depends on current time.

Parameters

  • name: Optional condition name, defaults to 'ttl:notExpired'
  • metaKey: Key in ctx.data to read metadata from, defaults to 'meta'
  • createdAtKey: Key in meta for creation timestamp, defaults to 'created_at'
  • ttlSecondsKey: Key in meta for TTL duration, defaults to 'ttl_seconds'
  • nowProvider: Function to get current time, defaults to DateTime.now()

Example

final condition = ttlNotExpiredCondition();
engine.register(HiHook(
  conditions: [condition],
  // ... handler
));

Implementation

HiCond<dynamic> ttlNotExpiredCondition({
  String name = 'ttl:notExpired',
  String metaKey = 'meta',
  String createdAtKey = 'created_at',
  String ttlSecondsKey = 'ttl_seconds',
  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 createdAt = meta[createdAtKey] as int?;
      final ttlSeconds = meta[ttlSecondsKey] as int?;
      if (createdAt == null || ttlSeconds == null) return true; // Incomplete = allow

      final now = nowProvider?.call() ?? DateTime.now().millisecondsSinceEpoch;
      final expiresAt = createdAt + (ttlSeconds * 1000);
      return now < expiresAt; // Not expired = allow
    },
  );
}