Skip to content

Commit 85deffa

Browse files
committed
Atomic storage writes
1 parent 9ab28a5 commit 85deffa

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

src/storage.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,11 +274,25 @@ where
274274
T: Serialize,
275275
{
276276
async fn write_to_file(&self, path: impl AsRef<Path> + Debug) -> eyre::Result<()> {
277+
let path = path.as_ref();
278+
279+
let temp_path = path.with_extension("tmp");
277280
let contents = serde_json::to_vec_pretty(self).wrap_err("failed to serialize to JSON")?;
278-
let mut file = File::create(path).await.wrap_err("failed to create file")?;
281+
282+
let mut file = File::create(&temp_path)
283+
.await
284+
.wrap_err("failed to create temp file")?;
285+
279286
file.write_all(&contents)
280287
.await
281-
.wrap_err("failed to write to file")?;
288+
.wrap_err("failed to write to temp file")?;
289+
290+
file.sync_all().await.wrap_err("failed to sync to disk")?;
291+
292+
tokio::fs::rename(&temp_path, path)
293+
.await
294+
.wrap_err("failed to rename temp file to target")?;
295+
282296
Ok(())
283297
}
284298
}

0 commit comments

Comments
 (0)