cleanupOutbox method

Future<void> cleanupOutbox()

Cleanup expired or over-attempted outbox entries TTL: 48 hours, Max attempts: 100

Implementation

Future<void> cleanupOutbox() async {
  try {
    const maxTtlMs = 48 * 60 * 60 * 1000; // 48 hours
    const maxAttempts = 100;
    final now = DateTime.now();
    final cutoffTime = now.subtract(Duration(milliseconds: maxTtlMs));

    final expired = realm.query<SyncOutboxPatch>(
      'uid == \$0 AND collection == \$1 AND (createdAt < \$2 OR attempts >= \$3)',
      [userId, collectionName, cutoffTime, maxAttempts],
    );

    if (expired.isNotEmpty) {
      realm.write(() {
        for (final entry in expired) {
          AppLogger.log(
            'Outbox cleanup: removing ${entry.entityId} (age: ${now.difference(entry.createdAt ?? now).inHours}h, attempts: ${entry.attempts})',
          );
          realm.delete(entry);
        }
      });
      AppLogger.log(
        'Outbox cleanup: removed ${expired.length} expired entries for $collectionName',
      );
    }
  } catch (e) {
    AppLogger.log('Outbox cleanup failed: $e');
  }
}