use std::time::{SystemTime, UNIX_EPOCH};
use crate::error::{CoreError, ErrorCode};
pub const MAX_ID_LEN: usize = 64;
pub const SLUG_PATTERN: &str = "^[a-z0-9][a-z0-9._-]{0,63}$";
pub const ULID_PATTERN: &str = "^[0-7][0-9A-HJKMNP-TV-Z]{25}$";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IdKind {
Server,
Skill,
Project,
SecretAlias,
EnvVar,
Machine,
Apply,
Store,
}
impl IdKind {
pub const fn noun(self) -> &'static str {
match self {
IdKind::Server => "server id",
IdKind::Skill => "skill id",
IdKind::Project => "project id",
IdKind::SecretAlias => "secret alias",
IdKind::EnvVar => "environment variable name",
IdKind::Machine => "machine id",
IdKind::Apply => "apply id",
IdKind::Store => "store id",
}
}
const fn rule(self) -> &'static str {
match self {
IdKind::Server | IdKind::Skill | IdKind::Project => {
"1 to 64 characters from a-z, 0-9, '.', '_', '-', starting with a letter or digit"
}
IdKind::SecretAlias => {
"1 to 64 characters from A-Z, a-z, 0-9, '_', not starting with a digit"
}
IdKind::EnvVar => "characters from A-Z, a-z, 0-9, '_', not starting with a digit",
IdKind::Machine | IdKind::Apply | IdKind::Store => {
"a ULID: 26 upper-case Crockford base32 characters"
}
}
}
}
pub fn is_valid(kind: IdKind, value: &str) -> bool {
match kind {
IdKind::Server | IdKind::Skill | IdKind::Project => is_slug(value),
IdKind::SecretAlias => value.len() <= MAX_ID_LEN && is_env_name(value),
IdKind::EnvVar => is_env_name(value),
IdKind::Machine | IdKind::Apply | IdKind::Store => is_ulid(value),
}
}
pub fn check(kind: IdKind, value: &str) -> Result<(), CoreError> {
if is_valid(kind, value) {
Ok(())
} else {
Err(CoreError::new(
ErrorCode::InvalidId,
invalid_message(kind, value),
))
}
}
pub(crate) fn invalid_message(kind: IdKind, value: &str) -> String {
format!(
"invalid {} {value:?}: expected {}",
kind.noun(),
kind.rule()
)
}
fn is_slug(value: &str) -> bool {
let bytes = value.as_bytes();
let Some(first) = bytes.first() else {
return false;
};
bytes.len() <= MAX_ID_LEN
&& (first.is_ascii_lowercase() || first.is_ascii_digit())
&& bytes.iter().all(|&b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
})
}
fn is_env_name(value: &str) -> bool {
let bytes = value.as_bytes();
let Some(first) = bytes.first() else {
return false;
};
(first.is_ascii_alphabetic() || *first == b'_')
&& bytes
.iter()
.all(|&b| b.is_ascii_alphanumeric() || b == b'_')
}
const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
fn is_ulid(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 26 && bytes[0] <= b'7' && bytes.iter().all(|b| CROCKFORD.contains(b))
}
pub fn new_ulid(time: SystemTime) -> Result<String, CoreError> {
let mut random = [0u8; 10];
getrandom::fill(&mut random).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot read random bytes for a new id: {err}"),
)
})?;
Ok(encode_ulid(time, random))
}
pub fn new_token() -> Result<String, CoreError> {
let mut random = [0u8; 16];
getrandom::fill(&mut random).map_err(|err| {
CoreError::new(
ErrorCode::IoError,
format!("cannot read random bytes for a token: {err}"),
)
})?;
Ok(random.iter().map(|byte| format!("{byte:02x}")).collect())
}
fn encode_ulid(time: SystemTime, random: [u8; 10]) -> String {
let millis = time
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_millis())
& ((1 << 48) - 1);
let value = random
.iter()
.fold(millis, |value, &byte| (value << 8) | u128::from(byte));
(0..26)
.map(|index| char::from(CROCKFORD[((value >> (125 - 5 * index)) & 31) as usize]))
.collect()
}
pub fn is_commit_id(value: &str) -> bool {
(7..=64).contains(&value.len())
&& value
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}