use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Routed {
Existing(String),
Registered(String),
WouldRegister(String),
Fallback,
Unresolved(String),
}
impl Routed {
pub fn namespace(&self) -> Option<&str> {
match self {
Routed::Existing(ns) | Routed::Registered(ns) => Some(ns.as_str()),
Routed::WouldRegister(_) | Routed::Fallback | Routed::Unresolved(_) => None,
}
}
pub fn unresolved(&self) -> Option<&str> {
match self {
Routed::Unresolved(reason) => Some(reason.as_str()),
_ => None,
}
}
}
pub struct Router {
server: String,
probe: reqwest::Client,
auto_register: bool,
dry_run: bool,
fallback: Option<String>,
dir_workspaces: bool,
memo: HashMap<String, Routed>,
clients: HashMap<Option<String>, reqwest::Client>,
tombstones: HashMap<Option<String>, std::collections::HashSet<String>>,
}
impl Router {
pub fn new(server: &str, auto_register: bool, dry_run: bool, fallback: Option<String>) -> Self {
Self {
server: server.to_string(),
dry_run,
fallback,
probe: reqwest::Client::builder()
.timeout(crate::detect::DETECT_TIMEOUT)
.build()
.unwrap_or_default(),
auto_register,
dir_workspaces: false,
memo: HashMap::new(),
clients: HashMap::new(),
tombstones: HashMap::new(),
}
}
pub fn with_dir_workspaces(mut self, on: bool) -> Self {
self.dir_workspaces = on;
self
}
fn resolve_root(&self, dir: &std::path::Path) -> Option<std::path::PathBuf> {
match crate::find_git_root(dir) {
Some(root) => Some(root),
None if self.dir_workspaces => Some(dir.to_path_buf()),
None => None,
}
}
pub async fn is_tombstoned(&mut self, ns: Option<&str>, sid: &str) -> bool {
let key = ns.map(str::to_string);
if !self.tombstones.contains_key(&key) {
let set = fetch_tombstones(&self.server, &self.probe, ns).await;
self.tombstones.insert(key.clone(), set);
}
self.tombstones
.get(&key)
.map(|s| s.contains(sid))
.unwrap_or(false)
}
pub async fn route(&mut self, cwd: Option<&str>) -> Routed {
let Some(cwd) = cwd.map(str::trim).filter(|c| !c.is_empty()) else {
return self.fallback();
};
if let Some(hit) = self.memo.get(cwd) {
return hit.clone();
}
let outcome = self.resolve(cwd).await;
self.memo.insert(cwd.to_string(), outcome.clone());
outcome
}
async fn resolve(&self, cwd: &str) -> Routed {
match self.detect(cwd).await {
Ok(Some(ns)) => return Routed::Existing(ns),
Ok(None) => {}
Err(reason) => return Routed::Unresolved(reason),
}
if !self.auto_register {
return self.fallback();
}
if self.dry_run {
return match self.would_register(cwd) {
Some(id) => Routed::WouldRegister(id),
None => self.fallback(),
};
}
match self.register(cwd).await {
Some(ns) => Routed::Registered(ns),
None => self.fallback(),
}
}
fn fallback(&self) -> Routed {
match &self.fallback {
Some(ns) => Routed::Existing(ns.clone()),
None => Routed::Fallback,
}
}
fn would_register(&self, cwd: &str) -> Option<String> {
let dir = std::path::Path::new(cwd);
if !dir.is_dir() {
return None;
}
let root = self.resolve_root(dir)?;
project_id_for(&root, crate::read_git_remote(&root).as_deref())
}
async fn detect(&self, cwd: &str) -> Result<Option<String>, String> {
crate::detect::detect(&self.probe, &self.server, cwd)
.await
.map_err(|f| f.detail)
}
async fn register(&self, cwd: &str) -> Option<String> {
let dir = std::path::Path::new(cwd);
if !dir.is_dir() {
return None; }
let root = self.resolve_root(dir)?;
let remote = crate::read_git_remote(&root);
let id = project_id_for(&root, remote.as_deref())?;
let body = serde_json::json!({
"id": id,
"remote_url": remote,
"local_path": root.to_string_lossy(),
"display_name": root.file_name().map(|n| n.to_string_lossy().to_string()),
});
let resp = self
.probe
.post(format!("{}/api/projects", self.server))
.json(&body)
.send()
.await
.ok()?;
if !resp.status().is_success() {
return None;
}
let v: serde_json::Value = resp.json().await.ok()?;
v["namespace"]
.as_str()
.or(Some(id.as_str()))
.map(str::to_string)
}
pub fn client_for(
&mut self,
ns: Option<&str>,
build: impl FnOnce(Option<&str>) -> reqwest::Client,
) -> reqwest::Client {
let key = ns.map(str::to_string);
self.clients.entry(key).or_insert_with(|| build(ns)).clone()
}
pub fn decisions(&self) -> Vec<(&str, &Routed)> {
let mut out: Vec<(&str, &Routed)> =
self.memo.iter().map(|(k, v)| (k.as_str(), v)).collect();
out.sort_by(|a, b| a.0.cmp(b.0));
out
}
}
pub async fn fetch_tombstones(
server: &str,
client: &reqwest::Client,
namespace: Option<&str>,
) -> std::collections::HashSet<String> {
let mut url = format!("{server}/api/session_tombstones");
if let Some(ns) = namespace {
url.push_str(&format!("?namespace={}", crate::urlencoding(ns)));
}
let Ok(resp) = client.get(url).send().await else {
return Default::default();
};
if !resp.status().is_success() {
return Default::default();
}
let Ok(v) = resp.json::<serde_json::Value>().await else {
return Default::default();
};
v["sessions"]
.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str())
.map(str::to_string)
.collect()
})
.unwrap_or_default()
}
pub fn project_id_for(root: &std::path::Path, remote: Option<&str>) -> Option<String> {
if let Some(canonical) = remote.and_then(canonical_remote) {
return Some(id_from_canonical(&canonical));
}
let from_remote = remote.and_then(|r| {
let trimmed = r.trim_end_matches('/').trim_end_matches(".git");
trimmed
.rsplit(['/', ':'])
.find(|s| !s.is_empty())
.map(str::to_string)
});
let raw = from_remote.or_else(|| root.file_name().map(|n| n.to_string_lossy().to_string()))?;
let id = kebab(&raw);
(!id.is_empty()).then_some(id)
}
const MAX_ID_LEN: usize = 64;
fn id_from_canonical(canonical: &str) -> String {
let id = kebab(canonical);
if id.len() <= MAX_ID_LEN {
return id;
}
let path = canonical.split_once('/').map_or(canonical, |(_, p)| p);
let mut base = kebab(path);
base.truncate(MAX_ID_LEN - 9);
let base = base.trim_end_matches('-');
format!("{base}-{:08x}", fnv1a(canonical) >> 32)
}
fn fnv1a(s: &str) -> u64 {
s.bytes().fold(0xcbf2_9ce4_8422_2325, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
})
}
pub fn canonical_remote(url: &str) -> Option<String> {
let url = url.trim();
let (authority, path) = match url.split_once("://") {
Some((scheme, _)) if scheme.eq_ignore_ascii_case("file") => return None,
Some((_, rest)) => rest.split_once('/')?,
None => {
let (authority, path) = url.split_once(':')?;
if authority.contains('/') || authority.contains('\\') {
return None;
}
(authority, path)
}
};
let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
let host = match host_port.strip_prefix('[') {
Some(v6) => v6.split_once(']').map_or(v6, |(h, _)| h),
None => host_port
.rsplit_once(':')
.filter(|(_, port)| port.chars().all(|c| c.is_ascii_digit()))
.map_or(host_port, |(h, _)| h),
};
let path = path.trim_matches('/');
let path = path
.strip_suffix(".git")
.unwrap_or(path)
.trim_end_matches('/');
if host.len() < 2 || path.is_empty() {
return None;
}
Some(format!("{host}/{path}").to_ascii_lowercase())
}
fn kebab(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut prev_dash = false;
for c in s.chars() {
if c.is_ascii_alphanumeric() {
out.push(c.to_ascii_lowercase());
prev_dash = false;
} else if !out.is_empty() && !prev_dash {
out.push('-');
prev_dash = true;
}
}
while out.ends_with('-') {
out.pop();
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn kebab_keeps_only_namespace_safe_chars() {
assert_eq!(kebab("My Repo!"), "my-repo");
assert_eq!(kebab("CTXone"), "ctxone");
assert_eq!(kebab("a__b--c"), "a-b-c");
assert_eq!(kebab("--trailing--"), "trailing");
assert_eq!(kebab(""), "");
}
#[test]
fn project_id_is_the_whole_remote() {
let root = PathBuf::from("/Users/user/checkouts/some-checkout-dir");
for remote in [
"git@github.com:agentstatelabs/CTXone.git",
"https://github.com/agentstatelabs/ctxone",
"ssh://git@github.com:22/agentstatelabs/ctxone.git",
] {
assert_eq!(
project_id_for(&root, Some(remote)).unwrap(),
"github-com-agentstatelabs-ctxone",
"{remote}"
);
}
assert_ne!(
project_id_for(&root, Some("https://github.com/a/app")),
project_id_for(&root, Some("https://github.com/b/app"))
);
assert_eq!(
project_id_for(&root, Some("/srv/git/Shared-Repo.git")).unwrap(),
"shared-repo"
);
}
#[test]
fn a_long_remote_id_fits_a_namespace_and_stays_distinct() {
let root = PathBuf::from("/x");
let long = |repo: &str| {
format!(
"https://gitlab.example.com/a-very-long-group-name/another-long-subgroup/{repo}"
)
};
let a = project_id_for(&root, Some(&long("the-application"))).unwrap();
let b = project_id_for(&root, Some(&long("the-application-two"))).unwrap();
for id in [&a, &b] {
assert!(id.len() <= 64, "{id} is {} bytes", id.len());
assert!(id.starts_with("a-very-long-group-name-"), "{id}");
}
assert_ne!(a, b);
assert_eq!(
a,
project_id_for(&root, Some(&long("the-application"))).unwrap()
);
}
#[test]
fn canonical_remote_agrees_with_the_hubs() {
for (url, want) in [
(
"https://user:secret@github.com:443/Owner/Repo.git/",
Some("github.com/owner/repo"),
),
(
"git@gitlab.example.com:group/sub/app.git",
Some("gitlab.example.com/group/sub/app"),
),
(
"ssh://git@[2001:db8::1]:2222/g/app",
Some("2001:db8::1/g/app"),
),
("/srv/git/repo.git", None),
("file:///srv/git/repo.git", None),
("C:/repos/app", None),
("https://github.com", None),
] {
assert_eq!(canonical_remote(url).as_deref(), want, "{url}");
}
}
#[test]
fn project_id_falls_back_to_directory_name() {
let root = PathBuf::from("/Users/user/Apps/ExampleProj");
assert_eq!(project_id_for(&root, None).unwrap(), "exampleproj");
}
#[test]
fn routed_namespace_maps_fallback_to_none() {
assert_eq!(Routed::Existing("a".into()).namespace(), Some("a"));
assert_eq!(Routed::Registered("b".into()).namespace(), Some("b"));
assert_eq!(Routed::Fallback.namespace(), None);
assert_eq!(Routed::Fallback.unresolved(), None);
assert_eq!(Routed::Unresolved("x".into()).unresolved(), Some("x"));
}
#[tokio::test]
async fn failed_detection_is_unresolved_not_default_or_registered() {
let repo = tempfile::tempdir().unwrap();
let git = |args: &[&str]| {
std::process::Command::new("git")
.args(args)
.current_dir(repo.path())
.output()
.expect("git")
};
git(&["init", "-q"]);
git(&[
"remote",
"add",
"origin",
"https://example.com/acme/widgets.git",
]);
let cwd = repo.path().to_string_lossy().to_string();
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}");
for auto_register in [false, true] {
let mut router = Router::new(&server, auto_register, false, None);
let routed = router.route(Some(&cwd)).await;
assert!(
matches!(routed, Routed::Unresolved(ref why) if why.contains("unreachable")),
"auto_register={auto_register}: got {routed:?}"
);
assert_eq!(router.decisions().len(), 1);
}
}
#[tokio::test]
async fn no_cwd_uses_the_configured_fallback_namespace() {
let mut with = Router::new("http://127.0.0.1:0", false, true, Some("asd".into()));
assert_eq!(with.route(None).await.namespace(), Some("asd"));
assert_eq!(with.route(Some(" ")).await.namespace(), Some("asd"));
let mut without = Router::new("http://127.0.0.1:0", false, true, None);
assert_eq!(without.route(None).await.namespace(), None);
}
#[test]
fn dir_workspaces_routes_a_non_git_dir_to_its_basename() {
let base = std::env::temp_dir().join(format!("ctxone-dw-{}", std::process::id()));
let dir = base.join("My Scratch_App");
std::fs::create_dir_all(&dir).expect("mkdir temp");
let off = Router::new("http://127.0.0.1:0", true, true, None);
assert!(off.resolve_root(&dir).is_none());
assert!(off.would_register(&dir.to_string_lossy()).is_none());
let on = Router::new("http://127.0.0.1:0", true, true, None).with_dir_workspaces(true);
assert_eq!(on.resolve_root(&dir).as_deref(), Some(dir.as_path()));
assert_eq!(
on.would_register(&dir.to_string_lossy()).as_deref(),
Some("my-scratch-app")
);
let _ = std::fs::remove_dir_all(&base);
}
}