evictByPriority method
Evicts items based on priority, starting with the lowest priority.
This method is used as a fallback when other strategies don't have enough data.
Returns true
if eviction was performed, false
otherwise.
Implementation
Future<bool> evictByPriority() async {
// Get all keys
final keys = await _cacheAdapter.getKeys();
if (keys.isEmpty) {
_log.warning('No items available for priority-based eviction.');
return false;
}
// Get all items to group by priority
final itemsByPriority = <CachePriority, List<String>>{};
for (final key in keys) {
final item = await _cacheAdapter.get(key);
if (item != null) {
final priority = item.priority;
itemsByPriority.putIfAbsent(priority, () => []).add(key);
}
}
// Evict items in priority order (low to high)
final priorities = [
CachePriority.low,
CachePriority.normal,
CachePriority.high,
CachePriority.critical,
];
bool evicted = false;
for (final priority in priorities) {
final priorityKeys = itemsByPriority[priority] ?? [];
for (final key in priorityKeys) {
// Evict the item
await _cacheAdapter.delete(key);
_analytics.recordDelete(key);
evicted = true;
_log.info(
'Evicted item with key: $key (Priority strategy, priority: $priority)');
// Check if we've evicted enough
if (_maxSize != null && _analytics.totalSize <= _maxSize * 0.8) {
_log.info(
'Eviction complete. New cache size: ${_analytics.totalSize}');
return true;
}
if (_maxItems != null) {
final remainingKeys = await _cacheAdapter.getKeys();
if (remainingKeys.length <= _maxItems * 0.8) {
_log.info(
'Eviction complete. New item count: ${remainingKeys.length}');
return true;
}
}
}
// If we've evicted all items of this priority and still need more,
// move on to the next priority level
}
return evicted;
}