1use std::{fmt, str::FromStr};
4
5use uuid::Uuid;
6
7use crate::{Error, ErrorKind, Result};
8
9macro_rules! strong_id {
10 ($(#[$metadata:meta])* $name:ident) => {
11 $(#[$metadata])*
12 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
13 pub struct $name(Uuid);
14
15 impl $name {
16 #[must_use]
18 pub fn new() -> Self {
19 Self(Uuid::new_v4())
20 }
21
22 #[must_use]
24 pub const fn from_bytes(bytes: [u8; 16]) -> Self {
25 Self(Uuid::from_bytes(bytes))
26 }
27
28 #[must_use]
30 pub const fn into_bytes(self) -> [u8; 16] {
31 self.0.into_bytes()
32 }
33
34 #[must_use]
36 pub const fn as_bytes(&self) -> &[u8; 16] {
37 self.0.as_bytes()
38 }
39 }
40
41 impl Default for $name {
42 fn default() -> Self {
43 Self::new()
44 }
45 }
46
47 impl fmt::Display for $name {
48 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
49 self.0.fmt(formatter)
50 }
51 }
52
53 impl FromStr for $name {
54 type Err = Error;
55
56 fn from_str(value: &str) -> Result<Self> {
57 Uuid::parse_str(value).map(Self).map_err(|error| {
58 Error::new(
59 ErrorKind::InvalidArgument,
60 format!("invalid {}: {error}", stringify!($name)),
61 )
62 })
63 }
64 }
65 };
66}
67
68strong_id!(
69 ProductionId
71);
72strong_id!(
73 AssetId
75);
76strong_id!(
77 RepresentationId
79);
80strong_id!(
81 ResourceId
83);
84strong_id!(
85 LocatorId
87);
88strong_id!(
89 MediaRootId
91);
92strong_id!(
93 ActivityId
95);
96strong_id!(
97 JobId
99);
100strong_id!(
101 JobClaimId
103);
104strong_id!(
105 RevisionId
107);
108strong_id!(
109 TransactionId
111);
112
113#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115#[non_exhaustive]
116pub enum ObjectRef {
117 Production(ProductionId),
119 Asset(AssetId),
121 Representation(RepresentationId),
123 Resource(ResourceId),
125 Activity(ActivityId),
127 Job(JobId),
129}
130
131#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
133pub struct HostObjectBinding {
134 production_id: ProductionId,
135 object: ObjectRef,
136}
137
138impl HostObjectBinding {
139 pub fn new(production_id: ProductionId, object: ObjectRef) -> Result<Self> {
146 if let ObjectRef::Production(object_id) = object {
147 if object_id != production_id {
148 return Err(Error::new(
149 ErrorKind::InvalidArgument,
150 "a production binding must reference its containing production",
151 ));
152 }
153 }
154 Ok(Self {
155 production_id,
156 object,
157 })
158 }
159
160 #[must_use]
162 pub const fn production_id(self) -> ProductionId {
163 self.production_id
164 }
165
166 #[must_use]
168 pub const fn object(self) -> ObjectRef {
169 self.object
170 }
171}
172
173impl fmt::Display for HostObjectBinding {
174 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
175 let (kind, object_id) = match self.object {
176 ObjectRef::Production(id) => ("production", id.to_string()),
177 ObjectRef::Asset(id) => ("asset", id.to_string()),
178 ObjectRef::Representation(id) => ("representation", id.to_string()),
179 ObjectRef::Resource(id) => ("resource", id.to_string()),
180 ObjectRef::Activity(id) => ("activity", id.to_string()),
181 ObjectRef::Job(id) => ("job", id.to_string()),
182 };
183 write!(
184 formatter,
185 "https://postproject.org/ref/v1/{}/{kind}/{object_id}",
186 self.production_id
187 )
188 }
189}
190
191impl FromStr for HostObjectBinding {
192 type Err = Error;
193
194 fn from_str(value: &str) -> Result<Self> {
195 let Some(path) = value.strip_prefix("https://postproject.org/ref/v1/") else {
196 return Err(invalid_binding());
197 };
198 let mut parts = path.split('/');
199 let (Some(production_id), Some(kind), Some(object_id)) =
200 (parts.next(), parts.next(), parts.next())
201 else {
202 return Err(invalid_binding());
203 };
204 if parts.next().is_some() {
205 return Err(invalid_binding());
206 }
207 let production_id = parse_canonical_id::<ProductionId>(production_id, "production UUID")?;
208 let object = match kind {
209 "production" => ObjectRef::Production(parse_canonical_id(object_id, "object UUID")?),
210 "asset" => ObjectRef::Asset(parse_canonical_id(object_id, "object UUID")?),
211 "representation" => {
212 ObjectRef::Representation(parse_canonical_id(object_id, "object UUID")?)
213 }
214 "resource" => ObjectRef::Resource(parse_canonical_id(object_id, "object UUID")?),
215 "activity" => ObjectRef::Activity(parse_canonical_id(object_id, "object UUID")?),
216 "job" => ObjectRef::Job(parse_canonical_id(object_id, "object UUID")?),
217 _ => return Err(invalid_binding()),
218 };
219 Self::new(production_id, object)
220 }
221}
222
223fn parse_canonical_id<T>(value: &str, label: &str) -> Result<T>
224where
225 T: FromStr<Err = Error> + fmt::Display,
226{
227 let parsed = T::from_str(value)?;
228 if parsed.to_string() != value {
229 return Err(Error::new(
230 ErrorKind::InvalidArgument,
231 format!("host binding {label} must use canonical lowercase UUID text"),
232 ));
233 }
234 Ok(parsed)
235}
236
237fn invalid_binding() -> Error {
238 Error::new(
239 ErrorKind::InvalidArgument,
240 "host binding must be https://postproject.org/ref/v1/<production UUID>/<object kind>/<object UUID>",
241 )
242}
243
244#[cfg(test)]
245mod tests {
246 use proptest::prelude::*;
247
248 use super::*;
249
250 proptest! {
251 #[test]
252 fn production_id_byte_and_text_round_trips(bytes in any::<[u8; 16]>()) {
253 let id = ProductionId::from_bytes(bytes);
254 prop_assert_eq!(ProductionId::from_str(&id.to_string()), Ok(id));
255 prop_assert_eq!(id.into_bytes(), bytes);
256 }
257 }
258
259 #[test]
260 fn identifier_types_are_not_interchangeable() {
261 let bytes = [7; 16];
262 let production = ProductionId::from_bytes(bytes);
263 let asset = AssetId::from_bytes(bytes);
264 let resource = ResourceId::from_bytes(bytes);
265 let locator = LocatorId::from_bytes(bytes);
266
267 assert_eq!(production.as_bytes(), asset.as_bytes());
268 assert_eq!(production.to_string(), asset.to_string());
269 assert_eq!(resource.as_bytes(), locator.as_bytes());
270 }
271
272 #[test]
273 fn object_references_preserve_identity_level() {
274 let bytes = [9; 16];
275 assert_ne!(
276 ObjectRef::Asset(AssetId::from_bytes(bytes)),
277 ObjectRef::Representation(RepresentationId::from_bytes(bytes))
278 );
279 }
280
281 #[test]
282 fn invalid_text_has_stable_error_kind() {
283 let error = AssetId::from_str("not-a-uuid").expect_err("text must be rejected");
284 assert_eq!(error.kind(), ErrorKind::InvalidArgument);
285 }
286
287 #[test]
288 fn host_bindings_round_trip_each_object_kind() {
289 let production_id = ProductionId::from_bytes([1; 16]);
290 let objects = [
291 ObjectRef::Production(production_id),
292 ObjectRef::Asset(AssetId::from_bytes([2; 16])),
293 ObjectRef::Representation(RepresentationId::from_bytes([3; 16])),
294 ObjectRef::Resource(ResourceId::from_bytes([4; 16])),
295 ObjectRef::Activity(ActivityId::from_bytes([5; 16])),
296 ObjectRef::Job(JobId::from_bytes([6; 16])),
297 ];
298 for object in objects {
299 let binding = HostObjectBinding::new(production_id, object).expect("valid binding");
300 let encoded = binding.to_string();
301 assert_eq!(HostObjectBinding::from_str(&encoded), Ok(binding));
302 }
303 }
304
305 #[test]
306 fn host_bindings_reject_noncanonical_or_ambiguous_text() {
307 let production_id = ProductionId::from_bytes([1; 16]);
308 let asset_id = AssetId::from_bytes([2; 16]);
309 let valid = format!("https://postproject.org/ref/v1/{production_id}/asset/{asset_id}");
310 assert!(HostObjectBinding::from_str(&valid.to_uppercase()).is_err());
311 assert!(HostObjectBinding::from_str(&valid.replace("/v1/", "/v2/")).is_err());
312 assert!(HostObjectBinding::from_str(&format!("{valid}/fallback")).is_err());
313 assert!(HostObjectBinding::from_str(&valid.replace("/asset/", "/locator/")).is_err());
314 assert!(HostObjectBinding::from_str("postproject:v1:old:asset:old").is_err());
315 assert!(
316 HostObjectBinding::new(
317 production_id,
318 ObjectRef::Production(ProductionId::from_bytes([9; 16]))
319 )
320 .is_err()
321 );
322 }
323}