use std::{fmt, num::NonZeroU64, str::FromStr};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
macro_rules! identity {
($($name:ident),+ $(,)?) => {$(
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[serde(transparent)]
pub struct $name(Uuid);
impl $name {
#[expect(
clippy::new_without_default,
reason = "a default would be a fresh random ID, which reads like a neutral value"
)]
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(uuid: Uuid) -> Self {
Self(uuid)
}
pub fn as_uuid(&self) -> Uuid {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl FromStr for $name {
type Err = uuid::Error;
fn from_str(input: &str) -> Result<Self, Self::Err> {
Uuid::parse_str(input).map(Self)
}
}
#[cfg(feature = "sql")]
impl rusqlite::ToSql for $name {
fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
Ok(rusqlite::types::ToSqlOutput::from(self.to_string()))
}
}
#[cfg(feature = "sql")]
impl rusqlite::types::FromSql for $name {
fn column_result(
value: rusqlite::types::ValueRef<'_>,
) -> rusqlite::types::FromSqlResult<Self> {
value
.as_str()?
.parse()
.map_err(|error| rusqlite::types::FromSqlError::Other(Box::new(error)))
}
}
)+};
}
identity!(
BackupId,
NetworkId,
ServiceId,
InstanceId,
NodeId,
ClusterId,
AgentId,
WorkloadId,
RevisionId,
VolumeId,
LedgerId,
WorkspaceId,
WorkspaceAttachmentId,
WorkspaceGrantId,
AttemptId,
CheckpointId,
EgressGrantId,
OperationId,
ReplicaId,
JobRunId,
JobGroupId,
PreparationId,
RequestId,
TransferId,
DiskStagingId,
TemplateId,
TicketId,
PoolId,
LeaseId,
ProjectId,
TokenId,
RelocationId,
LeaseToken,
ReporterId,
ReporterEpoch,
ObserverId,
);
impl ProjectId {
pub const DEFAULT: Self = Self(Uuid::from_u128(1));
}
impl TokenId {
pub fn simple(&self) -> String {
self.0.simple().to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AgentTag {
pub id: AgentId,
pub generation: NonZeroU64,
}
impl RequestId {
pub fn internal() -> Self {
let mut bytes = *Uuid::new_v4().as_bytes();
bytes[..6].copy_from_slice(b"capsid");
bytes[6] = (bytes[6] & 0x0f) | 0x80;
Self(Uuid::from_bytes(bytes))
}
pub fn is_internal(self) -> bool {
self.0.as_bytes()[..6] == *b"capsid" && self.0.as_bytes()[6] >> 4 == 8
}
}