Skip to main content

alien_core/
custom_resource.rs

1//! Resources of a type an extension defines, kept as JSON.
2//!
3//! Alien deserializes `Resource`, `ResourceOutputs` and `ResourceHeartbeatData` by their type
4//! tag. A tag of the form `<extension>/<type>` that Alien does not define loads as one of the
5//! types here, so a stack, its state and its heartbeats can carry an extension's resource and
6//! serialize it back unchanged.
7
8use crate::error::ErrorData;
9use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
10use alien_error::AlienError;
11use serde_json::{Map, Value};
12use std::any::Any;
13
14/// Type prefixes no extension may use: `alien/` is Alien's own namespace, and `experimental/`
15/// holds built-in types that are not stable yet, such as `experimental/aws-opensearch`.
16pub const RESERVED_TYPE_PREFIXES: &[&str] = &["alien", "experimental"];
17
18/// Whether a type tag Alien does not define names an extension's type: `<extension>/<type>`,
19/// both parts non-empty, under a prefix that is not reserved. Any other unknown tag stays an
20/// error, so a typo in a built-in type name is refused instead of loading as custom.
21pub(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/// Configuration of a resource whose type an extension defines.
33///
34/// `config` holds every field but `type`, including `id`, so the resource serializes back
35/// exactly as it was read.
36#[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    /// Builds one from the JSON object `Resource` read, with its `type` tag removed.
45    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    /// The resource's fields, without `type`.
64    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    /// Alien cannot read references out of a config it does not know. A custom resource's
79    /// dependencies travel in `ResourceEntry.dependencies` instead.
80    fn get_dependencies(&self) -> Vec<ResourceRef> {
81        Vec::new()
82    }
83
84    /// The type and id can't change, as for Alien's own types; which other fields may is the
85    /// controller's to say when it starts the update.
86    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    /// Alien cannot tell whether a custom resource holds data, so it never deletes a
104    /// half-created one to create it again.
105    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/// Outputs of a resource whose type an extension defines.
131#[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    /// Builds one from the JSON object `ResourceOutputs` read, with its `type` tag removed.
146    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    /// The output fields, without `type`.
159    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    /// A custom resource keeps its type and id across an update; other fields are the
193    /// controller's to judge.
194    #[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    /// A stack with a worker that depends on an extension's DNS zone, as alien.ts writes it.
216    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    /// The tags serde lists in its `unknown variant` refusal: every tag the type defines.
256    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    // The heartbeat deserializer applies the custom rule before the built-in tags, and platform
270    // tells a custom heartbeat apart by its slash; both hold only while no built-in tag is custom.
271    #[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    /// A release records no minimum Alien version for its extensions: a binary that has none
364    /// of the stack's extensions loaded still reads and writes back a state with their
365    /// resources unchanged, since a custom resource's config, controller state and outputs are
366    /// kept as JSON.
367    #[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}