evict method

  1. @override
Future<EvictionResult> evict(
  1. EvictionPolicy policy
)
override

Run one eviction pass according to policy.

Backends should remove associated sidecars, provenance, and delivery state for any event they physically delete.

Implementation

@override
Future<EvictionResult> evict(EvictionPolicy policy) async {
  final activeDeliveryEventIds = eventDeliveryRecords.values
      .where((record) => record.status != EventDeliveryStatus.delivered)
      .map((record) => record.eventId)
      .toSet();
  final lockedEventIds = <String>{
    ...activeDeliveryEventIds,
    ...relayDeliveryTargets.values
        .where((target) => target.state != RelayDeliveryState.acked)
        .map((target) => target.eventId),
  };
  final deliveredEventIds = eventDeliveryRecords.values
      .where((record) => record.status == EventDeliveryStatus.delivered)
      .map((record) => record.eventId)
      .toSet();
  final plan = EventEvictionPlanner.planFromStateRecords(
    stateRecords: eventCacheStateRecords.values.toList(),
    lockedEventIds: lockedEventIds,
    deliveredEventIds: deliveredEventIds,
    policy: policy,
  );

  if (plan.eventIdsToRemove.isNotEmpty) {
    final removedEvents = events.values
        .where((event) => plan.eventIdsToRemove.contains(event.id))
        .toList();
    events.removeWhere((key, value) => plan.eventIdsToRemove.contains(key));
    _removeEventSidecarsByIds(plan.eventIdsToRemove);
    await _refreshDerivedStateForPubKeys(
      removedEvents.map((event) => event.pubKey).toSet(),
    );
  }

  // Sweep leftover delivery records whose event was kept (or never stored).
  // A terminally failed record swept here unpins its event for the next run.
  final deliverySweep = EventEvictionPlanner.planDeliverySweep(
    deliveryRecords: eventDeliveryRecords.values.toList(),
    policy: policy,
  );
  for (final eventId in deliverySweep.deliveryEventIdsToRemove) {
    eventDeliveryRecords.remove(eventId);
    relayDeliveryTargets.removeWhere(
      (key, target) => target.eventId == eventId,
    );
  }

  return plan.toResult().copyWith(
    removedCompletedDeliveries: deliverySweep.removedCompletedDeliveries,
    removedTerminalFailedDeliveries:
        deliverySweep.removedTerminalFailedDeliveries,
  );
}