surjection_core/model/
ids.rs1use std::time::{SystemTime, UNIX_EPOCH};
6
7use crate::error::{CoreError, ErrorCode};
8
9pub const MAX_ID_LEN: usize = 64;
11
12pub const SLUG_PATTERN: &str = "^[a-z0-9][a-z0-9._-]{0,63}$";
14pub const ULID_PATTERN: &str = "^[0-7][0-9A-HJKMNP-TV-Z]{25}$";
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum IdKind {
20 Server,
22 Skill,
24 Project,
26 SecretAlias,
29 EnvVar,
31 Machine,
33 Apply,
35 Store,
37}
38
39impl IdKind {
40 pub const fn noun(self) -> &'static str {
42 match self {
43 IdKind::Server => "server id",
44 IdKind::Skill => "skill id",
45 IdKind::Project => "project id",
46 IdKind::SecretAlias => "secret alias",
47 IdKind::EnvVar => "environment variable name",
48 IdKind::Machine => "machine id",
49 IdKind::Apply => "apply id",
50 IdKind::Store => "store id",
51 }
52 }
53
54 const fn rule(self) -> &'static str {
55 match self {
56 IdKind::Server | IdKind::Skill | IdKind::Project => {
57 "1 to 64 characters from a-z, 0-9, '.', '_', '-', starting with a letter or digit"
58 }
59 IdKind::SecretAlias => {
60 "1 to 64 characters from A-Z, a-z, 0-9, '_', not starting with a digit"
61 }
62 IdKind::EnvVar => "characters from A-Z, a-z, 0-9, '_', not starting with a digit",
63 IdKind::Machine | IdKind::Apply | IdKind::Store => {
64 "a ULID: 26 upper-case Crockford base32 characters"
65 }
66 }
67 }
68}
69
70pub fn is_valid(kind: IdKind, value: &str) -> bool {
72 match kind {
73 IdKind::Server | IdKind::Skill | IdKind::Project => is_slug(value),
74 IdKind::SecretAlias => value.len() <= MAX_ID_LEN && is_env_name(value),
75 IdKind::EnvVar => is_env_name(value),
76 IdKind::Machine | IdKind::Apply | IdKind::Store => is_ulid(value),
77 }
78}
79
80pub fn check(kind: IdKind, value: &str) -> Result<(), CoreError> {
82 if is_valid(kind, value) {
83 Ok(())
84 } else {
85 Err(CoreError::new(
86 ErrorCode::InvalidId,
87 invalid_message(kind, value),
88 ))
89 }
90}
91
92pub(crate) fn invalid_message(kind: IdKind, value: &str) -> String {
94 format!(
95 "invalid {} {value:?}: expected {}",
96 kind.noun(),
97 kind.rule()
98 )
99}
100
101fn is_slug(value: &str) -> bool {
102 let bytes = value.as_bytes();
103 let Some(first) = bytes.first() else {
104 return false;
105 };
106 bytes.len() <= MAX_ID_LEN
107 && (first.is_ascii_lowercase() || first.is_ascii_digit())
108 && bytes.iter().all(|&b| {
109 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-')
110 })
111}
112
113fn is_env_name(value: &str) -> bool {
114 let bytes = value.as_bytes();
115 let Some(first) = bytes.first() else {
116 return false;
117 };
118 (first.is_ascii_alphabetic() || *first == b'_')
119 && bytes
120 .iter()
121 .all(|&b| b.is_ascii_alphanumeric() || b == b'_')
122}
123
124const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
126
127fn is_ulid(value: &str) -> bool {
128 let bytes = value.as_bytes();
129 bytes.len() == 26 && bytes[0] <= b'7' && bytes.iter().all(|b| CROCKFORD.contains(b))
131}
132
133pub fn new_ulid(time: SystemTime) -> Result<String, CoreError> {
136 let mut random = [0u8; 10];
137 getrandom::fill(&mut random).map_err(|err| {
138 CoreError::new(
139 ErrorCode::IoError,
140 format!("cannot read random bytes for a new id: {err}"),
141 )
142 })?;
143 Ok(encode_ulid(time, random))
144}
145
146pub fn new_token() -> Result<String, CoreError> {
149 let mut random = [0u8; 16];
150 getrandom::fill(&mut random).map_err(|err| {
151 CoreError::new(
152 ErrorCode::IoError,
153 format!("cannot read random bytes for a token: {err}"),
154 )
155 })?;
156 Ok(random.iter().map(|byte| format!("{byte:02x}")).collect())
157}
158
159fn encode_ulid(time: SystemTime, random: [u8; 10]) -> String {
160 let millis = time
161 .duration_since(UNIX_EPOCH)
162 .map_or(0, |elapsed| elapsed.as_millis())
163 & ((1 << 48) - 1);
164 let value = random
165 .iter()
166 .fold(millis, |value, &byte| (value << 8) | u128::from(byte));
167 (0..26)
168 .map(|index| char::from(CROCKFORD[((value >> (125 - 5 * index)) & 31) as usize]))
169 .collect()
170}
171
172pub fn is_commit_id(value: &str) -> bool {
174 (7..=64).contains(&value.len())
175 && value
176 .bytes()
177 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
178}