backupToFile method

Future<void> backupToFile(
  1. String path
)

Writes a consistent copy of this container to path atomically.

The copy is built in a sibling temp file, flushed, and renamed over path (with a parent-directory fsync on POSIX), so path always holds either the previous file or a complete backup. Safe while other processes keep committing.

Implementation

Future<void> backupToFile(String path) async {
  if (isClosed) {
    throw const WalPackClosedException();
  }
  if (backend case final IoStorageBackend io
      when _canonicalizePath(io.path) == _canonicalizePath(path)) {
    throw ArgumentError.value(path, 'path', 'Cannot back up onto itself');
  }
  // Unique per call so concurrent backups to one path never share a temp.
  final tempPath = '$path.backup.$pid.${_backupCounter++}.tmp';
  final tempFile = File(tempPath);
  if (tempFile.existsSync()) {
    tempFile.deleteSync();
  }
  final dest = await IoStorageBackend.open(
    tempPath,
    createIfMissing: true,
    readOnly: false,
    keepHandleOpen: true,
  );
  // Only the final rename needs a durable directory entry.
  dest._needsDirectorySync = false;
  try {
    await copyTo(dest);
    await dest.close();
    await tempFile.rename(path);
    await PosixFs.syncDirectoryAsync(File(path).absolute.parent.path);
  } on Object {
    try {
      await dest.close();
    } on Object {
      // Never let cleanup errors hide the original failure or the temp.
    }
    try {
      if (tempFile.existsSync()) {
        tempFile.deleteSync();
      }
    } on Object {
      // Best-effort cleanup.
    }
    rethrow;
  }
}