use std::hash::{BuildHasher, Hash, RandomState};
use std::sync::LazyLock;
use url::Url;
static KEYS: LazyLock<RandomState> = LazyLock::new(RandomState::new);
pub(crate) fn keyed_hash64(value: &impl Hash) -> u64 {
KEYS.hash_one(value)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EgressTier {
Baseline,
Guarded,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct EndpointFingerprint(u64);
impl std::fmt::Debug for EndpointFingerprint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("EndpointFingerprint(..)")
}
}
#[derive(Debug, Clone, Default)]
pub struct CachedEndpoint(std::sync::OnceLock<RegistryEndpoint>);
impl CachedEndpoint {
#[must_use]
pub const fn new() -> Self {
Self(std::sync::OnceLock::new())
}
pub fn get_or_compute(&self, compute: impl FnOnce() -> RegistryEndpoint) -> RegistryEndpoint {
*self.0.get_or_init(compute)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RegistryEndpoint {
Unresolved,
Resolved(EndpointFingerprint),
}
#[derive(Hash)]
struct HopIdentity<'a> {
scheme: &'a str,
host: &'a str,
port: Option<u16>,
path: &'a str,
egress: EgressTier,
}
impl RegistryEndpoint {
#[must_use]
pub fn base(url: &Url, egress: EgressTier) -> Self {
Self::chain([(url, egress)])
}
#[must_use]
pub fn from_base_str(base: &str, egress: EgressTier) -> Self {
Self::chain_from_strs([(base, egress)])
}
#[must_use]
pub fn chain_from_strs<'a>(hops: impl IntoIterator<Item = (&'a str, EgressTier)>) -> Self {
let parsed: Option<Vec<(Url, EgressTier)>> = hops
.into_iter()
.map(|(text, egress)| Url::parse(text).ok().map(|url| (url, egress)))
.collect();
parsed.map_or(Self::Unresolved, |hops| {
Self::chain(hops.iter().map(|(url, egress)| (url, *egress)))
})
}
#[must_use]
pub fn chain<'a>(hops: impl IntoIterator<Item = (&'a Url, EgressTier)>) -> Self {
let mut identities = Vec::new();
for (url, egress) in hops {
let Some(host) = url.host_str() else {
return Self::Unresolved;
};
let path = url.path();
identities.push(HopIdentity {
scheme: url.scheme(),
host,
port: url.port_or_known_default(),
path: path.strip_suffix('/').unwrap_or(path),
egress,
});
}
if identities.is_empty() {
return Self::Unresolved;
}
Self::Resolved(EndpointFingerprint(keyed_hash64(&identities)))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn url(text: &str) -> Url {
Url::parse(text).unwrap()
}
fn base(text: &str, egress: EgressTier) -> RegistryEndpoint {
RegistryEndpoint::base(&url(text), egress)
}
#[test]
fn userinfo_query_and_trailing_slash_do_not_change_the_endpoint() {
let plain = base("https://r.example/npm/", EgressTier::Baseline);
let decorated = base(
"https://user:pw@R.example:443/npm?token=1#frag",
EgressTier::Baseline,
);
assert_eq!(plain, decorated);
}
#[test]
fn path_port_scheme_and_egress_split_endpoints() {
let reference = base("https://r.example/api/npm/local/", EgressTier::Baseline);
for other in [
base("https://r.example/api/npm/remote/", EgressTier::Baseline),
base(
"https://r.example:8443/api/npm/local/",
EgressTier::Baseline,
),
base("http://r.example/api/npm/local/", EgressTier::Baseline),
base("https://r.example/api/npm/local/", EgressTier::Guarded),
] {
assert_ne!(reference, other);
}
}
#[test]
fn chain_order_and_length_are_part_of_the_identity() {
let (a, b) = (url("https://a.example/"), url("https://b.example/"));
let ab = RegistryEndpoint::chain([(&a, EgressTier::Baseline), (&b, EgressTier::Baseline)]);
let ba = RegistryEndpoint::chain([(&b, EgressTier::Baseline), (&a, EgressTier::Baseline)]);
let only_a = RegistryEndpoint::chain([(&a, EgressTier::Baseline)]);
assert_ne!(ab, ba);
assert_ne!(ab, only_a);
}
#[test]
fn hostless_or_empty_chains_are_unresolved() {
assert_eq!(
RegistryEndpoint::chain(std::iter::empty()),
RegistryEndpoint::Unresolved
);
assert_eq!(
base("file:///tmp/index", EgressTier::Baseline),
RegistryEndpoint::Unresolved
);
}
#[test]
fn debug_hides_the_fingerprint_value() {
let endpoint = base("https://r.example/", EgressTier::Baseline);
assert_eq!(format!("{endpoint:?}"), "Resolved(EndpointFingerprint(..))");
}
#[test]
fn keyed_hash_is_stable_within_a_process() {
assert_eq!(keyed_hash64(&"x"), keyed_hash64(&"x"));
}
}