use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
mod exemption;
mod scope;
pub use exemption::{Exemption, ExemptionError, ExemptionList, ExemptionSyntax, parse_exemptions};
pub use scope::RepositoryScope;
use crate::lsp_helpers::{ResolvedCandidatesMap, ResolvedVersionsMap, VersionData};
use crate::{ConcreteVersion, CooldownWindow, Dependency, NormalizedName, PackageKey, PublishTime};
const MINUTE: u64 = 60;
const HOUR: u64 = 60 * MINUTE;
const DAY: u64 = 24 * HOUR;
const WEEK: u64 = 7 * DAY;
const MONTH: u64 = 2_629_746;
const MAX_WINDOW_SECS: u64 = 10 * 365 * DAY;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeUnit {
Second,
Minute,
Hour,
Day,
Week,
Month,
}
impl TimeUnit {
const fn secs(self) -> u64 {
match self {
Self::Second => 1,
Self::Minute => MINUTE,
Self::Hour => HOUR,
Self::Day => DAY,
Self::Week => WEEK,
Self::Month => MONTH,
}
}
const fn singular(self) -> &'static str {
match self {
Self::Second => "second",
Self::Minute => "minute",
Self::Hour => "hour",
Self::Day => "day",
Self::Week => "week",
Self::Month => "month",
}
}
fn from_word(word: &str) -> Option<Self> {
let singular = word.strip_suffix('s').unwrap_or(word);
[
Self::Second,
Self::Minute,
Self::Hour,
Self::Day,
Self::Week,
Self::Month,
]
.into_iter()
.find(|unit| unit.singular() == singular)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativeTimeSpan {
count: u64,
unit: TimeUnit,
secs: u64,
}
impl NativeTimeSpan {
pub fn from_count(count: u64, unit: TimeUnit) -> Result<TimeSpanValue, TimeSpanError> {
if count == 0 {
return Ok(TimeSpanValue::Disabled);
}
let secs = count
.checked_mul(unit.secs())
.ok_or(TimeSpanError::Overflow)?;
Ok(TimeSpanValue::Span(Self { count, unit, secs }))
}
const fn as_secs(self) -> u64 {
self.secs
}
}
impl fmt::Display for NativeTimeSpan {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let plural = if self.count == 1 { "" } else { "s" };
write!(f, "{} {}{plural}", self.count, self.unit.singular())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeSpanValue {
Disabled,
Span(NativeTimeSpan),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum TimeSpanError {
#[error("not a valid time span")]
Malformed,
#[error("time span overflows")]
Overflow,
}
pub fn parse_time_span(raw: &str) -> Result<TimeSpanValue, TimeSpanError> {
if raw == "0" {
return Ok(TimeSpanValue::Disabled);
}
let digits_len = raw.bytes().take_while(u8::is_ascii_digit).count();
let (digits, rest) = raw.split_at(digits_len);
if digits.is_empty() {
return Err(TimeSpanError::Malformed);
}
let word = rest.strip_prefix(' ').unwrap_or(rest);
let unit = TimeUnit::from_word(word).ok_or(TimeSpanError::Malformed)?;
let count: u64 = digits.parse().map_err(|_| TimeSpanError::Overflow)?;
NativeTimeSpan::from_count(count, unit)
}
pub fn parse_uv_span(raw: &str) -> Result<TimeSpanValue, TimeSpanError> {
let parsed = match raw.strip_prefix(['P', 'p']) {
Some(iso) => parse_iso_term(iso),
None => split_count(raw).and_then(|(count, rest)| Some((count, friendly_unit(rest)?))),
};
let (count, unit) = parsed.ok_or(TimeSpanError::Malformed)?;
NativeTimeSpan::from_count(count?, unit)
}
pub fn parse_yarn_duration(raw: &str) -> Result<TimeSpanValue, TimeSpanError> {
let number = YarnNumber::split(raw).ok_or(TimeSpanError::Malformed)?;
if number.mantissa_is_zero() {
return Ok(TimeSpanValue::Disabled);
}
match (number.fraction_len, number.unit) {
(0, YarnUnit::Exact(unit)) => {
let count = number
.mantissa
.parse()
.map_err(|_| TimeSpanError::Overflow)?;
NativeTimeSpan::from_count(count, unit)
}
(fraction_len, unit) => number.rounded_span(fraction_len, unit),
}
}
#[derive(Debug, Clone, Copy)]
enum YarnUnit {
Exact(TimeUnit),
Millis,
}
struct YarnNumber {
mantissa: String,
fraction_len: u32,
unit: YarnUnit,
}
impl YarnNumber {
const MAX_FRACTION_DIGITS: u32 = 18;
fn split(raw: &str) -> Option<Self> {
let int_len = raw.bytes().take_while(u8::is_ascii_digit).count();
let (int_digits, rest) = raw.split_at(int_len);
let (fraction, rest) = match rest.strip_prefix('.') {
Some(after) => {
let len = after.bytes().take_while(u8::is_ascii_digit).count();
if len == 0 {
return None;
}
after.split_at(len)
}
None => ("", rest),
};
if int_digits.is_empty() && fraction.is_empty() {
return None;
}
let unit = match rest {
"" | "m" => YarnUnit::Exact(TimeUnit::Minute),
"s" => YarnUnit::Exact(TimeUnit::Second),
"h" => YarnUnit::Exact(TimeUnit::Hour),
"d" => YarnUnit::Exact(TimeUnit::Day),
"w" => YarnUnit::Exact(TimeUnit::Week),
"ms" => YarnUnit::Millis,
_ => return None,
};
let fraction = fraction.trim_end_matches('0');
Some(Self {
mantissa: format!("{int_digits}{fraction}"),
fraction_len: u32::try_from(fraction.len()).unwrap_or(u32::MAX),
unit,
})
}
fn mantissa_is_zero(&self) -> bool {
self.mantissa.bytes().all(|b| b == b'0')
}
fn rounded_span(
&self,
fraction_len: u32,
unit: YarnUnit,
) -> Result<TimeSpanValue, TimeSpanError> {
if fraction_len > Self::MAX_FRACTION_DIGITS {
return Err(TimeSpanError::Overflow);
}
let unit_millis: u128 = match unit {
YarnUnit::Exact(unit) => u128::from(unit.secs()) * 1000,
YarnUnit::Millis => 1,
};
let mantissa: u128 = self.mantissa.parse().map_err(|_| TimeSpanError::Overflow)?;
let scaled_millis = mantissa
.checked_mul(unit_millis)
.ok_or(TimeSpanError::Overflow)?;
let denominator = 10_u128.pow(fraction_len) * 1000;
let secs = u64::try_from(scaled_millis.div_ceil(denominator))
.map_err(|_| TimeSpanError::Overflow)?;
let unit = [
TimeUnit::Week,
TimeUnit::Day,
TimeUnit::Hour,
TimeUnit::Minute,
TimeUnit::Second,
]
.into_iter()
.find(|unit| secs % unit.secs() == 0)
.unwrap_or(TimeUnit::Second);
NativeTimeSpan::from_count(secs / unit.secs(), unit)
}
}
type CountAndUnit = (Result<u64, TimeSpanError>, TimeUnit);
fn split_count(text: &str) -> Option<(Result<u64, TimeSpanError>, &str)> {
let digits_len = text.bytes().take_while(u8::is_ascii_digit).count();
let (digits, rest) = text.split_at(digits_len);
(!digits.is_empty()).then(|| (digits.parse().map_err(|_| TimeSpanError::Overflow), rest))
}
fn parse_iso_term(iso: &str) -> Option<CountAndUnit> {
let (time_part, body) = match iso.strip_prefix(['T', 't']) {
Some(body) => (true, body),
None => (false, iso),
};
let (count, designator) = split_count(body)?;
let unit = match (time_part, designator.to_ascii_uppercase().as_str()) {
(false, "W") => TimeUnit::Week,
(false, "D") => TimeUnit::Day,
(true, "H") => TimeUnit::Hour,
(true, "M") => TimeUnit::Minute,
(true, "S") => TimeUnit::Second,
_ => return None,
};
Some((count, unit))
}
fn friendly_unit(rest: &str) -> Option<TimeUnit> {
let word = rest.strip_prefix(' ').unwrap_or(rest).to_ascii_lowercase();
match word.as_str() {
"second" | "seconds" | "sec" | "secs" => Some(TimeUnit::Second),
"minute" | "minutes" | "min" | "mins" => Some(TimeUnit::Minute),
"hour" | "hours" | "hr" | "hrs" => Some(TimeUnit::Hour),
"day" | "days" => Some(TimeUnit::Day),
"week" | "weeks" | "wk" | "wks" => Some(TimeUnit::Week),
_ => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativeCutoff(PublishTime);
impl NativeCutoff {
#[must_use]
pub fn parse_rfc3339(raw: &str) -> Option<Self> {
PublishTime::parse_rfc3339(raw).map(Self)
}
#[must_use]
pub fn parse_npm_date(raw: &str) -> Option<Self> {
let date_only = raw.len() == 10
&& raw.bytes().enumerate().all(|(i, b)| {
if matches!(i, 4 | 7) {
b == b'-'
} else {
b.is_ascii_digit()
}
});
if date_only {
PublishTime::parse_rfc3339(&format!("{raw}T00:00:00Z")).map(Self)
} else {
Self::parse_rfc3339(raw)
}
}
}
impl fmt::Display for NativeCutoff {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let secs = self.0.as_unix_secs();
let (days, day_secs) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
let (year, month, day) = civil_from_days(days);
write!(
f,
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
day_secs / 3600,
day_secs % 3600 / 60,
day_secs % 60
)
}
}
const fn civil_from_days(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
(year, month, day)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeLimit {
MinAge(NativeTimeSpan),
PublishedAfter(NativeCutoff),
}
impl fmt::Display for NativeLimit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MinAge(span) => span.fmt(f),
Self::PublishedAfter(cutoff) => cutoff.fmt(f),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeHold {
For(u64),
Indefinite,
}
impl NativeHold {
#[must_use]
pub fn eligibility_clause(self) -> String {
match self {
Self::For(secs) => format!("eligible in {}", crate::format_remaining_duration(secs)),
Self::Indefinite => "not eligible while the cutoff stays in place".to_owned(),
}
}
}
fn is_safe_label(name: &str, max_len: usize) -> bool {
!name.is_empty()
&& name.len() <= max_len
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PypiPackageLabel(String);
impl PypiPackageLabel {
const MAX_LEN: usize = 128;
#[must_use]
pub fn new(name: &str) -> Option<Self> {
is_safe_label(name, Self::MAX_LEN).then(|| Self(name.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NpmScopeLabel(String);
impl NpmScopeLabel {
const MAX_LEN: usize = 214;
#[must_use]
pub fn new(scope: &str) -> Option<Self> {
is_safe_label(scope, Self::MAX_LEN).then(|| Self(scope.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UvIndexLabel(String);
impl UvIndexLabel {
#[must_use]
pub fn new(name: &str) -> Option<Self> {
is_safe_label(name, PypiPackageLabel::MAX_LEN).then(|| Self(name.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateOrigin {
Configured,
ManagerDefault,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NativeWindow(CooldownWindow);
impl NativeWindow {
fn new(span: NativeTimeSpan) -> Self {
Self(CooldownWindow::from_secs(
span.as_secs().min(MAX_WINDOW_SECS),
))
}
#[must_use]
pub const fn contains(self, age_secs: u64) -> bool {
self.0.contains(age_secs)
}
const fn as_secs(self) -> u64 {
self.0.as_secs()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegistryAlias(String);
impl RegistryAlias {
const MAX_LEN: usize = 64;
#[must_use]
pub fn new(alias: &str) -> Option<Self> {
let valid = !alias.is_empty()
&& alias.len() <= Self::MAX_LEN
&& alias
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
valid.then(|| Self(alias.to_owned()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NativeCooldownSource {
CargoGlobal,
CargoRegistry {
alias: RegistryAlias,
},
NpmMinReleaseAge,
NpmBefore,
PnpmMinimumReleaseAge,
BunMinimumReleaseAge,
UvExcludeNewer,
UvExcludeNewerPackage {
package: PypiPackageLabel,
},
YarnNpmMinimalAgeGate,
YarnScopeNpmMinimalAgeGate {
scope: NpmScopeLabel,
origin: GateOrigin,
},
UvIndexExcludeNewer {
index: UvIndexLabel,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeCooldown {
limit: NativeLimit,
source: NativeCooldownSource,
exempt_versions: Arc<[ConcreteVersion]>,
}
impl NativeCooldown {
#[must_use]
pub fn new(limit: NativeLimit, source: NativeCooldownSource) -> Self {
Self {
limit,
source,
exempt_versions: Arc::from([]),
}
}
#[must_use]
pub fn with_exempt_versions(mut self, versions: Arc<[ConcreteVersion]>) -> Self {
self.exempt_versions = versions;
self
}
#[must_use]
pub const fn limit(&self) -> &NativeLimit {
&self.limit
}
#[must_use]
pub fn hold(
&self,
published_at: Option<PublishTime>,
version: &ConcreteVersion,
now: PublishTime,
) -> Option<NativeHold> {
if self.exempt_versions.contains(version) {
return None;
}
let published_at = published_at?;
match self.limit {
NativeLimit::MinAge(span) => {
let window = NativeWindow::new(span);
let age = published_at.age_secs_from(now);
window
.contains(age)
.then(|| NativeHold::For(window.as_secs() - age))
}
NativeLimit::PublishedAfter(cutoff) => (published_at.as_unix_secs()
> cutoff.0.as_unix_secs())
.then_some(NativeHold::Indefinite),
}
}
#[must_use]
pub const fn source(&self) -> &NativeCooldownSource {
&self.source
}
#[must_use]
pub fn age_window(&self) -> Option<NativeWindow> {
match self.limit {
NativeLimit::MinAge(span) => Some(NativeWindow::new(span)),
NativeLimit::PublishedAfter(_) => None,
}
}
}
impl fmt::Display for NativeCooldown {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let limit = &self.limit;
match &self.source {
NativeCooldownSource::CargoGlobal => {
write!(f, "cargo registry.global-min-publish-age = {limit}")
}
NativeCooldownSource::CargoRegistry { alias } => {
write!(
f,
"cargo registries.{}.min-publish-age = {limit}",
alias.as_str()
)
}
NativeCooldownSource::NpmMinReleaseAge => {
write!(f, "npm min-release-age = {limit}")
}
NativeCooldownSource::NpmBefore => write!(f, "npm before = {limit}"),
NativeCooldownSource::PnpmMinimumReleaseAge => {
write!(f, "pnpm minimumReleaseAge = {limit}")
}
NativeCooldownSource::BunMinimumReleaseAge => {
write!(f, "bun minimumReleaseAge = {limit}")
}
NativeCooldownSource::UvExcludeNewer => write!(f, "uv exclude-newer = {limit}"),
NativeCooldownSource::UvExcludeNewerPackage { package } => {
write!(f, "uv exclude-newer-package.{} = {limit}", package.as_str())
}
NativeCooldownSource::YarnNpmMinimalAgeGate => {
write!(f, "yarn npmMinimalAgeGate = {limit}")
}
NativeCooldownSource::YarnScopeNpmMinimalAgeGate { scope, origin } => {
write!(
f,
"yarn npmScopes.{}.npmMinimalAgeGate = {limit}",
scope.as_str()
)?;
match origin {
GateOrigin::Configured => Ok(()),
GateOrigin::ManagerDefault => f.write_str(" (Yarn default)"),
}
}
NativeCooldownSource::UvIndexExcludeNewer { index } => {
write!(f, "uv index.{}.exclude-newer = {limit}", index.as_str())
}
}
}
}
#[derive(Debug, Clone)]
pub struct NativeGate<'a> {
cooldown: &'a NativeCooldown,
name: NormalizedName,
resolved: &'a ResolvedVersionsMap,
candidates: Option<&'a ResolvedCandidatesMap>,
now: PublishTime,
}
impl<'a> NativeGate<'a> {
#[must_use]
pub fn for_dependency(
dep: &'a dyn Dependency,
key: &PackageKey,
versions: &VersionData<'a>,
) -> Option<Self> {
Some(Self::for_name(
dep.native_cooldown()?,
key.normalized(),
versions,
))
}
#[must_use]
pub fn for_name(
cooldown: &'a NativeCooldown,
name: &NormalizedName,
versions: &VersionData<'a>,
) -> Self {
Self {
cooldown,
name: name.clone(),
resolved: versions.resolved_map(),
candidates: versions.candidates_map(),
now: versions.now,
}
}
#[must_use]
pub const fn cooldown(&self) -> &'a NativeCooldown {
self.cooldown
}
#[must_use]
pub const fn now(&self) -> PublishTime {
self.now
}
fn is_locked(&self, version: &ConcreteVersion) -> bool {
self.resolved.get(&self.name) == Some(version)
|| self
.candidates
.and_then(|candidates| candidates.get(&self.name))
.is_some_and(|candidates| candidates.versions().contains(version))
}
#[must_use]
pub fn hold(
&self,
published_at: Option<PublishTime>,
version: &ConcreteVersion,
now: PublishTime,
) -> Option<NativeHold> {
if self.is_locked(version) {
return None;
}
self.cooldown.hold(published_at, version, now)
}
#[must_use]
pub fn excludes(
&self,
published_at: Option<PublishTime>,
version: &ConcreteVersion,
now: PublishTime,
) -> bool {
self.hold(published_at, version, now).is_some()
}
}
#[must_use]
pub fn native_cooldowns_by_name(
parse_result: &dyn crate::ParsedManifest,
) -> HashMap<NormalizedName, NativeCooldown> {
let mut seen: HashMap<NormalizedName, Option<NativeCooldown>> = HashMap::new();
parse_result.for_each_formatted_dependency(&mut |bound| {
let dependency = bound.dependency();
let key = PackageKey::new(dependency.name(), bound.formatter());
let cooldown = dependency.native_cooldown().cloned();
seen.entry(key.normalized().clone())
.and_modify(|existing| {
if *existing != cooldown {
*existing = None;
}
})
.or_insert(cooldown);
});
seen.into_iter()
.filter_map(|(name, cooldown)| Some((name, cooldown?)))
.collect()
}