1use crate::error::ErrorData;
9use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
10use alien_error::AlienError;
11use serde_json::{Map, Value};
12use std::any::Any;
13
14pub const RESERVED_TYPE_PREFIXES: &[&str] = &["alien", "experimental"];
17
18pub(crate) fn is_custom_resource_type(tag: &str) -> bool {
22 match tag.split_once('/') {
23 Some((extension, name)) => {
24 !extension.is_empty()
25 && !name.is_empty()
26 && !RESERVED_TYPE_PREFIXES.contains(&extension)
27 }
28 None => false,
29 }
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct CustomResource {
38 resource_type: ResourceType,
39 id: String,
40 config: Map<String, Value>,
41}
42
43impl CustomResource {
44 pub fn from_untagged(resource_type: &str, value: Value) -> Result<Self, String> {
46 let Value::Object(config) = value else {
47 return Err(format!(
48 "resource of type '{resource_type}' must be a JSON object"
49 ));
50 };
51 let id = config
52 .get("id")
53 .and_then(Value::as_str)
54 .ok_or_else(|| format!("resource of type '{resource_type}' has no string 'id'"))?
55 .to_string();
56 Ok(Self {
57 resource_type: ResourceType::from(resource_type),
58 id,
59 config,
60 })
61 }
62
63 pub fn config(&self) -> &Map<String, Value> {
65 &self.config
66 }
67}
68
69impl ResourceDefinition for CustomResource {
70 fn get_resource_type(&self) -> ResourceType {
71 self.resource_type.clone()
72 }
73
74 fn id(&self) -> &str {
75 &self.id
76 }
77
78 fn get_dependencies(&self) -> Vec<ResourceRef> {
81 Vec::new()
82 }
83
84 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> crate::error::Result<()> {
87 if new_config.get_resource_type() != self.resource_type {
88 return Err(AlienError::new(ErrorData::UnexpectedResourceType {
89 resource_id: self.id.clone(),
90 expected: self.resource_type.clone(),
91 actual: new_config.get_resource_type(),
92 }));
93 }
94 if new_config.id() != self.id {
95 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
96 resource_id: self.id.clone(),
97 reason: "the 'id' field is immutable".to_string(),
98 }));
99 }
100 Ok(())
101 }
102
103 fn replace_after_failed_create_is_safe(&self) -> bool {
106 false
107 }
108
109 fn as_any(&self) -> &dyn Any {
110 self
111 }
112
113 fn as_any_mut(&mut self) -> &mut dyn Any {
114 self
115 }
116
117 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
118 Box::new(self.clone())
119 }
120
121 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
122 other.as_any().downcast_ref::<CustomResource>() == Some(self)
123 }
124
125 fn to_json_value(&self) -> serde_json::Result<Value> {
126 Ok(Value::Object(self.config.clone()))
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq)]
132pub struct CustomResourceOutputs {
133 resource_type: ResourceType,
134 fields: Map<String, Value>,
135}
136
137impl CustomResourceOutputs {
138 pub(crate) fn new(resource_type: ResourceType, fields: Map<String, Value>) -> Self {
139 Self {
140 resource_type,
141 fields,
142 }
143 }
144
145 pub fn from_untagged(resource_type: &str, value: Value) -> Result<Self, String> {
147 let Value::Object(fields) = value else {
148 return Err(format!(
149 "outputs of type '{resource_type}' must be a JSON object"
150 ));
151 };
152 Ok(Self {
153 resource_type: ResourceType::from(resource_type),
154 fields,
155 })
156 }
157
158 pub fn fields(&self) -> &Map<String, Value> {
160 &self.fields
161 }
162}
163
164impl ResourceOutputsDefinition for CustomResourceOutputs {
165 fn get_resource_type(&self) -> ResourceType {
166 self.resource_type.clone()
167 }
168
169 fn as_any(&self) -> &dyn Any {
170 self
171 }
172
173 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
174 Box::new(self.clone())
175 }
176
177 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
178 other.as_any().downcast_ref::<CustomResourceOutputs>() == Some(self)
179 }
180
181 fn to_json_value(&self) -> serde_json::Result<Value> {
182 Ok(Value::Object(self.fields.clone()))
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use crate::{Resource, ResourceOutputs, Stack, Worker, WorkerCode};
190 use serde_json::json;
191
192 #[test]
195 fn an_update_keeps_the_type_and_id() {
196 let zone = |resource_type: &str, id: &str, domain: &str| {
197 CustomResource::from_untagged(
198 resource_type,
199 serde_json::json!({ "id": id, "domain": domain }),
200 )
201 .unwrap()
202 };
203 let current = zone("acme/dns-zone", "zone", "a.example");
204 current
205 .validate_update(&zone("acme/dns-zone", "zone", "b.example"))
206 .unwrap();
207 assert!(current
208 .validate_update(&zone("acme/dns-zone", "other", "a.example"))
209 .is_err());
210 assert!(current
211 .validate_update(&zone("acme/record", "zone", "a.example"))
212 .is_err());
213 }
214
215 fn stack_json() -> Value {
217 let api = Worker::new("api".to_string())
218 .code(WorkerCode::Image {
219 image: "api:1".to_string(),
220 })
221 .permissions("api".to_string())
222 .build();
223 json!({
224 "id": "acme",
225 "resources": {
226 "zone": {
227 "config": { "type": "acme/dns-zone", "id": "zone", "domain": "internal.acme.dev" },
228 "lifecycle": "live",
229 "dependencies": []
230 },
231 "api": {
232 "config": serde_json::to_value(Resource::new(api)).unwrap(),
233 "lifecycle": "live",
234 "dependencies": [{ "type": "acme/dns-zone", "id": "zone" }]
235 }
236 }
237 })
238 }
239
240 #[test]
241 fn only_an_unreserved_extension_prefix_names_a_custom_type() {
242 for (tag, custom) in [
243 ("acme/dns-zone", true),
244 ("worker", false),
245 ("not-a-resource", false),
246 ("alien/dns-zone", false),
247 ("experimental/dns-zone", false),
248 ("/dns-zone", false),
249 ("acme/", false),
250 ] {
251 assert_eq!(is_custom_resource_type(tag), custom, "{tag}");
252 }
253 }
254
255 fn listed_tags(refusal: impl std::fmt::Display) -> Vec<String> {
257 let message = refusal.to_string();
258 let tags: Vec<String> = message
259 .split('`')
260 .skip(1)
261 .step_by(2)
262 .filter(|tag| *tag != "not-a-resource")
263 .map(str::to_string)
264 .collect();
265 assert!(tags.len() > 10, "could not read the tags out of: {message}");
266 tags
267 }
268
269 #[test]
272 fn no_built_in_tag_names_a_custom_type() {
273 let resources = serde_json::from_value::<Resource>(json!({ "type": "not-a-resource" }))
274 .expect_err("an unknown tag is refused");
275 let outputs =
276 serde_json::from_value::<ResourceOutputs>(json!({ "type": "not-a-resource" }))
277 .expect_err("an unknown tag is refused");
278 let heartbeats = serde_json::from_value::<crate::ResourceHeartbeatData>(json!({
279 "resourceType": "not-a-resource",
280 "data": {}
281 }))
282 .expect_err("an unknown tag is refused");
283
284 for tag in listed_tags(resources)
285 .into_iter()
286 .chain(listed_tags(outputs))
287 .chain(listed_tags(heartbeats))
288 {
289 assert!(!is_custom_resource_type(&tag), "{tag}");
290 }
291 }
292
293 #[test]
294 fn custom_resource_round_trips_through_stack_json() {
295 let stack: Stack = serde_json::from_value(stack_json()).expect("the stack loads");
296 let zone = &stack.resources["zone"].config;
297 let custom = zone
298 .downcast_ref::<CustomResource>()
299 .expect("the extension's type is a CustomResource");
300 assert_eq!(custom.id(), "zone");
301 assert_eq!(zone.resource_type().as_ref(), "acme/dns-zone");
302 assert_eq!(custom.config()["domain"], "internal.acme.dev");
303
304 let again = serde_json::to_value(&stack).expect("the stack serializes");
305 assert_eq!(
306 again["resources"]["zone"]["config"],
307 stack_json()["resources"]["zone"]["config"]
308 );
309 let reloaded: Stack = serde_json::from_value(again).expect("it loads again");
310 assert_eq!(reloaded, stack);
311 }
312
313 #[test]
314 fn built_in_types_still_load_as_themselves() {
315 let stack: Stack = serde_json::from_value(stack_json()).expect("the stack loads");
316 let api = &stack.resources["api"].config;
317 assert!(api.downcast_ref::<Worker>().is_some());
318 assert!(api.downcast_ref::<CustomResource>().is_none());
319 }
320
321 #[test]
322 fn custom_resource_without_id_is_refused() {
323 let err =
324 serde_json::from_value::<Resource>(json!({ "type": "acme/dns-zone", "domain": "x" }))
325 .expect_err("no id");
326 assert!(err.to_string().contains("no string 'id'"), "{err}");
327 }
328
329 #[test]
330 fn custom_resource_is_never_replaced_after_a_failed_create() {
331 let resource: Resource =
332 serde_json::from_value(json!({ "type": "acme/dns-zone", "id": "zone" })).unwrap();
333 assert!(!resource.replace_after_failed_create_is_safe());
334 }
335
336 #[test]
337 fn custom_outputs_round_trip() {
338 let tagged = json!({ "type": "acme/dns-zone", "zoneId": "Z123" });
339 let outputs: ResourceOutputs =
340 serde_json::from_value(tagged.clone()).expect("outputs load");
341 let custom = outputs
342 .downcast_ref::<CustomResourceOutputs>()
343 .expect("CustomResourceOutputs");
344 assert_eq!(custom.fields()["zoneId"], "Z123");
345 assert_eq!(serde_json::to_value(&outputs).unwrap(), tagged);
346 }
347
348 #[test]
349 fn unknown_type_outside_an_extension_namespace_is_refused() {
350 for tag in ["not-a-resource", "alien/dns-zone", "experimental/dns-zone"] {
351 let resource = serde_json::from_value::<Resource>(json!({ "type": tag, "id": "x" }))
352 .expect_err(tag);
353 assert!(
354 resource.to_string().contains("unknown variant"),
355 "{resource}"
356 );
357 let outputs =
358 serde_json::from_value::<ResourceOutputs>(json!({ "type": tag })).expect_err(tag);
359 assert!(outputs.to_string().contains("unknown variant"), "{outputs}");
360 }
361 }
362
363 #[test]
368 fn a_stack_state_with_a_custom_resource_round_trips_without_its_extension() {
369 let state = json!({
370 "platform": "aws",
371 "resourcePrefix": "k1234567",
372 "resources": {
373 "zone": {
374 "type": "acme/dns-zone",
375 "_internal": {
376 "type": "acme/dns-zone",
377 "_controllerStateVersion": 1,
378 "state": "Ready",
379 "zoneId": "Z123",
380 "nameServers": ["ns-1.example.net"]
381 },
382 "status": "running",
383 "outputs": { "type": "acme/dns-zone", "zoneId": "Z123" },
384 "config": { "type": "acme/dns-zone", "id": "zone", "domain": "internal.acme.dev" },
385 "previousConfig": { "type": "acme/dns-zone", "id": "zone", "domain": "old.acme.dev" },
386 "lifecycle": "live",
387 "lastFailedState": { "type": "acme/dns-zone", "state": "Creating" }
388 }
389 }
390 });
391 let loaded: crate::StackState =
392 serde_json::from_value(state.clone()).expect("the state loads with no extension");
393 assert_eq!(serde_json::to_value(&loaded).unwrap(), state);
394 }
395
396 #[test]
397 fn built_in_type_with_a_malformed_body_is_refused() {
398 serde_json::from_value::<Resource>(json!({ "type": "worker", "id": "api" }))
399 .expect_err("a worker needs its code");
400 serde_json::from_value::<ResourceOutputs>(json!({ "type": "storage" }))
401 .expect_err("storage outputs need their fields");
402 }
403}