brokkr-ctl: delete ChangeGate, refuse hard-linked stores, pin the survivors
The store lock removed the failure the stat gate compensated, so wait reads each poll. A store with more than one hard link is refused (unix nlink; windows via GetFileInformationByHandle, windows-sys already in the lock). Tests pin the 86400 s cap, the receipt-key prefix and -h as a flag; the help test finds the dispatch table by its own line after live-2 added other *ACTIONS tuples. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8f5a660964
commit
4510dcc45b
4 changed files with 69 additions and 54 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -57,6 +57,7 @@ dependencies = [
|
|||
"serde_json",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -11,5 +11,8 @@ rmp-serde = "1.3"
|
|||
serde_json = "1"
|
||||
uuid = { version = "1", features = ["v7"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
|
|
|||
|
|
@ -18,8 +18,6 @@ const RESERVED: [&str; 5] = ["schema", "commandId", "action", "requestedBy", "no
|
|||
const DEFAULT_TIMEOUT_SECS: u64 = 60;
|
||||
const POLL: Duration = Duration::from_millis(200);
|
||||
const MAX_TIMEOUT: Duration = Duration::from_secs(24 * 3600);
|
||||
/// Even when the file looks unchanged, read it again this often.
|
||||
const RECHECK: Duration = Duration::from_secs(5);
|
||||
|
||||
/// What a receipt (or its absence) says; the exit code derives from it and from nothing else.
|
||||
pub enum Outcome {
|
||||
|
|
@ -162,9 +160,35 @@ fn open_store(options: &Options) -> Result<SingleFileMessagePackBackingStore> {
|
|||
if meta.file_type().is_symlink() || !meta.is_file() {
|
||||
bail!("store {} must be the add-on's regular file, not a link", path.display());
|
||||
}
|
||||
// The same swap would leave a second name on the old bytes.
|
||||
if link_count(&path)? > 1 {
|
||||
bail!("store {} has more than one hard link; it must be the add-on's only name for the file", path.display());
|
||||
}
|
||||
Ok(SingleFileMessagePackBackingStore::new(path))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn link_count(path: &std::path::Path) -> Result<u64> {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
Ok(std::fs::metadata(path)?.nlink())
|
||||
}
|
||||
|
||||
/// std's `number_of_links` is unstable, so ask the handle.
|
||||
#[cfg(windows)]
|
||||
fn link_count(path: &std::path::Path) -> Result<u64> {
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle};
|
||||
let file = std::fs::File::open(path)?;
|
||||
let mut info = std::mem::MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::zeroed();
|
||||
// SAFETY: the handle is live for the call and `info` is a writable BY_HANDLE_FILE_INFORMATION.
|
||||
let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, info.as_mut_ptr()) };
|
||||
if ok == 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
// SAFETY: the call succeeded, so it filled the struct.
|
||||
Ok(u64::from(unsafe { info.assume_init() }.nNumberOfLinks))
|
||||
}
|
||||
|
||||
fn requested_by(options: &Options) -> Result<String> {
|
||||
let instance = std::env::var("EUREKA_INSTANCE").unwrap_or_default();
|
||||
let agent = options
|
||||
|
|
@ -244,16 +268,7 @@ fn wait_for_receipt(
|
|||
limit: Duration,
|
||||
) -> Result<i32> {
|
||||
let started = Instant::now();
|
||||
let mut gate = ChangeGate::new(store.path());
|
||||
loop {
|
||||
if !gate.should_read() {
|
||||
if started.elapsed() >= limit {
|
||||
println!("status: timeout");
|
||||
return Ok(Outcome::Timeout.code());
|
||||
}
|
||||
thread::sleep(POLL);
|
||||
continue;
|
||||
}
|
||||
if let Some(receipt) = read_receipt(store, id)? {
|
||||
print_fields(&receipt);
|
||||
let status = receipt.get("status").and_then(Value::as_str).unwrap_or("");
|
||||
|
|
@ -267,32 +282,6 @@ fn wait_for_receipt(
|
|||
}
|
||||
}
|
||||
|
||||
/// Polling must not hold the store: a read takes the shared lock and an open handle, and on
|
||||
/// Windows that can make the add-on's replace fail. So the file's stat is polled and the store
|
||||
/// is read only after it changed (and every RECHECK as a backstop).
|
||||
pub struct ChangeGate {
|
||||
path: PathBuf,
|
||||
seen: Option<(u64, Option<SystemTime>)>,
|
||||
last_read: Option<Instant>,
|
||||
}
|
||||
|
||||
impl ChangeGate {
|
||||
pub fn new(path: &std::path::Path) -> Self {
|
||||
Self { path: path.to_path_buf(), seen: None, last_read: None }
|
||||
}
|
||||
|
||||
pub fn should_read(&mut self) -> bool {
|
||||
let stamp = std::fs::metadata(&self.path).ok().map(|m| (m.len(), m.modified().ok()));
|
||||
let stale = self.last_read.is_none_or(|at| at.elapsed() >= RECHECK);
|
||||
if self.seen.is_none() || stamp != self.seen || stale {
|
||||
self.seen = stamp;
|
||||
self.last_read = Some(Instant::now());
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn receipts(store: &SingleFileMessagePackBackingStore, last: Option<usize>) -> Result<i32> {
|
||||
let mut found = Vec::new();
|
||||
for envelope in store.pull_all()? {
|
||||
|
|
@ -628,22 +617,6 @@ mod tests {
|
|||
assert!(build_intent("../x", "abc", "a/b", "", &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gate_reads_first_then_only_after_the_file_changes() {
|
||||
let dir = std::env::temp_dir().join(format!("brokkr-gate-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("s.ccmp");
|
||||
std::fs::write(&file, b"one").unwrap();
|
||||
let mut gate = ChangeGate::new(&file);
|
||||
assert!(gate.should_read());
|
||||
assert!(!gate.should_read());
|
||||
assert!(!gate.should_read());
|
||||
std::fs::write(&file, b"three").unwrap();
|
||||
assert!(gate.should_read());
|
||||
assert!(!gate.should_read());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statuses_map_to_exit_codes() {
|
||||
for (status, code) in [("accepted", 0), ("denied", 2), ("failed", 2), ("stopped", 3), ("weird", 2)] {
|
||||
|
|
|
|||
|
|
@ -240,6 +240,43 @@ fn a_symlinked_store_is_refused() {
|
|||
assert_eq!(ctl(&link, &["receipts"], None).status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hard_linked_store_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[("a", "accepted")]);
|
||||
let link = dir.path().join("second-name.ccmp");
|
||||
std::fs::hard_link(&path, &link).unwrap();
|
||||
let before = std::fs::read(&path).unwrap();
|
||||
for name in [&path, &link] {
|
||||
let output = ctl(name, &["send", "createObject", "--agent", "hands", "--no-wait"], Some("nibu"));
|
||||
assert_eq!(output.status.code(), Some(1), "{}", name.display());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("hard link"));
|
||||
}
|
||||
assert_eq!(std::fs::read(&path).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_timeout_cap_is_one_day_inclusive() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[]);
|
||||
// --help returns after parsing, so a legal timeout does not wait
|
||||
let at_cap = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400"], None);
|
||||
assert_eq!(at_cap.status.code(), Some(0));
|
||||
let over = ctl(&path, &["send", "createObject", "--help", "--timeout", "86400.5"], None);
|
||||
assert_eq!(over.status.code(), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_help_is_a_flag() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = store_with_receipts(dir.path(), &[]);
|
||||
let output = ctl(&path, &["send", "createObject", "-h"], Some("nibu"));
|
||||
assert_eq!(output.status.code(), Some(0));
|
||||
assert!(stdout(&output).contains("actions:"));
|
||||
let group = ctl(&path, &["receipts", "-h"], None);
|
||||
assert!(stdout(&group).contains("brokkr-ctl blender:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipts_only_come_from_the_receipt_keys_and_type() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
@ -250,6 +287,7 @@ fn receipts_only_come_from_the_receipt_keys_and_type() {
|
|||
&[
|
||||
envelope_at(RECEIPT, "elsewhere/fake", &fake),
|
||||
envelope_at(INTENT, "blender/receipts/wrongtype", &fake),
|
||||
envelope_at(RECEIPT, "nested/blender/receipts/fake2", &fake),
|
||||
],
|
||||
);
|
||||
let listed = stdout(&ctl(&path, &["receipts"], None));
|
||||
|
|
@ -306,7 +344,7 @@ fn help_names_every_dispatched_action_and_only_fields_the_addon_mentions() {
|
|||
.filter_map(|rest| rest.split('"').next())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let actions_line = source.lines().find(|l| l.contains("ACTIONS = (\"")).unwrap();
|
||||
let actions_line = source.lines().find(|l| l.trim_start().starts_with("ACTIONS = (\"")).unwrap();
|
||||
dispatched.extend(actions_line.split('"').skip(1).step_by(2).map(String::from));
|
||||
assert!(dispatched.len() >= 20, "{dispatched:?}");
|
||||
let listed: Vec<&str> = help.lines().filter_map(|l| l.strip_prefix(" ")).filter(|l| !l.starts_with(' ')).collect();
|
||||
|
|
|
|||
Loading…
Reference in a new issue