1use std::{fmt, num::NonZeroU64, str::FromStr};
2
3use serde::{Deserialize, Serialize};
4use uuid::Uuid;
5
6macro_rules! identity {
7 ($($name:ident),+ $(,)?) => {$(
8 #[derive(
9 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
10 )]
11 #[serde(transparent)]
12 pub struct $name(Uuid);
13
14 impl $name {
15 #[expect(
16 clippy::new_without_default,
17 reason = "a default would be a fresh random ID, which reads like a neutral value"
18 )]
19 pub fn new() -> Self {
20 Self(Uuid::new_v4())
21 }
22
23 pub fn from_uuid(uuid: Uuid) -> Self {
24 Self(uuid)
25 }
26
27 pub fn as_uuid(&self) -> Uuid {
28 self.0
29 }
30 }
31
32 impl fmt::Display for $name {
33 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34 self.0.fmt(formatter)
35 }
36 }
37
38 impl FromStr for $name {
39 type Err = uuid::Error;
40
41 fn from_str(input: &str) -> Result<Self, Self::Err> {
42 Uuid::parse_str(input).map(Self)
43 }
44 }
45
46 #[cfg(feature = "sql")]
47 impl rusqlite::ToSql for $name {
48 fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
49 Ok(rusqlite::types::ToSqlOutput::from(self.to_string()))
50 }
51 }
52
53 #[cfg(feature = "sql")]
54 impl rusqlite::types::FromSql for $name {
55 fn column_result(
56 value: rusqlite::types::ValueRef<'_>,
57 ) -> rusqlite::types::FromSqlResult<Self> {
58 value
59 .as_str()?
60 .parse()
61 .map_err(|error| rusqlite::types::FromSqlError::Other(Box::new(error)))
62 }
63 }
64 )+};
65}
66
67identity!(
68 BackupId,
69 NetworkId,
70 ServiceId,
71 InstanceId,
72 NodeId,
73 ClusterId,
74 AgentId,
75 WorkloadId,
76 RevisionId,
77 VolumeId,
78 LedgerId,
79 WorkspaceId,
80 WorkspaceAttachmentId,
81 WorkspaceGrantId,
82 AttemptId,
83 CheckpointId,
84 EgressGrantId,
85 OperationId,
86 ReplicaId,
87 JobRunId,
88 JobGroupId,
89 PreparationId,
90 RequestId,
91 TransferId,
92 DiskStagingId,
93 TemplateId,
94 TicketId,
95 PoolId,
96 LeaseId,
97 ProjectId,
98 TokenId,
99 RelocationId,
100 LeaseToken,
101 ReporterId,
102 ReporterEpoch,
103 ObserverId,
104);
105
106impl ProjectId {
107 pub const DEFAULT: Self = Self(Uuid::from_u128(1));
109}
110
111impl TokenId {
112 pub fn simple(&self) -> String {
114 self.0.simple().to_string()
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(deny_unknown_fields)]
120pub struct AgentTag {
121 pub id: AgentId,
122
123 pub generation: NonZeroU64,
124}
125
126impl RequestId {
127 pub fn internal() -> Self {
128 let mut bytes = *Uuid::new_v4().as_bytes();
129 bytes[..6].copy_from_slice(b"capsid");
130 bytes[6] = (bytes[6] & 0x0f) | 0x80;
131 Self(Uuid::from_bytes(bytes))
132 }
133
134 pub fn is_internal(self) -> bool {
135 self.0.as_bytes()[..6] == *b"capsid" && self.0.as_bytes()[6] >> 4 == 8
136 }
137}