Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5aac40da5d | |||
| 5322d0dd5c | |||
| 6a9dfac1ac | |||
| 51bfd34d74 | |||
| 485dc07288 | |||
| 52b0c53846 | |||
| 736ca0c4c2 | |||
| 6366a44bc4 |
@@ -89,19 +89,16 @@ jobs:
|
||||
rustup component add rustfmt clippy
|
||||
cargo --version && cargo fmt --version && cargo clippy --version
|
||||
|
||||
# Keyed on Cargo.lock: dependency builds are reused until a dep actually
|
||||
# changes. A cache miss only makes the run slower, never wrong.
|
||||
- name: Cache cargo registry and build dir
|
||||
# Dependency builds are reused until a dep actually changes; a cache miss
|
||||
# only makes the run slower, never wrong. rust-cache rather than a plain
|
||||
# actions/cache of target/: it strips this crate's own artifacts and
|
||||
# anything stale before saving, and saves only on a miss. The plain cache
|
||||
# restored the previous target/ and re-saved all of it under every new
|
||||
# Cargo.lock, so each entry carried every older build and the runner's
|
||||
# cache grew without bound.
|
||||
- name: Cache cargo registry and dependency builds
|
||||
if: ${{ steps.detect.outputs.crate == 'true' }}
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-
|
||||
uses: Swatinem/rust-cache@v2
|
||||
|
||||
# Cheapest gate first — parses only, no compile, so a formatting slip
|
||||
# fails in seconds instead of after a full build.
|
||||
|
||||
13
src/cli.rs
13
src/cli.rs
@@ -56,7 +56,7 @@ pub enum PatchChoice {
|
||||
No,
|
||||
}
|
||||
|
||||
/// Which game's shard side this run is about (docs/modules/rust/PLAN.md §34.2.3). ServUO is the
|
||||
/// Which game this run sets up (docs/modules/rust/PLAN.md §34.2.3). ServUO is the
|
||||
/// default, so every command line written before Rust existed means exactly what it meant.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Game {
|
||||
@@ -94,7 +94,8 @@ pub struct Cli {
|
||||
pub patches_unsupported_servuo: bool,
|
||||
/// `--host <name>`: the hostname to print in the website URLs.
|
||||
pub host: Option<String>,
|
||||
/// `--site-url <url>`: the site's base URL, for the Admin → Shard (uo-link) link.
|
||||
/// `--site-url <url>`: the site's base URL, printed as a link to the admin page that takes
|
||||
/// the values.
|
||||
pub site_url: Option<String>,
|
||||
/// `--yes`: assume the default answer to every prompt.
|
||||
pub assume_yes: bool,
|
||||
@@ -128,7 +129,7 @@ impl Default for Cli {
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
Runic Gateway installer — connects a ServUO shard, or Rust servers, to a Runic
|
||||
Runic Gateway installer — connects a ServUO server, or Rust servers, to a Runic
|
||||
Gateway website.
|
||||
|
||||
Usage: runicgateway-installer <COMMAND> [OPTIONS]
|
||||
@@ -144,7 +145,7 @@ Commands:
|
||||
removes only its own plugin file and keeps the plugin config.
|
||||
|
||||
Options:
|
||||
--game <servuo|rust> Which game's shard side. Default servuo.
|
||||
--game <servuo|rust> Which game this run sets up. Default servuo.
|
||||
--verify install, update. Dry run: report every
|
||||
change that would be made, write nothing.
|
||||
--servuo <PATH> install, doctor, update. The ServUO root,
|
||||
@@ -161,7 +162,7 @@ Options:
|
||||
--host <NAME> install. The hostname to print in the
|
||||
website URLs.
|
||||
--site-url <URL> install. Your site's base URL, for the
|
||||
Admin → Shard (uo-link) link.
|
||||
admin page link it prints at the end.
|
||||
--yes Assume the default answer to every prompt.
|
||||
On uninstall it means yes: that prompt
|
||||
defaults to no, and typing `uninstall
|
||||
@@ -194,7 +195,7 @@ Environment:
|
||||
set it.
|
||||
|
||||
The installer never contacts your website, never deletes anything from your
|
||||
ServUO tree, and never starts or stops your shard.
|
||||
ServUO tree, and never starts or stops your game server.
|
||||
";
|
||||
|
||||
/// Parses arguments **without** the program name.
|
||||
|
||||
@@ -651,7 +651,12 @@ fn protocol_row(
|
||||
/// than a `✗`: reporting a stopped shard as a failure would train operators to ignore this line,
|
||||
/// which is the one line worth reading.
|
||||
fn shard_row(root: Result<&ServUoRoot, &anyhow::Error>, health: Option<&Health>) -> Row {
|
||||
let running = root.ok().and_then(|r| servuo::find_running(&r.path));
|
||||
// Only a certain match: an unreadable-cwd process may be a different shard, and "running but
|
||||
// has not dialed in" about the wrong shard would send the operator after the wrong problem.
|
||||
let running = root
|
||||
.ok()
|
||||
.and_then(|r| servuo::find_running(&r.path))
|
||||
.filter(|s| s.certain);
|
||||
|
||||
match (health.and_then(|h| h.plugin_connected), running) {
|
||||
(Some(true), _) => {
|
||||
|
||||
289
src/servuo.rs
289
src/servuo.rs
@@ -180,6 +180,21 @@ pub(crate) fn strip_extended_prefix(path: PathBuf) -> PathBuf {
|
||||
pub struct RunningShard {
|
||||
pub pid: u32,
|
||||
pub detail: String,
|
||||
/// `false` when the process names a *relative* `ServUO.exe` and its working directory could not
|
||||
/// be read (another user's process, installer not run as root), so it may be a different
|
||||
/// shard. Install/update still refuse — failing closed is the point — but say why.
|
||||
pub certain: bool,
|
||||
}
|
||||
|
||||
/// How one process relates to the tree being deployed into. See [`classify`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Verdict {
|
||||
/// Not a ServUO process, or one running out of a different tree.
|
||||
No,
|
||||
/// A ServUO process running out of this tree.
|
||||
Shard,
|
||||
/// A ServUO process launched with a relative path whose working directory could not be read.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Refuses to proceed if a shard is running out of `root`.
|
||||
@@ -190,20 +205,31 @@ pub struct RunningShard {
|
||||
/// running" for a shard that is very much running — the one wrong answer that corrupts a live
|
||||
/// `Scripts.dll`. Scoping to processes under *this* root also means a second shard on the same host
|
||||
/// does not block a deploy into the first.
|
||||
///
|
||||
/// Every launch shape is covered (installer#47): `ServUO.exe` run directly (Windows),
|
||||
/// `mono /abs/path/ServUO.exe`, and — the common one under systemd or tmux — `mono ServUO.exe`
|
||||
/// started from inside the root, where the root appears only in the process's working directory.
|
||||
/// The decision itself is [`classify`]; this function only gathers what it needs.
|
||||
pub fn find_running(root: &Path) -> Option<RunningShard> {
|
||||
use sysinfo::{ProcessRefreshKind, RefreshKind, System};
|
||||
|
||||
let system = System::new_with_specifics(
|
||||
RefreshKind::nothing().with_processes(ProcessRefreshKind::everything()),
|
||||
);
|
||||
let root_str = normalize_for_match(&root.to_string_lossy());
|
||||
|
||||
let mut unknown = None;
|
||||
for (pid, process) in system.processes() {
|
||||
// Own process first: the installer may well have been copied into the server root, and
|
||||
// matching itself would make every run refuse to start.
|
||||
if pid.as_u32() == std::process::id() {
|
||||
continue;
|
||||
}
|
||||
// On Linux the scan lists every thread (TID) beside its process (TGID). They share the
|
||||
// process's exe/cmd/cwd, so a thread can match first and the refusal names a pid that
|
||||
// `kill` cannot use (installer#45 item 5). Threads are skipped; the process itself matches.
|
||||
if process.thread_kind().is_some() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let exe = process
|
||||
.exe()
|
||||
@@ -215,19 +241,101 @@ pub fn find_running(root: &Path) -> Option<RunningShard> {
|
||||
.map(|a| a.to_string_lossy().to_string())
|
||||
.collect();
|
||||
|
||||
let hay = normalize_for_match(&format!("{exe} {}", args.join(" ")));
|
||||
// Two conditions, both required: something in this process names the tree, AND it names
|
||||
// the ServUO assembly. Either alone over-matches — an editor with the path open, or a
|
||||
// different shard's ServUO.exe.
|
||||
if hay.contains(&root_str) && hay.contains("servuo.exe") {
|
||||
let detail = if exe.is_empty() { args.join(" ") } else { exe };
|
||||
return Some(RunningShard {
|
||||
let found = |certain| {
|
||||
let detail = if exe.is_empty() {
|
||||
args.join(" ")
|
||||
} else {
|
||||
exe.clone()
|
||||
};
|
||||
RunningShard {
|
||||
pid: pid.as_u32(),
|
||||
detail,
|
||||
});
|
||||
certain,
|
||||
}
|
||||
};
|
||||
match classify(root, &exe, &args, process.cwd()) {
|
||||
Verdict::Shard => return Some(found(true)),
|
||||
// Kept looking: a certain match elsewhere is the better report.
|
||||
Verdict::Unknown if unknown.is_none() => unknown = Some(found(false)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
unknown
|
||||
}
|
||||
|
||||
/// Decides whether one process is a ServUO running out of `root`. Pure, so every launch shape is
|
||||
/// unit-tested without spawning anything.
|
||||
///
|
||||
/// Something in the process must name the ServUO assembly — otherwise an editor or a shell sitting
|
||||
/// in the root would match — and that assembly must resolve into this tree, otherwise a second
|
||||
/// shard on the host would block this one.
|
||||
fn classify(root: &Path, exe: &str, args: &[String], cwd: Option<&Path>) -> Verdict {
|
||||
let root_str = normalize_for_match(&root.to_string_lossy());
|
||||
let names_assembly = |s: &str| normalize_for_match(s).ends_with("servuo.exe");
|
||||
|
||||
// ServUO.exe is itself the executable (Windows): its path settles it, whatever argv says.
|
||||
if names_assembly(exe) {
|
||||
return if in_tree(Path::new(exe), &root_str) {
|
||||
Verdict::Shard
|
||||
} else {
|
||||
Verdict::No
|
||||
};
|
||||
}
|
||||
|
||||
// The original substring rule, kept so nothing it caught is lost: the tree and the assembly
|
||||
// both named somewhere in the command line (`mono /opt/ServUO/ServUO.exe`, or an option of
|
||||
// the form `--assembly=/opt/ServUO/ServUO.exe`).
|
||||
let hay = normalize_for_match(&format!("{exe} {}", args.join(" ")));
|
||||
if !hay.contains("servuo.exe") {
|
||||
return Verdict::No;
|
||||
}
|
||||
if hay.contains(&root_str) {
|
||||
return Verdict::Shard;
|
||||
}
|
||||
|
||||
// Hosted (`mono` / `dotnet`) with the assembly named relatively: resolve it against the
|
||||
// process's working directory. `mono ServUO.exe` from the root and `mono ServUO/ServUO.exe`
|
||||
// from its parent both land here.
|
||||
let mut verdict = Verdict::No;
|
||||
for arg in args.iter().filter(|a| names_assembly(a)) {
|
||||
let path = Path::new(arg);
|
||||
let resolved = if path.has_root() {
|
||||
path.to_path_buf()
|
||||
} else if let Some(cwd) = cwd {
|
||||
cwd.join(path)
|
||||
} else {
|
||||
// Unreadable cwd: cannot rule this tree out. Fail closed (decided 2026-11-27).
|
||||
verdict = Verdict::Unknown;
|
||||
continue;
|
||||
};
|
||||
if in_tree(&resolved, &root_str) {
|
||||
return Verdict::Shard;
|
||||
}
|
||||
}
|
||||
verdict
|
||||
}
|
||||
|
||||
/// True when `path` (lexically normalized: `.` dropped, `..` applied) lies inside the tree whose
|
||||
/// normalized path is `root_str`. A component-wise prefix, so `/opt/ServUO2` is not inside
|
||||
/// `/opt/ServUO`.
|
||||
fn in_tree(path: &Path, root_str: &str) -> bool {
|
||||
use std::path::Component;
|
||||
|
||||
let mut clean = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
clean.pop();
|
||||
}
|
||||
other => clean.push(other.as_os_str()),
|
||||
}
|
||||
}
|
||||
let path_str = normalize_for_match(&clean.to_string_lossy());
|
||||
let root_str = root_str.trim_end_matches('/');
|
||||
path_str
|
||||
.strip_prefix(root_str)
|
||||
.is_some_and(|rest| rest.starts_with('/'))
|
||||
}
|
||||
|
||||
/// Lower-cases and unifies separators so a Windows path compares equal however it was spelled.
|
||||
@@ -238,6 +346,18 @@ fn normalize_for_match(s: &str) -> String {
|
||||
/// Builds the refusal message. Separate from [`find_running`] so the wording is testable and so
|
||||
/// callers cannot accidentally soften it.
|
||||
pub fn running_error(root: &Path, shard: &RunningShard) -> anyhow::Error {
|
||||
if !shard.certain {
|
||||
return anyhow::anyhow!(
|
||||
"A ServUO process is running (pid {} — {}) and its working directory cannot be read, \
|
||||
so the installer cannot rule out that it is running from {}.\n\
|
||||
Stop it, or re-run the installer as root (sudo) so it can check. ServUO.exe holds \
|
||||
Scripts.dll open and rewrites Saves/ on exit, so deploying underneath a live shard \
|
||||
corrupts one or both. This is not overridable.",
|
||||
shard.pid,
|
||||
shard.detail,
|
||||
root.display()
|
||||
);
|
||||
}
|
||||
anyhow::anyhow!(
|
||||
"ServUO is running from {} (pid {} — {}).\n\
|
||||
Stop the shard before installing. ServUO.exe holds Scripts.dll open and rewrites Saves/ \
|
||||
@@ -263,6 +383,16 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::util::TempDir;
|
||||
|
||||
/// Held by every test that scans the real process table. The live-launch test's child names
|
||||
/// `ServUO.exe`; caught mid-exit by a parallel scan (cmdline read, cwd already gone) it is an
|
||||
/// `Unknown` match, and the empty-tree test would report it as a shard.
|
||||
static PROCESS_TABLE: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn process_table() -> std::sync::MutexGuard<'static, ()> {
|
||||
// A failed test poisons the lock; the next one still needs it.
|
||||
PROCESS_TABLE.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn fake_root(dir: &Path) {
|
||||
fs::create_dir_all(dir.join("Scripts")).unwrap();
|
||||
fs::create_dir_all(dir.join("Config")).unwrap();
|
||||
@@ -383,6 +513,7 @@ mod tests {
|
||||
let shard = RunningShard {
|
||||
pid: 4242,
|
||||
detail: "/opt/ServUO/ServUO.exe".into(),
|
||||
certain: true,
|
||||
};
|
||||
let msg = running_error(Path::new("/opt/ServUO"), &shard).to_string();
|
||||
assert!(msg.contains("4242"), "{msg}");
|
||||
@@ -390,6 +521,143 @@ mod tests {
|
||||
assert!(msg.contains("not overridable"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uncertain_refusal_says_it_could_not_check_and_still_offers_no_override() {
|
||||
let shard = RunningShard {
|
||||
pid: 4242,
|
||||
detail: "mono ServUO.exe".into(),
|
||||
certain: false,
|
||||
};
|
||||
let msg = running_error(Path::new("/opt/ServUO"), &shard).to_string();
|
||||
assert!(msg.contains("4242"), "{msg}");
|
||||
assert!(msg.contains("cannot be read"), "{msg}");
|
||||
assert!(msg.contains("sudo"), "{msg}");
|
||||
assert!(msg.contains("not overridable"), "{msg}");
|
||||
}
|
||||
|
||||
// installer#47 — every launch shape. Paths are written Unix-style; `Path` parses them on
|
||||
// Windows too (root dir, no prefix), so these run on both CI legs.
|
||||
const ROOT: &str = "/opt/ServUO";
|
||||
const MONO: &str = "/usr/bin/mono-sgen";
|
||||
|
||||
fn verdict(exe: &str, args: &[&str], cwd: Option<&str>) -> Verdict {
|
||||
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
|
||||
classify(Path::new(ROOT), exe, &args, cwd.map(Path::new))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_launch_from_the_root_is_the_shard() {
|
||||
// `cd /opt/ServUO && mono ServUO.exe` — systemd WorkingDirectory=, or tmux.
|
||||
let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/opt/ServUO"));
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
let v = verdict(
|
||||
MONO,
|
||||
&["mono", "--debug", "./ServUO.exe"],
|
||||
Some("/opt/ServUO"),
|
||||
);
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_launch_from_elsewhere_resolves_against_its_cwd() {
|
||||
let v = verdict(MONO, &["mono", "ServUO/ServUO.exe"], Some("/opt"));
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
let v = verdict(MONO, &["mono", "../ServUO/ServUO.exe"], Some("/opt/other"));
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_absolute_launch_is_the_shard_whatever_the_cwd() {
|
||||
let v = verdict(MONO, &["mono", "/opt/ServUO/ServUO.exe"], Some("/root"));
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
// exe unreadable (another user's process), cwd unreadable: argv alone still settles it.
|
||||
let v = verdict("", &["mono", "/opt/ServUO/ServUO.exe"], None);
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servuo_as_the_executable_is_decided_by_its_path() {
|
||||
// Windows: ServUO.exe runs natively; argv may be relative.
|
||||
let v = verdict("/opt/ServUO/ServUO.exe", &["ServUO.exe"], None);
|
||||
assert_eq!(v, Verdict::Shard);
|
||||
let v = verdict("/srv/Other/ServUO.exe", &["ServUO.exe"], None);
|
||||
assert_eq!(v, Verdict::No);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_shard_on_the_host_does_not_match() {
|
||||
let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/srv/Other"));
|
||||
assert_eq!(v, Verdict::No);
|
||||
let v = verdict(
|
||||
MONO,
|
||||
&["mono", "/srv/Other/ServUO.exe"],
|
||||
Some("/opt/ServUO"),
|
||||
);
|
||||
assert_eq!(v, Verdict::No);
|
||||
// A sibling whose name merely starts with the root's.
|
||||
let v = verdict(MONO, &["mono", "ServUO.exe"], Some("/opt/ServUO2"));
|
||||
assert_eq!(v, Verdict::No);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_that_does_not_name_the_assembly_never_matches() {
|
||||
// The tmux shell sitting in the root, or an editor with a file open.
|
||||
assert_eq!(
|
||||
verdict("/bin/bash", &["-bash"], Some("/opt/ServUO")),
|
||||
Verdict::No
|
||||
);
|
||||
let v = verdict(
|
||||
"/usr/bin/vim",
|
||||
&["vim", "Config/Server.cfg"],
|
||||
Some("/opt/ServUO"),
|
||||
);
|
||||
assert_eq!(v, Verdict::No);
|
||||
}
|
||||
|
||||
/// installer#47 end to end on a real `/proc`: a process started *inside* the root naming a
|
||||
/// relative `ServUO.exe` — the shape of `cd root && mono ServUO.exe` — is found, under its own
|
||||
/// pid (a thread id would not equal `child.id()`, installer#45 item 5). `sh -c '…' ServUO.exe`
|
||||
/// puts `ServUO.exe` in argv as `$0`. The shell waits in the `read` builtin on a stdin pipe the
|
||||
/// test holds open, so it never forks: a forked child is a copy of `sh` — same argv, same cwd —
|
||||
/// until it execs, a genuine second match the scan could report first (release run 3309).
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_live_relative_launch_from_the_root_is_found_by_its_pid() {
|
||||
let tmp = TempDir::new("rg-test-live-shard").unwrap();
|
||||
let root = tmp.path().join("srv");
|
||||
fake_root(&root);
|
||||
let root = fs::canonicalize(&root).unwrap();
|
||||
|
||||
let _table = process_table();
|
||||
let mut child = std::process::Command::new("sh")
|
||||
.args(["-c", "read x", "ServUO.exe"])
|
||||
.current_dir(&root)
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// The process is listed as soon as it exists, but give /proc a moment to fill cmdline.
|
||||
let mut found = None;
|
||||
for _ in 0..20 {
|
||||
found = find_running(&root);
|
||||
if found.is_some() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
|
||||
let shard = found.expect("a relative launch from the root must be detected");
|
||||
assert_eq!(shard.pid, child.id());
|
||||
assert!(shard.certain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relative_launch_with_an_unreadable_cwd_fails_closed() {
|
||||
let v = verdict("", &["mono", "ServUO.exe"], None);
|
||||
assert_eq!(v, Verdict::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_running_out_of_an_empty_tree() {
|
||||
// Also proves the scan does not match the test binary itself, which is the failure mode
|
||||
@@ -397,6 +665,7 @@ mod tests {
|
||||
let tmp = TempDir::new("rg-test-running").unwrap();
|
||||
let root = tmp.path().join("srv");
|
||||
fake_root(&root);
|
||||
let _table = process_table();
|
||||
assert!(find_running(&root).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
29
src/util.rs
29
src/util.rs
@@ -119,13 +119,22 @@ pub struct TempDir {
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
/// The name is pid + a per-process counter + the clock. The counter is what makes it unique:
|
||||
/// two threads can read the same nanosecond (parallel tests did, and deleted each other's
|
||||
/// files). `create_dir`, not `create_dir_all`, so a name that somehow exists is an error rather
|
||||
/// than a directory silently shared with its owner.
|
||||
pub fn new(prefix: &str) -> Result<Self> {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
let n = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let path = std::env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()));
|
||||
fs::create_dir_all(&path)
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("{prefix}-{}-{n}-{nanos}", std::process::id()));
|
||||
fs::create_dir(&path)
|
||||
.with_context(|| format!("cannot create scratch directory {}", path.display()))?;
|
||||
Ok(Self { path })
|
||||
}
|
||||
@@ -307,6 +316,22 @@ mod tests {
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_dirs_made_at_once_on_many_threads_never_share_a_path() {
|
||||
// Parallel tests with one prefix used to land in one directory when they read the same
|
||||
// nanosecond, and the first to finish deleted the other's files.
|
||||
let dirs: Vec<TempDir> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..16)
|
||||
.map(|_| s.spawn(|| TempDir::new("rg-test-unique").unwrap()))
|
||||
.collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
let mut paths: Vec<_> = dirs.iter().map(|d| d.path().to_path_buf()).collect();
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
assert_eq!(paths.len(), dirs.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_command_is_reported_with_what_it_printed() {
|
||||
// Both halves matter: the command to retype, and the reason it failed. stderr wins over
|
||||
|
||||
Reference in New Issue
Block a user