backupToFile method

Future<void> backupToFile(
  1. String path
)

Writes a consistent copy of this container to path atomically.

The copy is built in a mode-restricted sibling temp file, flushed, and renamed over path (with a parent-directory fsync on POSIX), preserving the source container's POSIX permission bits when backed by IoStorageBackend. Safe while other processes keep committing.

Implementation

Future<void> backupToFile(String path) async {
  if (isClosed) {
    throw const WalPackClosedException();
  }
  int? sourceMode;
  if (backend case final IoStorageBackend io) {
    if (canonicalizePath(io.path) == canonicalizePath(path)) {
      throw ArgumentError.value(path, 'path', 'Cannot back up onto itself');
    }
    sourceMode = readPermissionBits(resolveReplaceTarget(io.path));
  } else {
    sourceMode = readPermissionBits(path);
  }

  // Unique per call so concurrent backups to one path never share a temp.
  final parent = File(path).parent;
  if (!parent.existsSync()) {
    parent.createSync(recursive: true);
  }
  final tempPath = '$path.backup.$pid.${_backupCounter++}.tmp';
  final tempFile = File(tempPath);
  PosixFs.createPrivateTempFile(tempPath, mode: sourceMode);

  final dest = await IoStorageBackend.open(
    tempPath,
    createIfMissing: true,
    readOnly: false,
    keepHandleOpen: true,
  );
  // Only the final rename needs a durable directory entry.
  dest.disableInitialDirectorySync();

  var swapped = false;
  try {
    await copyTo(dest);
    await dest.close();
    if (sourceMode != null) {
      PosixFs.chmod(tempPath, sourceMode);
    }
    await tempFile.rename(path);
    swapped = true;
    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.
    }
    if (!swapped) {
      try {
        if (tempFile.existsSync()) {
          tempFile.deleteSync();
        }
      } on Object {
        // Best-effort cleanup.
      }
    }
    rethrow;
  }
}