cockpitWaitForStableFile function

Future<bool> cockpitWaitForStableFile(
  1. File file, {
  2. required Duration timeout,
  3. Duration pollInterval = const Duration(milliseconds: 100),
  4. Duration stableWindow = const Duration(milliseconds: 400),
})

Implementation

Future<bool> cockpitWaitForStableFile(
  File file, {
  required Duration timeout,
  Duration pollInterval = const Duration(milliseconds: 100),
  Duration stableWindow = const Duration(milliseconds: 400),
}) async {
  final deadline = DateTime.now().add(timeout);
  int? lastLength;
  DateTime? stableSince;

  while (DateTime.now().isBefore(deadline)) {
    if (file.existsSync() && file.lengthSync() > 0) {
      final currentLength = file.lengthSync();
      if (lastLength == currentLength) {
        stableSince ??= DateTime.now();
        if (DateTime.now().difference(stableSince) >= stableWindow) {
          return true;
        }
      } else {
        lastLength = currentLength;
        stableSince = DateTime.now();
      }
    }
    await Future<void>.delayed(pollInterval);
  }

  if (!file.existsSync() || file.lengthSync() <= 0) {
    return false;
  }
  return lastLength == file.lengthSync();
}