use std::io::Write;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
pub const SOCK_ENV: &str = "CROFT_VIEW_SOCK";
pub static SOCK_PATH: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ViewRequest {
pub path: Vec<u8>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub probe: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum ViewReply {
Ok,
Err { message: String },
}
impl ViewRequest {
pub fn new(path: &Path) -> Self {
use std::os::unix::ffi::OsStrExt;
Self {
path: path.as_os_str().as_bytes().to_vec(),
probe: false,
}
}
pub fn probe(path: &Path) -> Self {
Self {
probe: true,
..Self::new(path)
}
}
pub fn to_path(&self) -> PathBuf {
use std::os::unix::ffi::OsStrExt;
PathBuf::from(std::ffi::OsStr::from_bytes(&self.path))
}
}
pub fn socket_path(cache_dir: &Path, pid: u32) -> PathBuf {
socket_path_with(cache_dir, pid, &nonce())
}
fn nonce() -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos() as u64)
.unwrap_or(0);
let here = Box::into_raw(Box::new(0u8));
let mixed = now ^ (here as u64);
drop(unsafe { Box::from_raw(here) });
format!("{:06x}", mixed & 0xff_ffff)
}
pub fn socket_path_with(cache_dir: &Path, pid: u32, nonce: &str) -> PathBuf {
cache_dir.join(format!("view-{pid}-{nonce}.sock"))
}
pub fn pid_of_socket(name: &str) -> Option<u32> {
let rest = name.strip_prefix("view-")?.strip_suffix(".sock")?;
let head = rest.split_once('-').map_or(rest, |(pid, _)| pid);
let pid = head.parse::<u32>().ok()?;
(pid > 0 && pid <= i32::MAX as u32).then_some(pid)
}
pub fn resolve(cwd: &Path, arg: &Path) -> PathBuf {
if arg.is_absolute() {
arg.to_path_buf()
} else {
cwd.join(arg)
}
}
pub fn send(socket: &Path, req: &ViewRequest) -> std::io::Result<ViewReply> {
let first = send_once(socket, req)?;
if first == retryable_refusal() {
return send_once(socket, req);
}
Ok(first)
}
pub const FRAME_BUDGET_REFUSAL: &str = "the request did not arrive within the frame budget";
fn retryable_refusal() -> ViewReply {
ViewReply::Err {
message: format!("unreadable request: {FRAME_BUDGET_REFUSAL}"),
}
}
fn send_once(socket: &Path, req: &ViewRequest) -> std::io::Result<ViewReply> {
use std::os::unix::net::UnixStream;
let mut stream = UnixStream::connect(socket)?;
stream.set_read_timeout(Some(std::time::Duration::from_secs(5)))?;
stream.set_write_timeout(Some(std::time::Duration::from_secs(5)))?;
let mut line = serde_json::to_string(req)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
line.push('\n');
stream.write_all(line.as_bytes())?;
stream.flush()?;
let reply = read_line_by_deadline(
&stream,
std::time::Instant::now() + std::time::Duration::from_secs(5),
"croft did not reply within 5s",
)?;
if reply.trim().is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"croft accepted the request but closed without replying",
));
}
serde_json::from_str(reply.trim())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
pub const MAX_STAGED_STDIN_BYTES: u64 = 64 * 1024 * 1024;
pub const MAX_REQUEST_BYTES: u64 = 64 * 1024;
pub fn read_line_by_deadline(
stream: &std::os::unix::net::UnixStream,
deadline: std::time::Instant,
whose: &str,
) -> std::io::Result<String> {
use std::io::Read;
let mut line: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let left = deadline.saturating_duration_since(std::time::Instant::now());
if left.is_zero() {
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, whose));
}
stream.set_read_timeout(Some(left))?;
match (&*stream).read(&mut chunk) {
Ok(0) => break,
Ok(n) => {
line.extend_from_slice(&chunk[..n]);
if let Some(pos) = line.iter().position(|b| *b == b'\n') {
if pos as u64 >= MAX_REQUEST_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"request exceeded the maximum length",
));
}
line.truncate(pos);
break;
}
if line.len() as u64 > MAX_REQUEST_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"request exceeded the maximum length",
));
}
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock
| std::io::ErrorKind::TimedOut
| std::io::ErrorKind::Interrupted
) => {}
Err(e) => return Err(e),
}
}
String::from_utf8(line).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
pub fn read_request(
stream: &std::os::unix::net::UnixStream,
deadline: std::time::Instant,
) -> std::io::Result<ViewRequest> {
let text = read_line_by_deadline(stream, deadline, FRAME_BUDGET_REFUSAL)?;
serde_json::from_str(text.trim())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
}
pub fn write_reply(
stream: &mut std::os::unix::net::UnixStream,
reply: &ViewReply,
) -> std::io::Result<()> {
let mut line = serde_json::to_string(reply)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
line.push('\n');
stream.write_all(line.as_bytes())?;
stream.flush()
}
pub fn extension_for(magic: crate::magic::Magic) -> &'static str {
use crate::magic::Magic;
match magic {
Magic::Png => "png",
Magic::Jpeg => "jpg",
Magic::Gif => "gif",
Magic::WebP => "webp",
Magic::Bmp => "bmp",
Magic::Pdf => "pdf",
Magic::Zip => "zip",
Magic::Gzip => "gz",
Magic::Tar => "tar",
Magic::Sqlite => "sqlite",
}
}
pub fn sanitize_extension(raw: &str) -> Option<String> {
let e = raw.trim().trim_start_matches('.').to_ascii_lowercase();
if e.is_empty() || e.len() > 16 {
return None;
}
e.chars().all(|c| c.is_ascii_alphanumeric()).then_some(e)
}
pub fn looks_delimited(bytes: &[u8]) -> Option<&'static str> {
if bytes.contains(&0) {
return None;
}
let text = std::str::from_utf8(bytes).ok()?;
let lines: Vec<&str> = text
.lines()
.filter(|l| !l.trim().is_empty())
.take(8)
.collect();
if lines.len() < 2 {
return None;
}
for (delim, ext) in [(',', "csv"), ('\t', "tsv")] {
let first = lines[0].matches(delim).count();
if first > 0 && lines.iter().all(|l| l.matches(delim).count() == first) {
return Some(ext);
}
}
None
}
pub fn stdin_extension(bytes: &[u8], hint: Option<&str>) -> anyhow::Result<Option<String>> {
if let Some(h) = hint {
let ext = sanitize_extension(h).ok_or_else(|| {
anyhow::anyhow!(
"croft view --as {h:?}: an extension must be a short run of letters and digits"
)
})?;
return Ok(Some(ext));
}
if let Some(m) = crate::magic::sniff(bytes) {
return Ok(Some(extension_for(m).to_string()));
}
Ok(looks_delimited(bytes).map(str::to_string))
}
pub fn stage_stdin(cache_dir: &Path, bytes: &[u8], hint: Option<&str>) -> anyhow::Result<PathBuf> {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
use std::os::unix::fs::DirBuilderExt;
let ext = stdin_extension(bytes, hint)?;
let dir = cache_dir.join("view-stdin");
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(&dir)?;
let _ = std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o700));
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let stem = format!("stdin-{}-{n}", std::process::id());
let name = match ext {
Some(ext) => format!("{stem}.{ext}"),
None => stem,
};
stage_at(&dir, &name, bytes)
}
pub const HELD_PREFIX: &str = "held-";
pub fn claim_staged(path: &Path, holder: u32) -> Option<PathBuf> {
let name = path.file_name()?.to_str()?;
if !name.starts_with("stdin-") {
return None;
}
let dir = path.parent()?;
if dir.file_name()?.to_str()? != "view-stdin" {
return None;
}
let held = dir.join(format!("{HELD_PREFIX}{holder}-{name}"));
std::fs::rename(path, &held).ok()?;
Some(held)
}
pub fn holder_of_staged(name: &str) -> Option<u32> {
let (pid, _) = name.strip_prefix(HELD_PREFIX)?.split_once('-')?;
let pid = pid.parse::<u32>().ok()?;
(pid > 0 && pid <= i32::MAX as u32).then_some(pid)
}
pub(crate) fn stage_at(dir: &Path, name: &str, bytes: &[u8]) -> anyhow::Result<PathBuf> {
use std::os::unix::fs::OpenOptionsExt as _;
let mut attempt = 0;
loop {
let suffixed = if attempt == 0 {
name.to_string()
} else {
match name.rsplit_once('.') {
Some((stem, ext)) => format!("{stem}-{attempt}.{ext}"),
None => format!("{name}-{attempt}"),
}
};
let path = dir.join(&suffixed);
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&path)
{
Ok(mut f) => {
std::io::Write::write_all(&mut f, bytes)?;
return Ok(std::path::absolute(&path).unwrap_or(path));
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && attempt < 64 => {
attempt += 1;
}
Err(e) => return Err(e.into()),
}
}
}
fn read_capped<R: std::io::Read>(reader: R, cap: u64) -> anyhow::Result<Vec<u8>> {
use std::io::Read as _;
let mut buf = Vec::new();
let read = reader.take(cap + 1).read_to_end(&mut buf)? as u64;
if read > cap {
anyhow::bail!(
"more than {cap} bytes arrived on stdin; write it to a file and view that instead"
);
}
Ok(buf)
}
pub const PROBE_CLOSED: &str = "closed";
pub const PROBE_OPEN: &str = "open";
const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(250);
pub fn edit(target: &std::ffi::OsStr, wait: bool, cache_dir: &Path) -> anyhow::Result<()> {
run(target, None, cache_dir)?;
if !wait {
return Ok(());
}
let Some(socket) = std::env::var_os(SOCK_ENV).filter(|s| !s.is_empty()) else {
return Ok(());
};
let path = resolve(&std::env::current_dir()?, Path::new(target));
let probe = ViewRequest::probe(&path);
loop {
std::thread::sleep(WAIT_POLL);
match wait_step(send(Path::new(&socket), &probe)) {
WaitStep::Poll => continue,
WaitStep::Closed => return Ok(()),
WaitStep::CannotWait => anyhow::bail!(
"the croft hosting this pane is older than `croft edit --wait`; restart it (F9) and try again"
),
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum WaitStep {
Poll,
Closed,
CannotWait,
}
fn wait_step(reply: std::io::Result<ViewReply>) -> WaitStep {
use std::io::ErrorKind as K;
match reply {
Ok(ViewReply::Err { message }) if message == PROBE_CLOSED => WaitStep::Closed,
Ok(ViewReply::Ok) => WaitStep::CannotWait,
Ok(ViewReply::Err { .. }) => WaitStep::Poll,
Err(e) => match e.kind() {
K::NotFound
| K::ConnectionRefused
| K::ConnectionReset
| K::BrokenPipe
| K::UnexpectedEof => WaitStep::Closed,
_ => WaitStep::Poll,
},
}
}
pub fn run(
target: &std::ffi::OsStr,
as_hint: Option<&str>,
cache_dir: &Path,
) -> anyhow::Result<()> {
let socket = match std::env::var_os(SOCK_ENV).filter(|s| !s.is_empty()) {
Some(s) => PathBuf::from(s),
None => anyhow::bail!(
"croft view needs a croft to view in: run it from a pane inside croft ({SOCK_ENV} is unset)"
),
};
if target != "-" && as_hint.is_some() {
anyhow::bail!(
"croft view --as applies only to piped input (`croft view - --as csv`); \
a named file is routed by its own extension"
);
}
let path = if target == "-" {
let buf = read_capped(std::io::stdin(), MAX_STAGED_STDIN_BYTES)?;
if buf.is_empty() {
anyhow::bail!("croft view -: nothing arrived on stdin");
}
stage_stdin(cache_dir, &buf, as_hint)?
} else {
let cwd = std::env::current_dir()?;
let path = resolve(&cwd, Path::new(target));
if !path.exists() {
anyhow::bail!("croft view: no such file: {}", path.display());
}
path
};
match send(&socket, &ViewRequest::new(&path)) {
Ok(ViewReply::Ok) => Ok(()),
Ok(ViewReply::Err { message }) => anyhow::bail!("croft view: {message}"),
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::ConnectionRefused
| std::io::ErrorKind::NotFound
| std::io::ErrorKind::BrokenPipe
| std::io::ErrorKind::UnexpectedEof
) =>
{
anyhow::bail!(
"croft view: the croft that opened this pane is gone (socket {})",
socket.display()
)
}
Err(e) => anyhow::bail!("croft view: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_closed_tab_or_a_gone_croft_ends_edit_wait() {
use std::io::{Error, ErrorKind};
let err = |m: &str| {
Ok(ViewReply::Err {
message: m.to_string(),
})
};
assert_eq!(wait_step(err(PROBE_CLOSED)), WaitStep::Closed);
assert_eq!(wait_step(err(PROBE_OPEN)), WaitStep::Poll);
assert_eq!(
wait_step(err(&format!("unreadable request: {FRAME_BUDGET_REFUSAL}"))),
WaitStep::Poll
);
assert_eq!(
wait_step(Err(Error::from(ErrorKind::TimedOut))),
WaitStep::Poll
);
assert_eq!(
wait_step(Err(Error::from(ErrorKind::WouldBlock))),
WaitStep::Poll
);
assert_eq!(
wait_step(Err(Error::from(ErrorKind::ConnectionRefused))),
WaitStep::Closed
);
assert_eq!(wait_step(Ok(ViewReply::Ok)), WaitStep::CannotWait);
}
#[test]
fn a_relative_argument_resolves_against_the_clients_cwd_not_the_servers() {
assert_eq!(
resolve(Path::new("/home/u/proj"), Path::new("report.pdf")),
PathBuf::from("/home/u/proj/report.pdf")
);
assert_eq!(
resolve(Path::new("/home/u/proj"), Path::new("../out/a.png")),
PathBuf::from("/home/u/proj/../out/a.png")
);
}
#[test]
fn an_absolute_argument_is_left_exactly_alone() {
assert_eq!(
resolve(Path::new("/home/u"), Path::new("/etc/hosts")),
PathBuf::from("/etc/hosts")
);
}
#[test]
fn a_tilde_is_a_filename_here_because_the_shell_already_had_its_turn() {
assert_eq!(
resolve(Path::new("/w"), Path::new("~")),
PathBuf::from("/w/~")
);
}
#[test]
fn a_path_that_is_not_utf8_survives_the_round_trip() {
use std::os::unix::ffi::OsStrExt;
let raw = std::ffi::OsStr::from_bytes(b"/tmp/\xff\xfe-broken.png");
let original = PathBuf::from(raw);
assert!(
original.to_str().is_none(),
"fixture must be invalid UTF-8, or this test proves nothing"
);
let wire = serde_json::to_string(&ViewRequest::new(&original)).unwrap();
let back: ViewRequest = serde_json::from_str(&wire).unwrap();
assert_eq!(back.to_path(), original);
}
#[test]
fn a_path_with_a_newline_survives_because_the_encoding_is_not_the_delimiter() {
let original = PathBuf::from("/tmp/two\nlines.pdf");
let wire = serde_json::to_string(&ViewRequest::new(&original)).unwrap();
assert!(!wire.contains('\n'), "the encoded form must be one line");
let back: ViewRequest = serde_json::from_str(&wire).unwrap();
assert_eq!(back.to_path(), original);
}
#[test]
fn the_socket_is_keyed_by_pid_so_two_crofts_do_not_contend() {
let dir = Path::new("/c");
let ten = socket_path(dir, 10);
let eleven = socket_path(dir, 11);
let name = ten.file_name().unwrap().to_str().unwrap();
assert_eq!(pid_of_socket(name), Some(10));
assert_eq!(
pid_of_socket(eleven.file_name().unwrap().to_str().unwrap()),
Some(11)
);
assert!(
ten.starts_with("/c"),
"and it stays in the cache dir: {ten:?}"
);
}
fn serve_counting(
listener: std::os::unix::net::UnixListener,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
answer: impl Fn(usize) -> ViewReply + Send + 'static,
) -> std::thread::JoinHandle<usize> {
listener.set_nonblocking(true).unwrap();
std::thread::spawn(move || {
let mut seen = 0usize;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, _)) => {
stream.set_nonblocking(false).unwrap();
let deadline =
std::time::Instant::now() + std::time::Duration::from_secs(5);
if read_line_by_deadline(&stream, deadline, "no request").is_err() {
continue;
}
let reply = answer(seen);
seen += 1;
let _ = write_reply(&mut stream, &reply);
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(std::time::Duration::from_millis(2));
}
Err(_) => break,
}
}
seen
})
}
#[test]
fn a_frame_budget_refusal_is_retried_once_and_then_succeeds() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let server = serve_counting(listener, std::sync::Arc::clone(&stop), |i| {
if i == 0 {
retryable_refusal()
} else {
ViewReply::Ok
}
});
let reply = send(&sock, &ViewRequest::new(Path::new("/tmp/x"))).unwrap();
stop.store(true, std::sync::atomic::Ordering::Relaxed);
let seen = server.join().unwrap();
assert_eq!(
reply,
ViewReply::Ok,
"the refusal names croft's own frame budget, which the client had \
no part in, so a second attempt is owed"
);
assert_eq!(
seen, 2,
"and the success must come from a SECOND connection: delete the \
retry and this is 1 with the refusal returned"
);
}
#[test]
fn the_frame_budget_retry_is_one_attempt_not_a_loop() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let server = serve_counting(listener, std::sync::Arc::clone(&stop), |_| {
retryable_refusal()
});
let reply = send(&sock, &ViewRequest::new(Path::new("/tmp/x"))).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
stop.store(true, std::sync::atomic::Ordering::Relaxed);
let seen = server.join().unwrap();
assert_eq!(
reply,
retryable_refusal(),
"a croft refusing twice is reported, not retried forever"
);
assert_eq!(seen, 2, "exactly two attempts, not {seen}");
}
#[test]
fn the_stdin_cap_accepts_exactly_the_cap_and_refuses_one_more() {
assert_eq!(
read_capped(&b"1234567"[..], 8).unwrap(),
b"1234567",
"under the cap"
);
assert_eq!(
read_capped(&b"12345678"[..], 8).unwrap(),
b"12345678",
"EXACTLY the cap must be accepted: `take(cap)` plus `==` refuses \
this, which is the mutation the `+ 1` exists to reject"
);
let over = read_capped(&b"123456789"[..], 8);
assert!(
over.is_err(),
"one byte past the cap must be refused rather than truncated: \
a truncated payload stages a corrupt file and reports success"
);
assert!(
over.unwrap_err().to_string().contains("more than 8 bytes"),
"and the message must name the cap the user hit: `contains(\"8\")` \
passed on any stray 8 in any wording"
);
}
#[test]
fn the_delimiter_sniff_judges_the_first_eight_lines_only() {
let mut agreeing = String::new();
for i in 0..8 {
agreeing.push_str(&format!("a{i},b{i}\n"));
}
let mut disagreeing = agreeing.clone();
disagreeing.push_str("this row has no delimiter at all\n");
assert_eq!(
looks_delimited(agreeing.as_bytes()),
Some("csv"),
"eight agreeing rows are a table"
);
assert_eq!(
looks_delimited(disagreeing.as_bytes()),
Some("csv"),
"and a NINTH row that disagrees is outside the window: drop the \
`take(8)` and this reads None, which is the change the window \
exists to make and nothing else here would notice"
);
let early = format!("a,b\nno delimiter here\n{agreeing}");
assert_eq!(
looks_delimited(early.as_bytes()),
None,
"a row that disagrees INSIDE the window rejects the whole sniff"
);
let mut seven = String::new();
for i in 0..7 {
seven.push_str(&format!("a{i},b{i}\n"));
}
seven.push_str("the eighth row has no delimiter\n");
assert_eq!(
looks_delimited(seven.as_bytes()),
None,
"the eighth row is INSIDE the window, so it must reject the sniff"
);
}
#[test]
fn an_extension_hint_that_could_escape_the_staging_dir_is_refused() {
for bad in ["../x", "a/b", "a.b", "", " ", "ext with space", "é"] {
assert_eq!(sanitize_extension(bad), None, "{bad:?} must be refused");
}
assert_eq!(sanitize_extension("CSV").as_deref(), Some("csv"));
assert_eq!(sanitize_extension(".png").as_deref(), Some("png"));
}
#[test]
fn delimited_data_is_recognised_only_when_every_row_agrees() {
assert_eq!(looks_delimited(b"a,b,c\n1,2,3\n4,5,6\n"), Some("csv"));
assert_eq!(looks_delimited(b"a\tb\n1\t2\n"), Some("tsv"));
}
#[test]
fn prose_with_commas_is_not_mistaken_for_a_table() {
assert_eq!(
looks_delimited(
b"Hello, world, and welcome.\nThis line, however, differs.\nOne more.\n"
),
None
);
}
#[test]
fn a_single_line_is_a_sentence_rather_than_a_table() {
assert_eq!(looks_delimited(b"name,age,city\n"), None);
}
#[test]
fn binary_content_never_reaches_the_delimiter_test() {
assert_eq!(looks_delimited(b"a,b\n\x00\x01,\x02\n"), None);
}
#[test]
fn the_hint_beats_the_sniff_which_beats_the_delimiter_guess() {
let png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR";
assert_eq!(stdin_extension(png, None).unwrap().as_deref(), Some("png"));
assert_eq!(
stdin_extension(png, Some("bin")).unwrap().as_deref(),
Some("bin")
);
assert_eq!(
stdin_extension(b"a,b\n1,2\n", None).unwrap().as_deref(),
Some("csv")
);
assert_eq!(
stdin_extension(b"just a log line\nand another\n", None).unwrap(),
None
);
}
#[test]
fn an_unusable_as_flag_is_an_error_rather_than_a_silent_fallback() {
let err = stdin_extension(b"a,b\n1,2\n", Some("../x")).unwrap_err();
assert!(
err.to_string().contains("--as"),
"the message must name the flag, got {err}"
);
assert_eq!(
stdin_extension(b"anything", Some("json"))
.unwrap()
.as_deref(),
Some("json")
);
}
#[test]
fn staged_stdin_carries_the_content_and_the_routing_extension() {
let tmp = tempfile::tempdir().unwrap();
let p = stage_stdin(tmp.path(), b"a,b\n1,2\n", None).unwrap();
assert_eq!(
p.extension().and_then(|e| e.to_str()),
Some("csv"),
"the editor routes on extension, so staging without one lands in text"
);
assert_eq!(std::fs::read(&p).unwrap(), b"a,b\n1,2\n");
}
#[test]
fn staged_stdin_is_readable_only_by_its_owner() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let p = stage_stdin(tmp.path(), b"hunter2", Some("txt")).unwrap();
let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "staged stdin was mode {mode:o}");
let dir_mode = std::fs::metadata(p.parent().unwrap())
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(dir_mode, 0o700, "the staging dir was mode {dir_mode:o}");
}
#[test]
fn two_pipes_in_one_process_do_not_collide() {
let tmp = tempfile::tempdir().unwrap();
let a = stage_stdin(tmp.path(), b"first", Some("txt")).unwrap();
let b = stage_stdin(tmp.path(), b"second", Some("txt")).unwrap();
assert_ne!(a, b);
assert_eq!(std::fs::read(&a).unwrap(), b"first");
assert_eq!(std::fs::read(&b).unwrap(), b"second");
}
#[test]
fn a_socket_name_carries_the_pid_first_and_a_tail_that_differs() {
let dir = PathBuf::from("/tmp/croft-test");
let a = socket_path(&dir, 4242);
let b = socket_path(&dir, 4242);
let name_a = a.file_name().unwrap().to_str().unwrap();
assert_eq!(
pid_of_socket(name_a),
Some(4242),
"the sweep must read the pid"
);
assert_ne!(a, b, "two binds by one pid must not collide on one name");
assert!(
name_a.len() < 104,
"the whole name has to fit an AF_UNIX path with room for the dir"
);
}
#[test]
fn a_socket_name_from_before_the_nonce_is_still_read() {
assert_eq!(pid_of_socket("view-77.sock"), Some(77));
assert_eq!(pid_of_socket("view-77-a1b2c3.sock"), Some(77));
assert_eq!(pid_of_socket("not-a-view-socket"), None);
assert_eq!(pid_of_socket("view-notapid.sock"), None);
}
#[test]
fn a_staged_name_already_on_disk_is_stepped_past_not_overwritten() {
let tmp = tempfile::tempdir().unwrap();
let taken = tmp.path().join("x.txt");
std::fs::write(&taken, b"an older croft's bytes").unwrap();
let path = stage_at(tmp.path(), "x.txt", b"mine").unwrap();
assert_eq!(
path.file_name().unwrap().to_str().unwrap(),
"x-1.txt",
"the taken name must be stepped past, not reused: {path:?}"
);
assert_eq!(
std::fs::read(&taken).unwrap(),
b"an older croft's bytes",
"and the file that held it must be untouched"
);
assert_eq!(std::fs::read(&path).unwrap(), b"mine");
}
#[test]
fn a_request_and_its_reply_cross_a_real_socket() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = crate::session::bind_socket_0600(&sock).unwrap();
let sent = PathBuf::from("/tmp/some\u{fffd}where/a.pdf");
let server = {
let sent = sent.clone();
std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let req = read_request(
&stream,
std::time::Instant::now() + std::time::Duration::from_secs(5),
)
.unwrap();
assert_eq!(req.to_path(), sent);
write_reply(&mut stream, &ViewReply::Ok).unwrap();
})
};
assert_eq!(
send(&sock, &ViewRequest::new(&sent)).unwrap(),
ViewReply::Ok
);
server.join().unwrap();
}
#[test]
fn the_servers_error_text_reaches_the_client_verbatim() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = crate::session::bind_socket_0600(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let _ = read_request(
&stream,
std::time::Instant::now() + std::time::Duration::from_secs(5),
);
write_reply(
&mut stream,
&ViewReply::Err {
message: String::from("/x is a directory"),
},
)
.unwrap();
});
let got = send(&sock, &ViewRequest::new(Path::new("/x"))).unwrap();
assert_eq!(
got,
ViewReply::Err {
message: String::from("/x is a directory")
}
);
server.join().unwrap();
}
#[test]
fn a_server_that_hangs_up_without_replying_is_an_error_not_a_success() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = crate::session::bind_socket_0600(&sock).unwrap();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let _ = read_request(
&stream,
std::time::Instant::now() + std::time::Duration::from_secs(5),
);
drop(stream);
});
let err = send(&sock, &ViewRequest::new(Path::new("/x"))).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
server.join().unwrap();
}
}