Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/tmpl-cli-core/src/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use time::OffsetDateTime;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum NoteError {
/// The id was not a positive integer.
#[error("invalid note id '{0}': expected a positive integer such as 1")]
#[error("invalid note id {0:?}: expected a positive integer such as 1")]
InvalidId(String),
/// The title was empty or only whitespace.
#[error("title is empty: pass some text, e.g. \"Buy milk\"")]
Expand All @@ -35,12 +35,12 @@ pub enum NoteError {
EmptyBody,
/// The tag had characters outside `a-z`, `0-9` and `-`, or a bad length.
#[error(
"invalid tag '{0}': use 1-{max} lowercase letters, digits or '-'",
"invalid tag {0:?}: use 1-{max} lowercase letters, digits or '-'",
max = Tag::MAX_CHARS
)]
InvalidTag(String),
/// The priority was not one of [`Priority::NAMES`].
#[error("invalid priority '{0}': expected one of low, normal, high")]
#[error("invalid priority {0:?}: expected one of low, normal, high")]
InvalidPriority(String),
}

Expand Down
36 changes: 28 additions & 8 deletions crates/tmpl-cli-core/src/store/fsio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,22 @@ impl LockGuard {
///
/// `label` says what the holder is doing; it is recorded with the pid and
/// time so a writer that times out can say who is in the way.
#[cfg_attr(
not(test),
expect(dead_code, reason = "unobserved lock helper used by fsio tests")
)]
pub(super) fn acquire(path: &Path, label: &str, wait: Duration) -> Result<Self> {
Self::acquire_observing(path, label, wait, || {})
}

/// Take the lock at `path`, invoking `on_contended` once if acquisition
/// encounters an active holder (`WouldBlock`).
pub(super) fn acquire_observing(
path: &Path,
label: &str,
wait: Duration,
on_contended: impl FnOnce(),
) -> Result<Self> {
// Never create or truncate through a link (STD-05 R7).
match fs::symlink_metadata(path) {
Ok(meta) => refuse_symlink(path, &meta)?,
Expand All @@ -271,18 +286,23 @@ impl LockGuard {
.open(path)
.map_err(|e| Error::io("open lock file", path, e))?;
let started = Instant::now();
let mut on_contended = Some(on_contended);
loop {
match file.try_lock() {
Ok(()) => break,
Err(TryLockError::WouldBlock) if started.elapsed() < wait => {
std::thread::sleep(LOCK_POLL);
}
Err(TryLockError::WouldBlock) => {
return Err(Error::Locked {
path: path.to_path_buf(),
holder: read_holder(&mut file),
waited_ms: started.elapsed().as_millis(),
});
if let Some(notify) = on_contended.take() {
notify();
}
if started.elapsed() < wait {
std::thread::sleep(LOCK_POLL);
} else {
return Err(Error::Locked {
path: path.to_path_buf(),
holder: read_holder(&mut file),
waited_ms: started.elapsed().as_millis(),
});
}
}
Err(TryLockError::Error(e)) => return Err(Error::io("lock", path, e)),
}
Expand Down
24 changes: 22 additions & 2 deletions crates/tmpl-cli-core/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ use format::StoreDocument;
use fsio::LockGuard;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use time::OffsetDateTime;

Expand Down Expand Up @@ -68,6 +70,7 @@ pub struct Loaded<T> {
pub struct Store {
root: PathBuf,
lock_wait: Duration,
contended_lock_waits: Arc<AtomicUsize>,
}

impl Store {
Expand All @@ -78,6 +81,7 @@ impl Store {
Self {
root: root.into(),
lock_wait: DEFAULT_LOCK_WAIT,
contended_lock_waits: Arc::new(AtomicUsize::new(0)),
}
}

Expand All @@ -88,6 +92,13 @@ impl Store {
self
}

/// Count of contended lock acquisitions observed through this store handle
/// (and clones of it), used by tests instead of timing lock deadlines.
#[must_use]
pub fn contended_lock_waits(&self) -> usize {
self.contended_lock_waits.load(Ordering::Relaxed)
}

/// The data directory.
#[must_use]
pub fn root(&self) -> &Path {
Expand Down Expand Up @@ -188,11 +199,20 @@ impl Store {
}

fn lock(&self, label: &str) -> Result<LockGuard> {
LockGuard::acquire(&self.root.join(LOCK_FILE), label, self.lock_wait)
LockGuard::acquire_observing(&self.root.join(LOCK_FILE), label, self.lock_wait, || {
self.contended_lock_waits.fetch_add(1, Ordering::Relaxed);
})
}

fn audit_lock(&self, label: &str) -> Result<LockGuard> {
LockGuard::acquire(&self.root.join(AUDIT_LOCK_FILE), label, self.lock_wait)
LockGuard::acquire_observing(
&self.root.join(AUDIT_LOCK_FILE),
label,
self.lock_wait,
|| {
self.contended_lock_waits.fetch_add(1, Ordering::Relaxed);
},
)
}

fn load(&self) -> Result<StoreDocument> {
Expand Down
18 changes: 9 additions & 9 deletions crates/tmpl-cli-core/src/store/tests/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,22 +59,21 @@ fn record_audit_appends_one_line_per_event_and_creates_the_directory() {
#[test]
fn record_audit_succeeds_while_the_store_lock_is_held() {
// Defect 1: a command that timed out on the store lock must still write
// its failure audit line without waiting a second lock deadline.
// its failure audit line without waiting on the store lock a second time.
let dir = super::private_tempdir();
let deadline = Duration::from_millis(80);
let store = Store::open(dir.path()).with_lock_wait(deadline);
let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO);
let _held =
LockGuard::acquire(&dir.path().join(".lock"), "test", Duration::from_secs(1)).unwrap();
let started = std::time::Instant::now();
let err = store
.add(new_note("blocked"), OffsetDateTime::UNIX_EPOCH)
.unwrap_err();
assert_eq!(err.code(), "store_locked");
assert_eq!(store.contended_lock_waits(), 1);
store.record_audit(&event("note add")).unwrap();
let elapsed = started.elapsed();
assert!(
elapsed < deadline * 2,
"add + record_audit waited more than one deadline: {elapsed:?}"
assert_eq!(
store.contended_lock_waits(),
1,
"record_audit must not contend on the held store lock"
);
let text = std::fs::read_to_string(store.audit_path()).unwrap();
assert_eq!(text.lines().count(), 1, "got {text:?}");
Expand All @@ -83,7 +82,7 @@ fn record_audit_succeeds_while_the_store_lock_is_held() {
#[test]
fn record_audit_waits_for_the_audit_lock() {
let dir = super::private_tempdir();
let store = Store::open(dir.path()).with_lock_wait(Duration::from_millis(60));
let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO);
let _held = LockGuard::acquire(
&dir.path().join(".audit.lock"),
"test",
Expand All @@ -92,6 +91,7 @@ fn record_audit_waits_for_the_audit_lock() {
.unwrap();
let err = store.record_audit(&event("note add")).unwrap_err();
assert!(matches!(err, Error::Locked { .. }), "got {err:?}");
assert_eq!(store.contended_lock_waits(), 1);
assert!(!store.audit_path().exists());
}

Expand Down
14 changes: 6 additions & 8 deletions crates/tmpl-cli/src/commands/tests/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ fn lock_timeout_audited_command_waits_one_deadline_and_records_one_failure_line(
use crate::app::Context;
use crate::commands::run_with;
use std::fs::OpenOptions;
use std::time::{Duration, Instant};
use std::time::Duration;
use tmpl_cli_core::Store;

let dir = tempfile::tempdir().unwrap();
Expand All @@ -104,28 +104,26 @@ fn lock_timeout_audited_command_waits_one_deadline_and_records_one_failure_line(
.unwrap();
lock_file.try_lock().unwrap();

let deadline = Duration::from_millis(80);
let store = Store::open(dir.path()).with_lock_wait(deadline);
let store = Store::open(dir.path()).with_lock_wait(Duration::ZERO);
let ctx = Context::with_store(store, Some(String::from("alice")));
let cmd = command(&["tmpl-cli", "note", "add", "blocked"]);

let started = Instant::now();
let mut audit_written_before_finish = false;
let err_code = run_with(cmd, &ctx, |outcome| {
// The audit guard must not have dropped before finish runs.
audit_written_before_finish = ctx.store().audit_path().exists();
outcome.unwrap_err().code()
});
let elapsed = started.elapsed();

assert_eq!(err_code, "store_locked");
assert!(
!audit_written_before_finish,
"finish must run before the audit guard drops"
);
assert!(
elapsed >= deadline && elapsed < deadline * 2,
"expected roughly one deadline ({deadline:?}), took {elapsed:?}"
assert_eq!(
ctx.store().contended_lock_waits(),
1,
"failing audited command must wait on the store lock once, not twice"
);

let audit_raw = std::fs::read_to_string(ctx.store().audit_path()).unwrap();
Expand Down
13 changes: 9 additions & 4 deletions crates/tmpl-cli/src/output/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ pub(crate) fn finish_parse_error(err: &clap::Error, args: &[OsString]) -> ExitCo
let message = first.strip_prefix("error: ").unwrap_or(first);
write_json_error(message, "usage_error");
} else {
let _ = io::stderr().lock().write_all(rendered.as_bytes());
let sanitized = render::sanitize_for_display(&rendered);
let _ = io::stderr().lock().write_all(sanitized.as_bytes());
}
ExitCode::from(code)
}
Expand All @@ -108,10 +109,10 @@ fn emit(sink: &Sink, output: &Output) -> io::Result<()> {
// never fail a command whose payload is fine.
let mut err = io::stderr().lock();
for warning in warnings {
let _ = writeln!(err, "warning: {warning}");
let _ = writeln!(err, "warning: {}", render::sanitize_for_display(warning));
}
if let Some(notice) = notice {
let _ = writeln!(err, "{notice}");
let _ = writeln!(err, "{}", render::sanitize_for_display(notice));
}
}
let mut out = io::stdout().lock();
Expand Down Expand Up @@ -139,7 +140,11 @@ fn report_error(json: bool, err: &CliError) {
if json {
write_json_error(&message, err.code());
} else {
let _ = writeln!(io::stderr().lock(), "error: {message}");
let _ = writeln!(
io::stderr().lock(),
"error: {}",
render::sanitize_for_display(&message)
);
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/tmpl-cli/src/output/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ pub(crate) fn note_detail(out: &mut dyn Write, sink: &Sink, note: &NotePayload)
}

/// Neutralize control characters other than newline and tab so terminal
/// escape sequences and carriage returns cannot reach stdout raw.
fn sanitize_for_display(text: &str) -> String {
/// escape sequences and carriage returns cannot reach stdout or stderr raw.
pub(super) fn sanitize_for_display(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
Expand Down
47 changes: 47 additions & 0 deletions crates/tmpl-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,53 @@ fn bad_records_warn_on_reads_fail_on_show_and_refuse_writes_without_touching_sto
);
}

#[test]
fn bad_record_control_characters_are_escaped_on_stderr() {
let fx = Fixture::new();
std::fs::create_dir_all(fx.root()).unwrap();
support::make_private(&fx.root());
let store_path = fx.root().join("notes.json");
let raw = r#"{
"format": 1,
"notes": [
{"id": 1, "title": "Good note", "body": null, "tags": ["home"], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"},
{"id": 2, "title": "Bad tag", "body": null, "tags": ["bad\u001b[31mtag"], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"},
{"id": 3, "title": "Bad\u001b[31mtitle", "body": null, "tags": [], "priority": "normal", "created_at": "2026-01-02T03:04:05Z"},
{"id": 4, "title": "Bad priority", "body": null, "tags": [], "priority": "bad\u001b[31mprio", "created_at": "2026-01-02T03:04:05Z"}
]
}"#;
std::fs::write(&store_path, raw).unwrap();
support::make_private(&store_path);

let assert_clean_stderr = |args: &[&str], expected_code: i32| {
let out = fx.run(args);
assert_eq!(out.status.code(), Some(expected_code), "{args:?}");
let bad_byte = out
.stderr
.iter()
.copied()
.find(|&b| b < 0x20 && b != b'\n' && b != b'\t');
assert_eq!(
bad_byte,
None,
"{args:?} emitted raw control byte in stderr: {:?}",
String::from_utf8_lossy(&out.stderr)
);
out
};

let list_plain = assert_clean_stderr(&["note", "list"], 0);
assert!(text(&list_plain.stderr).contains("warning:"));
assert_clean_stderr(&["note", "list", "--json"], 0);
assert_clean_stderr(&["note", "add", "Should not write"], 1);
assert_clean_stderr(&["note", "add", "Should not write", "--json"], 1);
assert_clean_stderr(&["note", "show", "2"], 1);
assert_clean_stderr(&["note", "show", "3"], 1);
assert_clean_stderr(&["note", "show", "4"], 1);
assert_clean_stderr(&["note", "show", "bad\x1bid"], 2);
assert_clean_stderr(&["note", "add", "Bad arg", "--tag", "bad\x1btag"], 2);
}

#[test]
fn help_states_defaults_for_tag_and_json() {
let fx = Fixture::new();
Expand Down
Loading