Promote Staged Files With fs::rename

Finalize an upload by renaming the staged temp file to its object key: same-directory rename is atomic and a missing stage maps to a clear NotFound error.

RustFile Upload

Code

rustsnippet
38 lines
use std::fs;
use std::io::ErrorKind;
use std::path::Path;

fn promote(staged: &Path, object: &Path) -> std::io::Result<()> {
    match fs::rename(staged, object) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == ErrorKind::NotFound => {
            // 暂存文件不存在:换成调用方能理解的错误再上抛
            Err(std::io::Error::new(
                ErrorKind::NotFound,
                format!("staged file missing: {}", staged.display()),
            ))
        }
        Err(e) => Err(e),
    }
}

fn main() {
    let dir = std::env::temp_dir().join("promote-demo");
    fs::create_dir_all(&dir).expect("create temp dir");
    let staged = dir.join("upload-42.part");
    let object = dir.join("upload-42.bin");

    // 成功路径:写入暂存 -> 原子改名
    fs::write(&staged, b"payload").expect("write staged");
    promote(&staged, &object).expect("promote");
    println!("promoted: {}", object.exists());

    // 失败路径:暂存文件已不在
    match promote(&staged, &object) {
        Ok(()) => println!("unexpected ok"),
        Err(e) => println!("failed: {e}"),
    }

    fs::remove_file(&object).ok();
    fs::remove_dir_all(&dir).ok();
}

The promote path and its one failure arm

promote(staged, object) wraps fs::rename in a match with three arms: Ok(()) => Ok(()), a guard arm Err(e) if e.kind() == ErrorKind::NotFound that rebuilds the error with a caller-facing message — format!("staged file missing: {}", staged.display()) — and a final Err(e) => Err(e) that forwards every other kind untouched. Same-directory rename is atomic, so a successful promote is a single filesystem operation, not copy-plus-delete.

What a run prints

The demo writes b"payload" to upload-42.part, promotes it to upload-42.bin, then calls promote a second time on the now-moved staged path:

promoted: true
failed: staged file missing: <temp-dir>/promote-demo/upload-42.part

The first line is object.exists() after the successful rename. The second comes from the failure arm: the staged file no longer exists, so fs::rename returns NotFound and the rebuilt error names the missing path (the prefix is std::env::temp_dir(), platform-dependent). The unexpected ok string lives in the second match’s Ok arm — a branch a normal run can never reach, since the staged file was consumed by the first rename.

The line that replaces the raw error

Err(std::io::Error::new(
    ErrorKind::NotFound,
    format!("staged file missing: {}", staged.display()),
))

Keeping ErrorKind::NotFound means a caller can still match on the kind; the rebuilt message only adds the staged path, which the raw OS error never carried.

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Promote Staged Files With fs::rename print when run?
Running the file directly is enough — expect labeled output lines such as `promoted:`, `unexpected ok`, `failed:`.