use std::time::Duration;
pub const DETECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailureKind {
Unreachable,
Timeout,
Hub,
NoCwd,
}
#[derive(Debug, Clone)]
pub struct DetectFailure {
pub kind: FailureKind,
pub cwd: String,
pub detail: String,
}
impl DetectFailure {
pub fn new(kind: FailureKind, cwd: &str, detail: impl Into<String>) -> Self {
Self {
kind,
cwd: cwd.to_string(),
detail: detail.into(),
}
}
fn from_reqwest(server: &str, cwd: &str, e: &reqwest::Error) -> Self {
if e.is_timeout() {
let mut detail = format!(
"the hub at {server} did not answer within {}s",
DETECT_TIMEOUT.as_secs()
);
if cfg!(target_os = "macos") {
detail.push_str(
" — if macOS is showing a privacy prompt for ctxone-hub \
(common right after an upgrade), answer it",
);
}
Self::new(FailureKind::Timeout, cwd, detail)
} else if e.is_connect() {
Self::new(
FailureKind::Unreachable,
cwd,
format!("hub unreachable at {server} ({})", root_cause(e)),
)
} else {
Self::new(
FailureKind::Hub,
cwd,
format!("request to {server} failed ({e})"),
)
}
}
pub fn exit_code(&self) -> i32 {
match self.kind {
FailureKind::Unreachable => crate::EX_UNAVAILABLE,
FailureKind::Timeout => crate::EX_TEMPFAIL,
FailureKind::Hub => crate::EX_PROTOCOL,
FailureKind::NoCwd => crate::EX_NOINPUT,
}
}
pub fn headline(&self) -> String {
format!(
"can't tell which workspace {} belongs to: {}",
self.cwd, self.detail
)
}
pub fn report(&self) {
eprintln!("ctx: {}", self.headline());
eprintln!("{}", NAMESPACE_HINT);
}
pub fn exit(&self) -> ! {
self.report();
std::process::exit(self.exit_code());
}
}
pub const NAMESPACE_HINT: &str = " Not falling back to the 'default' workspace, which would read and \
write the wrong data.\n Pass --namespace <workspace> (or set CTX_NAMESPACE) to choose one \
and skip detection.";
pub async fn detect(
client: &reqwest::Client,
server: &str,
cwd: &str,
) -> Result<Option<String>, DetectFailure> {
let resp = client
.get(format!("{server}/api/projects/detect"))
.query(&[("cwd", cwd)])
.send()
.await
.map_err(|e| DetectFailure::from_reqwest(server, cwd, &e))?;
let status = resp.status();
let body = resp
.text()
.await
.map_err(|e| DetectFailure::from_reqwest(server, cwd, &e))?;
interpret(status, &body, cwd)
}
pub fn interpret(
status: reqwest::StatusCode,
body: &str,
cwd: &str,
) -> Result<Option<String>, DetectFailure> {
let parsed: Option<serde_json::Value> = serde_json::from_str(body).ok();
if !status.is_success() {
let detail = parsed
.as_ref()
.and_then(|v| v["error"].as_str())
.map(str::to_string)
.unwrap_or_else(|| format!("hub answered {status}: {}", snippet(body)));
let kind = if status == reqwest::StatusCode::GATEWAY_TIMEOUT {
FailureKind::Timeout
} else {
FailureKind::Hub
};
return Err(DetectFailure::new(kind, cwd, detail));
}
let unexpected = || {
DetectFailure::new(
FailureKind::Hub,
cwd,
format!("unexpected answer from the hub: {}", snippet(body)),
)
};
let v = parsed.ok_or_else(unexpected)?;
match v["status"].as_str() {
Some("found") => v["namespace"]
.as_str()
.map(|ns| Some(ns.to_string()))
.ok_or_else(unexpected),
Some("not_found") | Some("registry_unavailable") => Ok(None),
_ => Err(unexpected()),
}
}
fn root_cause(e: &reqwest::Error) -> String {
let mut cur: &dyn std::error::Error = e;
while let Some(next) = cur.source() {
cur = next;
}
cur.to_string()
}
fn snippet(body: &str) -> String {
let flat = body.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.is_empty() {
return "(empty body)".to_string();
}
match flat.char_indices().nth(200) {
Some((i, _)) => format!("{}…", &flat[..i]),
None => flat,
}
}
#[cfg(test)]
mod tests {
use super::*;
use reqwest::StatusCode;
const CWD: &str = "/Users/me/Documents/repo";
#[test]
fn found_is_the_project_namespace() {
let body = r#"{"status":"found","via":"ctxproject","project_id":"p","namespace":"p-ns"}"#;
assert_eq!(
interpret(StatusCode::OK, body, CWD).unwrap(),
Some("p-ns".into())
);
}
#[test]
fn not_found_and_no_registry_are_the_default_workspace() {
for status in ["not_found", "registry_unavailable"] {
let body = format!(r#"{{"status":"{status}","namespace":"default"}}"#);
assert_eq!(interpret(StatusCode::OK, &body, CWD).unwrap(), None);
}
}
#[test]
fn hub_timeout_is_a_timeout_failure_with_its_explanation() {
let body = r#"{"status":"timeout","error":"project detection did not finish within 3s"}"#;
let f = interpret(StatusCode::GATEWAY_TIMEOUT, body, CWD).unwrap_err();
assert_eq!(f.kind, FailureKind::Timeout);
assert_eq!(f.exit_code(), crate::EX_TEMPFAIL);
assert!(
f.detail.contains("did not finish within 3s"),
"{}",
f.detail
);
assert!(f.headline().contains(CWD));
}
#[test]
fn hub_errors_are_failures_not_not_found() {
let body =
r#"{"status":"error","error":"cannot read /r/.ctxproject: Operation not permitted"}"#;
let f = interpret(StatusCode::INTERNAL_SERVER_ERROR, body, CWD).unwrap_err();
assert_eq!(f.kind, FailureKind::Hub);
assert!(f.detail.contains("Operation not permitted"));
let f = interpret(
StatusCode::SERVICE_UNAVAILABLE,
r#"{"status":"busy","error":"x"}"#,
CWD,
)
.unwrap_err();
assert_eq!(f.kind, FailureKind::Hub);
let f = interpret(StatusCode::UNAUTHORIZED, "missing bearer token", CWD).unwrap_err();
assert!(f.detail.contains("missing bearer token"), "{}", f.detail);
}
#[test]
fn unparseable_or_unknown_answers_are_failures() {
assert!(interpret(StatusCode::OK, "<html>proxy</html>", CWD).is_err());
assert!(interpret(StatusCode::OK, r#"{"status":"maybe"}"#, CWD).is_err());
assert!(interpret(StatusCode::OK, r#"{"status":"found"}"#, CWD).is_err());
}
#[test]
fn snippet_is_bounded_and_single_line() {
let long = "word ".repeat(100);
let s = snippet(&long);
assert!(s.chars().count() <= 201);
assert!(!s.contains('\n'));
assert_eq!(snippet(" "), "(empty body)");
}
fn client(timeout: Duration) -> reqwest::Client {
reqwest::Client::builder().timeout(timeout).build().unwrap()
}
#[tokio::test]
async fn silent_hub_is_a_timeout_failure() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let server = format!("http://{}", listener.local_addr().unwrap());
let hold = tokio::spawn(async move {
let (_sock, _) = listener.accept().await.unwrap();
tokio::time::sleep(Duration::from_secs(30)).await;
});
let f = detect(&client(Duration::from_millis(200)), &server, CWD)
.await
.unwrap_err();
assert_eq!(f.kind, FailureKind::Timeout, "{f:?}");
hold.abort();
}
#[tokio::test]
async fn closed_port_is_an_unreachable_failure() {
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let server = format!("http://127.0.0.1:{port}");
let f = detect(&client(Duration::from_secs(2)), &server, CWD)
.await
.unwrap_err();
assert_eq!(f.kind, FailureKind::Unreachable, "{f:?}");
assert_eq!(f.exit_code(), crate::EX_UNAVAILABLE);
}
#[tokio::test]
async fn answering_hub_round_trips() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let server = format!("http://{}", listener.local_addr().unwrap());
let serve = tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let _ = sock.read(&mut buf).await;
let body = r#"{"status":"not_found","namespace":"default"}"#;
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
sock.write_all(resp.as_bytes()).await.unwrap();
});
let got = detect(&client(Duration::from_secs(2)), &server, CWD).await;
assert_eq!(got.unwrap(), None);
serve.await.unwrap();
}
}