atomicReplace method
Atomically swaps the container's contents with a fresh backend built by
buildTemp.
Implementations should build the temp target cleanly, invoke flush(),
atomically replace the live backing store (e.g. rename), and rebind
subsequent operations to the new store.
Implementation
@override
Future<void> atomicReplace(
Future<void> Function(StorageBackend temp) buildTemp,
) async {
if (readOnly) {
throw const WalPackReadOnlyException();
}
if (_closed) {
throw StateError('IoStorageBackend ($path) is closed');
}
// Replace the real file behind a symlink instead of the link itself.
final targetPath = _resolveReplaceTarget(path);
_sweepStaleCompactionTemps(targetPath);
final originalMode = _readPermissionBits(targetPath);
final tempPath = '$targetPath.compact.$pid.${_tempCounter++}.tmp';
final tempFile = File(tempPath);
if (tempFile.existsSync()) {
tempFile.deleteSync();
}
final tempBackend = await IoStorageBackend.open(
tempPath,
createIfMissing: true,
readOnly: false,
ioMode: ioMode,
keepHandleOpen: true,
);
// The temp name never needs to be durable: only the rename below does.
tempBackend._needsDirectorySync = false;
try {
await buildTemp(tempBackend);
await tempBackend.flush();
await tempBackend.close();
if (originalMode != null) {
PosixFs.chmod(tempPath, originalMode);
}
final oldRaf = _raf;
_knownPos = -1;
if (Platform.isWindows || !keepHandleOpen) {
_raf = null;
if (oldRaf != null) {
await oldRaf.close();
}
await tempFile.rename(targetPath);
if (keepHandleOpen) {
_raf = await File(path).open(mode: FileMode.append);
}
} else {
await tempFile.rename(targetPath);
_raf = null;
if (oldRaf != null) {
await oldRaf.close();
}
_raf = await File(path).open(mode: FileMode.append);
}
// Make the rename itself durable before reporting success.
final dir = File(targetPath).absolute.parent.path;
if (ioMode == .sync) {
PosixFs.syncDirectory(dir);
} else {
await PosixFs.syncDirectoryAsync(dir);
}
_needsDirectorySync = false;
} on Object {
_knownPos = -1;
try {
if (!tempBackend._closed) {
await tempBackend.close();
}
} on Object {
// Ignore secondary cleanup error.
}
try {
if (tempFile.existsSync()) {
tempFile.deleteSync();
}
} on Object {
// Ignore secondary cleanup error.
}
rethrow;
}
}