Skip to main content

alien_core/
resource.rs

1use crate::error::Result;
2use serde::{Deserialize, Serialize};
3use std::any::Any;
4use std::borrow::Cow;
5use std::fmt::Debug;
6#[cfg(feature = "openapi")]
7use utoipa::openapi::schema::AdditionalProperties;
8#[cfg(feature = "openapi")]
9use utoipa::openapi::{ObjectBuilder, Ref, RefOr, Schema, Type};
10#[cfg(feature = "openapi")]
11use utoipa::{PartialSchema, ToSchema};
12
13/// Type alias for resource type identifiers
14#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct ResourceType(pub Cow<'static, str>);
17
18impl ResourceType {
19    /// Create a new ResourceType from a static string (const-friendly)
20    pub const fn from_static(s: &'static str) -> Self {
21        Self(Cow::Borrowed(s))
22    }
23}
24
25impl From<String> for ResourceType {
26    fn from(s: String) -> Self {
27        Self(Cow::Owned(s))
28    }
29}
30
31impl From<&str> for ResourceType {
32    fn from(s: &str) -> Self {
33        Self(Cow::Owned(s.to_string()))
34    }
35}
36
37impl std::fmt::Display for ResourceType {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(f, "{}", self.0)
40    }
41}
42
43impl From<ResourceType> for String {
44    fn from(val: ResourceType) -> Self {
45        val.0.into_owned()
46    }
47}
48
49impl AsRef<str> for ResourceType {
50    fn as_ref(&self) -> &str {
51        &self.0
52    }
53}
54
55#[cfg(feature = "openapi")]
56impl PartialSchema for ResourceType {
57    fn schema() -> RefOr<Schema> {
58        RefOr::T(Schema::Object(
59            ObjectBuilder::new()
60                .schema_type(Type::String)
61                .description(Some("Resource type identifier that determines the specific kind of resource. This field is used for polymorphic deserialization and resource-specific behavior."))
62                .examples([
63                    "worker",
64                    "storage",
65                    "queue",
66                    "redis",
67                    "postgres"
68                ])
69                .build()
70        ))
71    }
72}
73
74#[cfg(feature = "openapi")]
75impl ToSchema for ResourceType {
76    fn name() -> std::borrow::Cow<'static, str> {
77        std::borrow::Cow::Borrowed("ResourceType")
78    }
79}
80
81/// Trait that defines the interface for all resource types in the Alien system.
82/// This trait enables extensibility by allowing new resource types to be registered
83/// and managed alongside built-in resources.
84pub trait ResourceDefinition: Debug + Send + Sync + 'static {
85    /// Returns the resource type for this instance
86    fn get_resource_type(&self) -> ResourceType;
87
88    /// Returns the unique identifier for this specific resource instance
89    fn id(&self) -> &str;
90
91    /// Returns the list of other resources this resource depends on
92    fn get_dependencies(&self) -> Vec<ResourceRef>;
93
94    /// Returns the permission profile name for this resource, if it has one.
95    ///
96    /// Used by `ServiceAccountDependenciesMutation` to wire the corresponding
97    /// `{profile}-sa` service account as a declared dependency so the executor
98    /// enforces ordering and propagates SA changes automatically.
99    ///
100    /// Override in concrete types that carry a `permissions` field (Container, Worker).
101    fn get_permissions(&self) -> Option<&str> {
102        None
103    }
104
105    /// Validates if an update from the current configuration to a new configuration is allowed
106    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()>;
107
108    /// Whether the executor may delete this resource and create it again when its create
109    /// failed and its config changed since.
110    ///
111    /// That replace is unsafe when deleting the half-created resource can destroy something the
112    /// create already holds: user data (a create can adopt an existing bucket, table or
113    /// database with the same name, and a key decrypts data stored elsewhere) or live capacity
114    /// (replicas a timed-out create already started, instances that already launched). Such a
115    /// resource is created again in place instead. That create may adopt the existing resource
116    /// by name, or fail on the name until the conflict is resolved by hand, but it never deletes
117    /// what is there.
118    fn replace_after_failed_create_is_safe(&self) -> bool {
119        true
120    }
121
122    /// Provides access to the underlying concrete type for downcasting
123    fn as_any(&self) -> &dyn Any;
124
125    /// Provides mutable access to the underlying concrete type for downcasting
126    fn as_any_mut(&mut self) -> &mut dyn Any;
127
128    /// Creates a boxed clone of this resource definition
129    fn box_clone(&self) -> Box<dyn ResourceDefinition>;
130
131    /// For equality comparison between resource definitions
132    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool;
133
134    /// Serialize this resource to a JSON value (without the "type" tag - that's added by Resource)
135    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
136
137    /// Resolves the fields of this config that point at a deployer stack input.
138    ///
139    /// A config can name an input instead of holding a value (for example the artifact
140    /// registry's `replicationRegionsInput`). The value is known only when a deployment is
141    /// prepared, so an update that adds such a reference can compare equal to the recorded,
142    /// reference-free config once the answer is empty. Return `None` when there is nothing to
143    /// resolve, or when the resolution cannot be made equal to a config without references (the
144    /// input is undeclared or answered with a value). Return the config with the references
145    /// that resolve to "no value" removed when it can. The frozen-resource check uses only
146    /// that last case, for a recorded config that lacks the reference.
147    ///
148    /// The next input-backed field implements this method instead of special-casing the check.
149    fn with_empty_input_references_removed(
150        &self,
151        _inputs: &crate::InputAnswers<'_>,
152    ) -> Option<Box<dyn ResourceDefinition>> {
153        None
154    }
155
156    /// The `(config field, input id)` pairs this config reads from deployer inputs. Names the
157    /// field in the message when a setup update is needed because an input now has a value.
158    fn input_references(&self) -> Vec<(&'static str, String)> {
159        Vec::new()
160    }
161}
162
163/// Clone implementation for boxed ResourceDefinition trait objects
164impl Clone for Box<dyn ResourceDefinition> {
165    fn clone(&self) -> Self {
166        self.box_clone()
167    }
168}
169
170#[derive(Debug, Clone)]
171pub struct Resource {
172    inner: Box<dyn ResourceDefinition>,
173}
174
175impl Serialize for Resource {
176    fn serialize<S: serde::Serializer>(
177        &self,
178        serializer: S,
179    ) -> std::result::Result<S::Ok, S::Error> {
180        let mut v = self
181            .inner
182            .to_json_value()
183            .map_err(serde::ser::Error::custom)?;
184        v.as_object_mut()
185            .ok_or_else(|| serde::ser::Error::custom("resource must serialize as object"))?
186            .insert(
187                "type".into(),
188                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
189            );
190        v.serialize(serializer)
191    }
192}
193
194impl<'de> Deserialize<'de> for Resource {
195    fn deserialize<D: serde::Deserializer<'de>>(
196        deserializer: D,
197    ) -> std::result::Result<Self, D::Error> {
198        let mut value = serde_json::Value::deserialize(deserializer)?;
199        let type_tag = value
200            .get("type")
201            .and_then(|v| v.as_str())
202            .ok_or_else(|| serde::de::Error::missing_field("type"))?
203            .to_string();
204
205        // Remove the "type" tag before passing to concrete deserializer
206        // (structs with deny_unknown_fields would reject it)
207        if let Some(obj) = value.as_object_mut() {
208            obj.remove("type");
209        }
210
211        let inner: Box<dyn ResourceDefinition> = match type_tag.as_str() {
212            "vault" => Box::new(
213                serde_json::from_value::<crate::resources::Vault>(value)
214                    .map_err(serde::de::Error::custom)?,
215            ),
216            "worker" => Box::new(
217                serde_json::from_value::<crate::resources::Worker>(value)
218                    .map_err(serde::de::Error::custom)?,
219            ),
220            "daemon" => Box::new(
221                serde_json::from_value::<crate::resources::Daemon>(value)
222                    .map_err(serde::de::Error::custom)?,
223            ),
224            "container" => Box::new(
225                serde_json::from_value::<crate::resources::Container>(value)
226                    .map_err(serde::de::Error::custom)?,
227            ),
228            "compute-cluster" => Box::new(
229                serde_json::from_value::<crate::resources::ComputeCluster>(value)
230                    .map_err(serde::de::Error::custom)?,
231            ),
232            "kubernetes-cluster" => Box::new(
233                serde_json::from_value::<crate::resources::KubernetesCluster>(value)
234                    .map_err(serde::de::Error::custom)?,
235            ),
236            "storage" => Box::new(
237                serde_json::from_value::<crate::resources::Storage>(value)
238                    .map_err(serde::de::Error::custom)?,
239            ),
240            "key" => Box::new(
241                serde_json::from_value::<crate::resources::Key>(value)
242                    .map_err(serde::de::Error::custom)?,
243            ),
244            "queue" => Box::new(
245                serde_json::from_value::<crate::resources::Queue>(value)
246                    .map_err(serde::de::Error::custom)?,
247            ),
248            "sandbox" => Box::new(
249                serde_json::from_value::<crate::resources::Sandbox>(value)
250                    .map_err(serde::de::Error::custom)?,
251            ),
252            "email" => Box::new(
253                serde_json::from_value::<crate::resources::Email>(value)
254                    .map_err(serde::de::Error::custom)?,
255            ),
256            "kv" => Box::new(
257                serde_json::from_value::<crate::resources::Kv>(value)
258                    .map_err(serde::de::Error::custom)?,
259            ),
260            "postgres" => Box::new(
261                serde_json::from_value::<crate::resources::Postgres>(value)
262                    .map_err(serde::de::Error::custom)?,
263            ),
264            "redis" => Box::new(
265                serde_json::from_value::<crate::resources::Redis>(value)
266                    .map_err(serde::de::Error::custom)?,
267            ),
268            "ai" => Box::new(
269                serde_json::from_value::<crate::resources::Ai>(value)
270                    .map_err(serde::de::Error::custom)?,
271            ),
272            "network" => Box::new(
273                serde_json::from_value::<crate::resources::Network>(value)
274                    .map_err(serde::de::Error::custom)?,
275            ),
276            "build" => Box::new(
277                serde_json::from_value::<crate::resources::Build>(value)
278                    .map_err(serde::de::Error::custom)?,
279            ),
280            "service-account" => Box::new(
281                serde_json::from_value::<crate::resources::ServiceAccount>(value)
282                    .map_err(serde::de::Error::custom)?,
283            ),
284            "artifact-registry" => Box::new(
285                serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
286                    .map_err(serde::de::Error::custom)?,
287            ),
288            "service_activation" => Box::new(
289                serde_json::from_value::<crate::resources::ServiceActivation>(value)
290                    .map_err(serde::de::Error::custom)?,
291            ),
292            "remote-stack-management" => Box::new(
293                serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
294                    .map_err(serde::de::Error::custom)?,
295            ),
296            "resource-access" => Box::new(
297                serde_json::from_value::<crate::resources::RemoteBindings>(value)
298                    .map_err(serde::de::Error::custom)?,
299            ),
300            "verifier" => Box::new(
301                serde_json::from_value::<crate::resources::SigningVerifier>(value)
302                    .map_err(serde::de::Error::custom)?,
303            ),
304            "azure_resource_group" => Box::new(
305                serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
306                    .map_err(serde::de::Error::custom)?,
307            ),
308            "gcp_agent_platform_engine" => Box::new(
309                serde_json::from_value::<crate::resources::GcpAgentPlatformEngine>(value)
310                    .map_err(serde::de::Error::custom)?,
311            ),
312            "azure_storage_account" => Box::new(
313                serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
314                    .map_err(serde::de::Error::custom)?,
315            ),
316            "azure_container_apps_environment" => Box::new(
317                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
318                    .map_err(serde::de::Error::custom)?,
319            ),
320            "azure_service_bus_namespace" => Box::new(
321                serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
322                    .map_err(serde::de::Error::custom)?,
323            ),
324            "experimental/aws-opensearch" => Box::new(
325                serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
326                    .map_err(serde::de::Error::custom)?,
327            ),
328            other if crate::custom_resource::is_custom_resource_type(other) => Box::new(
329                crate::custom_resource::CustomResource::from_untagged(other, value)
330                    .map_err(serde::de::Error::custom)?,
331            ),
332            other => {
333                return Err(serde::de::Error::unknown_variant(
334                    other,
335                    &[
336                        "vault",
337                        "worker",
338                        "daemon",
339                        "container",
340                        "compute-cluster",
341                        "kubernetes-cluster",
342                        "storage",
343                        "key",
344                        "queue",
345                        "sandbox",
346                        "email",
347                        "kv",
348                        "postgres",
349                        "redis",
350                        "ai",
351                        "network",
352                        "build",
353                        "service-account",
354                        "artifact-registry",
355                        "service_activation",
356                        "remote-stack-management",
357                        "resource-access",
358                        "verifier",
359                        "azure_resource_group",
360                        "gcp_agent_platform_engine",
361                        "azure_storage_account",
362                        "azure_container_apps_environment",
363                        "azure_service_bus_namespace",
364                        "experimental/aws-opensearch",
365                    ],
366                ))
367            }
368        };
369
370        Ok(Resource { inner })
371    }
372}
373
374impl Resource {
375    /// Creates a new Resource from any type that implements ResourceDefinition
376    pub fn new<T: ResourceDefinition>(resource: T) -> Self {
377        Self {
378            inner: Box::new(resource),
379        }
380    }
381
382    /// Creates a new Resource from a boxed ResourceDefinition
383    pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
384        Self {
385            inner: boxed_resource,
386        }
387    }
388
389    /// Returns the resource type identifier
390    pub fn resource_type(&self) -> ResourceType {
391        self.inner.get_resource_type()
392    }
393
394    /// Returns the unique identifier for this resource instance
395    pub fn id(&self) -> &str {
396        self.inner.id()
397    }
398
399    /// Returns the list of other resources this resource depends on
400    pub fn get_dependencies(&self) -> Vec<ResourceRef> {
401        self.inner.get_dependencies()
402    }
403
404    /// Returns the permission profile name for this resource, if it has one.
405    pub fn get_permissions(&self) -> Option<&str> {
406        self.inner.get_permissions()
407    }
408
409    /// Validates if an update from the current configuration to a new configuration is allowed
410    pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
411        self.inner.validate_update(new_config.inner.as_ref())
412    }
413
414    /// Whether a failed create may be deleted and created again. See
415    /// [`ResourceDefinition::replace_after_failed_create_is_safe`].
416    pub fn replace_after_failed_create_is_safe(&self) -> bool {
417        self.inner.replace_after_failed_create_is_safe()
418    }
419
420    /// See [`ResourceDefinition::with_empty_input_references_removed`].
421    pub fn with_empty_input_references_removed(
422        &self,
423        inputs: &crate::InputAnswers<'_>,
424    ) -> Option<Resource> {
425        self.inner
426            .with_empty_input_references_removed(inputs)
427            .map(Resource::from_boxed)
428    }
429
430    /// See [`ResourceDefinition::input_references`].
431    pub fn input_references(&self) -> Vec<(&'static str, String)> {
432        self.inner.input_references()
433    }
434
435    /// Provides access to the underlying ResourceDefinition trait object
436    pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
437        self.inner.as_ref()
438    }
439
440    /// Generic downcasting for any type
441    pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
442        self.inner.as_any().downcast_ref::<T>()
443    }
444
445    /// Generic mutable downcasting for any type
446    pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
447        self.inner.as_any_mut().downcast_mut::<T>()
448    }
449}
450
451impl PartialEq for Resource {
452    fn eq(&self, other: &Self) -> bool {
453        self.inner.resource_eq(other.inner.as_ref())
454    }
455}
456
457impl Eq for Resource {}
458
459/// OpenAPI schema implementation for Resource.
460///
461/// The schema represents the flattened JSON structure of any resource type in the Alien system.
462/// All resources have a common base structure with `type` and `id` fields, plus type-specific
463/// additional properties that vary depending on the concrete resource implementation.
464///
465/// # Schema Structure
466/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
467/// - `id` (required): The unique identifier for this specific resource instance
468/// - Additional properties: Type-specific fields that vary by resource type (e.g., Worker has `code`, `memory_mb`, etc.)
469///
470/// # Example JSON
471/// ```json
472/// {
473///   "type": "worker",
474///   "id": "my-function",
475///   "code": { "type": "image", "image": "my-image:latest" },
476///   "memoryMb": 512,
477///   "timeoutSeconds": 30
478/// }
479/// ```
480#[cfg(feature = "openapi")]
481impl PartialSchema for Resource {
482    fn schema() -> RefOr<Schema> {
483        RefOr::T(Schema::Object(
484            ObjectBuilder::new()
485                .schema_type(Type::Object)
486                .property("type", Ref::from_schema_name("ResourceType"))
487                .property("id",
488                    ObjectBuilder::new()
489                        .schema_type(Type::String)
490                        .description(Some("The unique identifier for this specific resource instance. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]). Maximum 64 characters."))
491                        .build()
492                )
493                .required("type")
494                .required("id")
495                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
496                .description(Some("Resource that can hold any resource type in the Alien system. All resources share common 'type' and 'id' fields with additional type-specific properties."))
497                .build()
498        ))
499    }
500}
501
502#[cfg(feature = "openapi")]
503impl ToSchema for Resource {
504    fn name() -> std::borrow::Cow<'static, str> {
505        std::borrow::Cow::Borrowed("BaseResource")
506    }
507}
508
509/// Reference to a resource by its stable id and resource type.
510#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
511#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
512#[serde(rename_all = "camelCase")]
513pub struct ResourceRef {
514    #[serde(rename = "type")]
515    pub resource_type: ResourceType,
516    pub id: String,
517}
518
519impl ResourceRef {
520    /// Creates a new ResourceRef
521    pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
522        Self {
523            resource_type,
524            id: id.into(),
525        }
526    }
527
528    /// Returns the resource type
529    pub fn resource_type(&self) -> &ResourceType {
530        &self.resource_type
531    }
532
533    /// Returns the resource id
534    pub fn id(&self) -> &str {
535        &self.id
536    }
537}
538
539impl<T: ResourceDefinition> From<&T> for ResourceRef {
540    fn from(resource: &T) -> Self {
541        Self::new(resource.get_resource_type(), resource.id())
542    }
543}
544
545impl From<&Resource> for ResourceRef {
546    fn from(resource: &Resource) -> Self {
547        Self::new(resource.resource_type(), resource.id())
548    }
549}
550
551/// Trait that defines the interface for all resource output types in the Alien system.
552/// This trait enables extensibility by allowing new resource output types to be registered
553/// and managed alongside built-in resource outputs.
554/// Resource observations may gain fields as providers and servers are upgraded.
555/// Implementations should accept unknown output fields so older readers remain compatible;
556/// user-authored resource configuration is validated separately.
557pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
558    /// Whether dependents may reconcile. Temporary unavailability preserves their
559    /// identities and controller progress until the dependency recovers.
560    fn is_available(&self) -> bool {
561        true
562    }
563
564    /// Returns the resource type for this instance
565    fn get_resource_type(&self) -> ResourceType;
566
567    /// Provides access to the underlying concrete type for downcasting
568    fn as_any(&self) -> &dyn Any;
569
570    /// Creates a boxed clone of this resource outputs
571    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
572
573    /// For equality comparison between resource outputs
574    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
575
576    /// Serialize this resource outputs to a JSON value (without the "type" tag - that's added by ResourceOutputs)
577    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
578}
579
580/// Clone implementation for boxed ResourceOutputsDefinition trait objects
581impl Clone for Box<dyn ResourceOutputsDefinition> {
582    fn clone(&self) -> Self {
583        self.box_clone()
584    }
585}
586
587/// New Resource outputs wrapper that can hold any ResourceOutputsDefinition.
588/// This replaces the old ResourceOutputs enum to enable runtime extensibility.
589#[derive(Debug, Clone)]
590pub struct ResourceOutputs {
591    inner: Box<dyn ResourceOutputsDefinition>,
592}
593
594impl Serialize for ResourceOutputs {
595    fn serialize<S: serde::Serializer>(
596        &self,
597        serializer: S,
598    ) -> std::result::Result<S::Ok, S::Error> {
599        let mut v = self
600            .inner
601            .to_json_value()
602            .map_err(serde::ser::Error::custom)?;
603        v.as_object_mut()
604            .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
605            .insert(
606                "type".into(),
607                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
608            );
609        v.serialize(serializer)
610    }
611}
612
613impl<'de> Deserialize<'de> for ResourceOutputs {
614    fn deserialize<D: serde::Deserializer<'de>>(
615        deserializer: D,
616    ) -> std::result::Result<Self, D::Error> {
617        let mut value = serde_json::Value::deserialize(deserializer)?;
618        let type_tag = value
619            .get("type")
620            .and_then(|v| v.as_str())
621            .ok_or_else(|| serde::de::Error::missing_field("type"))?
622            .to_string();
623
624        // Remove the "type" tag before passing to concrete deserializer
625        // (structs with deny_unknown_fields would reject it)
626        if let Some(obj) = value.as_object_mut() {
627            obj.remove("type");
628        }
629
630        let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
631            "vault" => Box::new(
632                serde_json::from_value::<crate::resources::VaultOutputs>(value)
633                    .map_err(serde::de::Error::custom)?,
634            ),
635            "worker" => Box::new(
636                serde_json::from_value::<crate::resources::WorkerOutputs>(value)
637                    .map_err(serde::de::Error::custom)?,
638            ),
639            "daemon" => Box::new(
640                serde_json::from_value::<crate::resources::DaemonOutputs>(value)
641                    .map_err(serde::de::Error::custom)?,
642            ),
643            "container" => Box::new(
644                serde_json::from_value::<crate::resources::ContainerOutputs>(value)
645                    .map_err(serde::de::Error::custom)?,
646            ),
647            "compute-cluster" => Box::new(
648                serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
649                    .map_err(serde::de::Error::custom)?,
650            ),
651            "storage" => Box::new(
652                serde_json::from_value::<crate::resources::StorageOutputs>(value)
653                    .map_err(serde::de::Error::custom)?,
654            ),
655            "key" => Box::new(
656                serde_json::from_value::<crate::resources::KeyOutputs>(value)
657                    .map_err(serde::de::Error::custom)?,
658            ),
659            "queue" => Box::new(
660                serde_json::from_value::<crate::resources::QueueOutputs>(value)
661                    .map_err(serde::de::Error::custom)?,
662            ),
663            "sandbox" => Box::new(
664                serde_json::from_value::<crate::resources::SandboxOutputs>(value)
665                    .map_err(serde::de::Error::custom)?,
666            ),
667            "email" => Box::new(
668                serde_json::from_value::<crate::resources::EmailOutputs>(value)
669                    .map_err(serde::de::Error::custom)?,
670            ),
671            "kv" => Box::new(
672                serde_json::from_value::<crate::resources::KvOutputs>(value)
673                    .map_err(serde::de::Error::custom)?,
674            ),
675            "postgres" => Box::new(
676                serde_json::from_value::<crate::resources::PostgresOutputs>(value)
677                    .map_err(serde::de::Error::custom)?,
678            ),
679            "redis" => Box::new(
680                serde_json::from_value::<crate::resources::RedisOutputs>(value)
681                    .map_err(serde::de::Error::custom)?,
682            ),
683            "ai" => Box::new(
684                serde_json::from_value::<crate::resources::AiOutputs>(value)
685                    .map_err(serde::de::Error::custom)?,
686            ),
687            "network" => Box::new(
688                serde_json::from_value::<crate::resources::NetworkOutputs>(value)
689                    .map_err(serde::de::Error::custom)?,
690            ),
691            "build" => Box::new(
692                serde_json::from_value::<crate::resources::BuildOutputs>(value)
693                    .map_err(serde::de::Error::custom)?,
694            ),
695            "service-account" => Box::new(
696                serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
697                    .map_err(serde::de::Error::custom)?,
698            ),
699            "artifact-registry" => Box::new(
700                serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
701                    .map_err(serde::de::Error::custom)?,
702            ),
703            "service_activation" => Box::new(
704                serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
705                    .map_err(serde::de::Error::custom)?,
706            ),
707            "remote-stack-management" => Box::new(
708                serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
709                    .map_err(serde::de::Error::custom)?,
710            ),
711            "resource-access" => Box::new(
712                serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
713                    .map_err(serde::de::Error::custom)?,
714            ),
715            "verifier" => Box::new(
716                serde_json::from_value::<crate::resources::SigningVerifierOutputs>(value)
717                    .map_err(serde::de::Error::custom)?,
718            ),
719            "kubernetes-cluster" => Box::new(
720                serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
721                    .map_err(serde::de::Error::custom)?,
722            ),
723            "azure_resource_group" => Box::new(
724                serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
725                    .map_err(serde::de::Error::custom)?,
726            ),
727            "azure_storage_account" => Box::new(
728                serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
729                    .map_err(serde::de::Error::custom)?,
730            ),
731            "azure_container_apps_environment" => Box::new(
732                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
733                    value,
734                )
735                .map_err(serde::de::Error::custom)?,
736            ),
737            "azure_service_bus_namespace" => Box::new(
738                serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
739                    .map_err(serde::de::Error::custom)?,
740            ),
741            "experimental/aws-opensearch" => Box::new(
742                serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
743                    .map_err(serde::de::Error::custom)?,
744            ),
745            other if crate::custom_resource::is_custom_resource_type(other) => Box::new(
746                crate::custom_resource::CustomResourceOutputs::from_untagged(other, value)
747                    .map_err(serde::de::Error::custom)?,
748            ),
749            other => {
750                return Err(serde::de::Error::unknown_variant(
751                    other,
752                    &[
753                        "vault",
754                        "worker",
755                        "daemon",
756                        "container",
757                        "compute-cluster",
758                        "storage",
759                        "key",
760                        "queue",
761                        "sandbox",
762                        "email",
763                        "kv",
764                        "postgres",
765                        "redis",
766                        "ai",
767                        "network",
768                        "build",
769                        "service-account",
770                        "artifact-registry",
771                        "service_activation",
772                        "remote-stack-management",
773                        "resource-access",
774                        "verifier",
775                        "kubernetes-cluster",
776                        "azure_resource_group",
777                        "azure_storage_account",
778                        "azure_container_apps_environment",
779                        "azure_service_bus_namespace",
780                        "experimental/aws-opensearch",
781                    ],
782                ))
783            }
784        };
785
786        Ok(ResourceOutputs { inner })
787    }
788}
789
790impl ResourceOutputs {
791    /// Creates a new ResourceOutputs from any type that implements ResourceOutputsDefinition
792    pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
793        Self {
794            inner: Box::new(outputs),
795        }
796    }
797
798    /// Provides access to the underlying ResourceOutputsDefinition trait object
799    pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
800        self.inner.as_ref()
801    }
802
803    /// Generic downcasting for any type
804    pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
805        self.inner.as_any().downcast_ref::<T>()
806    }
807}
808
809impl PartialEq for ResourceOutputs {
810    fn eq(&self, other: &Self) -> bool {
811        self.inner.outputs_eq(other.inner.as_ref())
812    }
813}
814
815impl Eq for ResourceOutputs {}
816
817/// OpenAPI schema implementation for ResourceOutputs.
818///
819/// The schema represents the flattened JSON structure of any resource outputs in the Alien system.
820/// All resource outputs have a common base structure with a `type` field, plus type-specific
821/// additional properties that vary depending on the concrete resource implementation.
822///
823/// # Schema Structure
824/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
825/// - Additional properties: Type-specific output fields that vary by resource type
826///
827/// # Example JSON
828/// ```json
829/// {
830///   "type": "worker",
831///   "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
832///   "functionUrl": "https://abc123.lambda-url.us-east-1.on.aws/"
833/// }
834/// ```
835#[cfg(feature = "openapi")]
836impl PartialSchema for ResourceOutputs {
837    fn schema() -> RefOr<Schema> {
838        RefOr::T(Schema::Object(
839            ObjectBuilder::new()
840                .schema_type(Type::Object)
841                .property("type", Ref::from_schema_name("ResourceType"))
842                .required("type")
843                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
844                .description(Some("Resource outputs that can hold output data for any resource type in the Alien system. All resource outputs share a common 'type' field with additional type-specific output properties."))
845                .build()
846        ))
847    }
848}
849
850#[cfg(feature = "openapi")]
851impl ToSchema for ResourceOutputs {
852    fn name() -> std::borrow::Cow<'static, str> {
853        std::borrow::Cow::Borrowed("BaseResourceOutputs")
854    }
855}
856
857/// Represents the high-level status of a resource during its lifecycle.
858#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
859#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
860#[serde(rename_all = "kebab-case")]
861pub enum ResourceStatus {
862    Pending,      // Initial state before any action starts
863    Provisioning, // Resource is being created or updated
864    ProvisionFailed,
865    Running, // Resource is active and configured as desired
866    Updating,
867    UpdateFailed,
868    Deleting, // Resource is being removed
869    DeleteFailed,
870    TeardownRequired, // Runtime-owned parts were removed; setup-owned parts remain
871    Deleted,          // Resource has been successfully removed (terminal state)
872    RefreshFailed,    // Resource heartbeat/health check failed
873}
874
875impl ResourceStatus {
876    pub fn is_terminal(&self) -> bool {
877        match self {
878            ResourceStatus::TeardownRequired => true,
879            ResourceStatus::Deleted => true,
880            ResourceStatus::ProvisionFailed => true,
881            ResourceStatus::UpdateFailed => true,
882            ResourceStatus::DeleteFailed => true,
883            ResourceStatus::RefreshFailed => true,
884            _ => false, // Pending, Provisioning, Updating, Deleting are not terminal
885        }
886    }
887}
888
889/// Describes the lifecycle of a resource within a stack, determining how it's managed and deployed.
890#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
891#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
892#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
893#[serde(rename_all = "kebab-case")]
894pub enum ResourceLifecycle {
895    /// Frozen resources are owned by setup. Setup creates, updates, and
896    /// deletes them. Alien may heartbeat them and may run explicit management
897    /// operations when setup granted management permissions.
898    Frozen,
899
900    /// Live resources are owned by Alien. Alien creates, updates, deletes, and
901    /// replaces them after setup, so Live resources require provision
902    /// permissions.
903    Live,
904}