Skip to content

Commit

Permalink
internal: add lock for writing target/packages.json
Browse files Browse the repository at this point in the history
  • Loading branch information
Young-Flash committed Oct 23, 2024
1 parent 8c345fb commit e9da0de
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ log = "0.4.20"
env_logger = "0.10.0"
thiserror = "1.0"
test-log = "0.2"
fs4 = { version = "0.8.3", features = ["sync"] }
fs4 = { version = "0.10.0", features = ["sync"] }
ariadne = { version = "0.4.1", features = ["auto-color"] }
clap_complete = { version = "4.5.4" }
schemars = "0.8"
Expand Down
4 changes: 3 additions & 1 deletion crates/moonbuild/src/check/normal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

use anyhow::Context;

use moonutil::common::{MoonbuildOpt, MooncOpt};
use moonutil::common::{FileLock, MoonbuildOpt, MooncOpt};
use moonutil::module::{convert_mdb_to_json, ModuleDB, ModuleDBJSON};
use n2::load::State;
use std::io::BufWriter;
Expand All @@ -43,6 +43,8 @@ pub fn write_pkg_lst(module: &ModuleDB, target_dir: &Path) -> anyhow::Result<()>

let mj = convert_mdb_to_json(module);
let pkg_json = target_dir.join("packages.json");
// packages.json now placed in target/, should be protected for mutil-thread write
let _lock = FileLock::lock_on_file(&pkg_json)?;

// if the file exist and the old content is the same as the new content in `module`, don't rewrite it
// otherwise we create and write
Expand Down
21 changes: 20 additions & 1 deletion crates/moonutil/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::module::{MoonMod, MoonModJSON};
use crate::package::{convert_pkg_json_to_package, MoonPkg, MoonPkgJSON, Package};
use anyhow::{bail, Context};
use clap::ValueEnum;
use fs4::FileExt;
use fs4::fs_std::FileExt;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
Expand Down Expand Up @@ -682,6 +682,25 @@ impl FileLock {
}
}
}

pub fn lock_on_file(path: &std::path::Path) -> std::io::Result<Self> {
let file = match std::fs::File::create_new(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
std::fs::File::open(path).unwrap()
}
Err(e) => return Err(e),
};
match file.try_lock_exclusive() {
Ok(_) => Ok(FileLock { _file: file }),
Err(_) => {
println!("Blocking waiting for file lock {} ...", path.display());
file.lock_exclusive()
.map_err(|e| std::io::Error::new(e.kind(), "failed to lock target dir"))?;
Ok(FileLock { _file: file })
}
}
}
}

#[derive(Debug, Clone)]
Expand Down

0 comments on commit e9da0de

Please sign in to comment.