trim method

Future<int> trim({
  1. int? targetQuotaBytes,
})

Trims the directory down to targetQuotaBytes (defaults to maxBytes * trimRatio).

Removes oldest files first according to sortStrategy until the target size is met. Also cleans up orphaned temporary (.tmp) files.

Returns the total number of bytes freed during this operation.

Implementation

Future<int> trim({int? targetQuotaBytes}) async {
  if (!directory.existsSync()) return 0;

  final effectiveMax = maxBytes;
  if (effectiveMax == null && targetQuotaBytes == null) return 0;

  var bytesFreed = 0;
  final now = DateTime.now();

  // Set of companion paths to avoid treating them as standalone primary files.
  final companionPaths = <String>{};
  final primaryFiles = <File>[];
  final orphanedTmpFiles = <File>[];

  try {
    final entities = await directory.list(followLinks: false).toList();

    for (final entity in entities) {
      if (entity is! File) continue;

      final path = entity.path;
      if (path.endsWith('.tmp')) {
        orphanedTmpFiles.add(entity);
        continue;
      }

      if (companionResolver != null) {
        final companions = companionResolver!(entity);
        for (final c in companions) {
          companionPaths.add(c.path);
        }
      }

      primaryFiles.add(entity);
    }
  } catch (_) {
    return 0;
  }

  // 1. Purge orphaned temporary files first
  for (final tmp in orphanedTmpFiles) {
    try {
      final stat = tmp.statSync();
      if (now.difference(stat.modified) > minAgeForEviction) {
        await tmp.delete();
        bytesFreed += stat.size;
        logger?.fine(
            'Evicted orphaned tmp file: ${tmp.path} (${stat.size} bytes)');
      }
    } catch (e) {
      logger?.warning('Failed to delete orphaned tmp file: ${tmp.path}', e);
    }
  }

  // 2. Build eviction entry units for primary files (excluding registered companions)
  var currentTotalSize = 0;
  final entries = <_EvictionEntry>[];

  for (final file in primaryFiles) {
    if (companionPaths.contains(file.path)) continue;

    try {
      final stat = file.statSync();
      var entryBytes = stat.size;

      final companions = companionResolver?.call(file) ?? const <File>[];
      for (final companion in companions) {
        try {
          if (companion.existsSync()) {
            entryBytes += companion.lengthSync();
          }
        } catch (_) {}
      }

      currentTotalSize += entryBytes;
      final timestamp = _resolveTimestamp(file, stat, companions);

      entries.add(
        _EvictionEntry(
          primaryFile: file,
          sortTimestamp: timestamp,
          totalBytes: entryBytes,
          companions: companions,
        ),
      );
    } catch (_) {}
  }

  final quota = targetQuotaBytes ?? effectiveMax!;
  if (currentTotalSize <= quota) {
    if (bytesFreed > 0) {
      logger?.info(
          'Trim completed for ${directory.path}: freed $bytesFreed bytes.');
    }
    return bytesFreed;
  }

  final targetSize = targetQuotaBytes ?? (effectiveMax! * trimRatio).toInt();

  // 3. Sort entries chronologically: oldest timestamp first (LRU)
  entries.sort((a, b) => a.sortTimestamp.compareTo(b.sortTimestamp));

  // 4. Evict oldest entries until total size drops to targetSize
  for (final entry in entries) {
    if (currentTotalSize <= targetSize) break;

    // Skip entries still within the protection window
    if (now.difference(entry.sortTimestamp) < minAgeForEviction) continue;

    try {
      if (entry.primaryFile.existsSync()) {
        await entry.primaryFile.delete();
      }
      for (final companion in entry.companions) {
        try {
          if (companion.existsSync()) {
            await companion.delete();
          }
        } catch (e) {
          logger?.warning(
              'Failed to delete companion file: ${companion.path}', e);
        }
      }

      currentTotalSize -= entry.totalBytes;
      bytesFreed += entry.totalBytes;
      logger?.fine(
        'Evicted file: ${entry.primaryFile.path} '
        '(${entry.totalBytes} bytes${entry.companions.isNotEmpty ? ' with ${entry.companions.length} companion(s)' : ''})',
      );
    } catch (e) {
      logger?.warning('Failed to evict entry: ${entry.primaryFile.path}', e);
    }
  }

  if (bytesFreed > 0) {
    logger?.info(
        'Trim completed for ${directory.path}: freed $bytesFreed bytes.');
  }

  return bytesFreed;
}