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
138/// Clone implementation for boxed ResourceDefinition trait objects
139impl Clone for Box<dyn ResourceDefinition> {
140    fn clone(&self) -> Self {
141        self.box_clone()
142    }
143}
144
145#[derive(Debug, Clone)]
146pub struct Resource {
147    inner: Box<dyn ResourceDefinition>,
148}
149
150impl Serialize for Resource {
151    fn serialize<S: serde::Serializer>(
152        &self,
153        serializer: S,
154    ) -> std::result::Result<S::Ok, S::Error> {
155        let mut v = self
156            .inner
157            .to_json_value()
158            .map_err(serde::ser::Error::custom)?;
159        v.as_object_mut()
160            .ok_or_else(|| serde::ser::Error::custom("resource must serialize as object"))?
161            .insert(
162                "type".into(),
163                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
164            );
165        v.serialize(serializer)
166    }
167}
168
169impl<'de> Deserialize<'de> for Resource {
170    fn deserialize<D: serde::Deserializer<'de>>(
171        deserializer: D,
172    ) -> std::result::Result<Self, D::Error> {
173        let mut value = serde_json::Value::deserialize(deserializer)?;
174        let type_tag = value
175            .get("type")
176            .and_then(|v| v.as_str())
177            .ok_or_else(|| serde::de::Error::missing_field("type"))?
178            .to_string();
179
180        // Remove the "type" tag before passing to concrete deserializer
181        // (structs with deny_unknown_fields would reject it)
182        if let Some(obj) = value.as_object_mut() {
183            obj.remove("type");
184        }
185
186        let inner: Box<dyn ResourceDefinition> = match type_tag.as_str() {
187            "vault" => Box::new(
188                serde_json::from_value::<crate::resources::Vault>(value)
189                    .map_err(serde::de::Error::custom)?,
190            ),
191            "worker" => Box::new(
192                serde_json::from_value::<crate::resources::Worker>(value)
193                    .map_err(serde::de::Error::custom)?,
194            ),
195            "daemon" => Box::new(
196                serde_json::from_value::<crate::resources::Daemon>(value)
197                    .map_err(serde::de::Error::custom)?,
198            ),
199            "container" => Box::new(
200                serde_json::from_value::<crate::resources::Container>(value)
201                    .map_err(serde::de::Error::custom)?,
202            ),
203            "compute-cluster" => Box::new(
204                serde_json::from_value::<crate::resources::ComputeCluster>(value)
205                    .map_err(serde::de::Error::custom)?,
206            ),
207            "kubernetes-cluster" => Box::new(
208                serde_json::from_value::<crate::resources::KubernetesCluster>(value)
209                    .map_err(serde::de::Error::custom)?,
210            ),
211            "storage" => Box::new(
212                serde_json::from_value::<crate::resources::Storage>(value)
213                    .map_err(serde::de::Error::custom)?,
214            ),
215            "key" => Box::new(
216                serde_json::from_value::<crate::resources::Key>(value)
217                    .map_err(serde::de::Error::custom)?,
218            ),
219            "queue" => Box::new(
220                serde_json::from_value::<crate::resources::Queue>(value)
221                    .map_err(serde::de::Error::custom)?,
222            ),
223            "sandbox" => Box::new(
224                serde_json::from_value::<crate::resources::Sandbox>(value)
225                    .map_err(serde::de::Error::custom)?,
226            ),
227            "email" => Box::new(
228                serde_json::from_value::<crate::resources::Email>(value)
229                    .map_err(serde::de::Error::custom)?,
230            ),
231            "kv" => Box::new(
232                serde_json::from_value::<crate::resources::Kv>(value)
233                    .map_err(serde::de::Error::custom)?,
234            ),
235            "postgres" => Box::new(
236                serde_json::from_value::<crate::resources::Postgres>(value)
237                    .map_err(serde::de::Error::custom)?,
238            ),
239            "ai" => Box::new(
240                serde_json::from_value::<crate::resources::Ai>(value)
241                    .map_err(serde::de::Error::custom)?,
242            ),
243            "network" => Box::new(
244                serde_json::from_value::<crate::resources::Network>(value)
245                    .map_err(serde::de::Error::custom)?,
246            ),
247            "build" => Box::new(
248                serde_json::from_value::<crate::resources::Build>(value)
249                    .map_err(serde::de::Error::custom)?,
250            ),
251            "service-account" => Box::new(
252                serde_json::from_value::<crate::resources::ServiceAccount>(value)
253                    .map_err(serde::de::Error::custom)?,
254            ),
255            "artifact-registry" => Box::new(
256                serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
257                    .map_err(serde::de::Error::custom)?,
258            ),
259            "service_activation" => Box::new(
260                serde_json::from_value::<crate::resources::ServiceActivation>(value)
261                    .map_err(serde::de::Error::custom)?,
262            ),
263            "remote-stack-management" => Box::new(
264                serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
265                    .map_err(serde::de::Error::custom)?,
266            ),
267            "resource-access" => Box::new(
268                serde_json::from_value::<crate::resources::RemoteBindings>(value)
269                    .map_err(serde::de::Error::custom)?,
270            ),
271            "azure_resource_group" => Box::new(
272                serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
273                    .map_err(serde::de::Error::custom)?,
274            ),
275            "gcp_agent_platform_engine" => Box::new(
276                serde_json::from_value::<crate::resources::GcpAgentPlatformEngine>(value)
277                    .map_err(serde::de::Error::custom)?,
278            ),
279            "azure_storage_account" => Box::new(
280                serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
281                    .map_err(serde::de::Error::custom)?,
282            ),
283            "azure_container_apps_environment" => Box::new(
284                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
285                    .map_err(serde::de::Error::custom)?,
286            ),
287            "azure_service_bus_namespace" => Box::new(
288                serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
289                    .map_err(serde::de::Error::custom)?,
290            ),
291            "experimental/aws-opensearch" => Box::new(
292                serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
293                    .map_err(serde::de::Error::custom)?,
294            ),
295            other => {
296                return Err(serde::de::Error::unknown_variant(
297                    other,
298                    &[
299                        "vault",
300                        "worker",
301                        "daemon",
302                        "container",
303                        "compute-cluster",
304                        "kubernetes-cluster",
305                        "storage",
306                        "key",
307                        "queue",
308                        "sandbox",
309                        "email",
310                        "kv",
311                        "postgres",
312                        "ai",
313                        "network",
314                        "build",
315                        "service-account",
316                        "artifact-registry",
317                        "service_activation",
318                        "remote-stack-management",
319                        "resource-access",
320                        "azure_resource_group",
321                        "gcp_agent_platform_engine",
322                        "azure_storage_account",
323                        "azure_container_apps_environment",
324                        "azure_service_bus_namespace",
325                        "experimental/aws-opensearch",
326                    ],
327                ))
328            }
329        };
330
331        Ok(Resource { inner })
332    }
333}
334
335impl Resource {
336    /// Creates a new Resource from any type that implements ResourceDefinition
337    pub fn new<T: ResourceDefinition>(resource: T) -> Self {
338        Self {
339            inner: Box::new(resource),
340        }
341    }
342
343    /// Creates a new Resource from a boxed ResourceDefinition
344    pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
345        Self {
346            inner: boxed_resource,
347        }
348    }
349
350    /// Returns the resource type identifier
351    pub fn resource_type(&self) -> ResourceType {
352        self.inner.get_resource_type()
353    }
354
355    /// Returns the unique identifier for this resource instance
356    pub fn id(&self) -> &str {
357        self.inner.id()
358    }
359
360    /// Returns the list of other resources this resource depends on
361    pub fn get_dependencies(&self) -> Vec<ResourceRef> {
362        self.inner.get_dependencies()
363    }
364
365    /// Returns the permission profile name for this resource, if it has one.
366    pub fn get_permissions(&self) -> Option<&str> {
367        self.inner.get_permissions()
368    }
369
370    /// Validates if an update from the current configuration to a new configuration is allowed
371    pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
372        self.inner.validate_update(new_config.inner.as_ref())
373    }
374
375    /// Whether a failed create may be deleted and created again. See
376    /// [`ResourceDefinition::replace_after_failed_create_is_safe`].
377    pub fn replace_after_failed_create_is_safe(&self) -> bool {
378        self.inner.replace_after_failed_create_is_safe()
379    }
380
381    /// Provides access to the underlying ResourceDefinition trait object
382    pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
383        self.inner.as_ref()
384    }
385
386    /// Generic downcasting for any type
387    pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
388        self.inner.as_any().downcast_ref::<T>()
389    }
390
391    /// Generic mutable downcasting for any type
392    pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
393        self.inner.as_any_mut().downcast_mut::<T>()
394    }
395}
396
397impl PartialEq for Resource {
398    fn eq(&self, other: &Self) -> bool {
399        self.inner.resource_eq(other.inner.as_ref())
400    }
401}
402
403impl Eq for Resource {}
404
405/// OpenAPI schema implementation for Resource.
406///
407/// The schema represents the flattened JSON structure of any resource type in the Alien system.
408/// All resources have a common base structure with `type` and `id` fields, plus type-specific
409/// additional properties that vary depending on the concrete resource implementation.
410///
411/// # Schema Structure
412/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
413/// - `id` (required): The unique identifier for this specific resource instance
414/// - Additional properties: Type-specific fields that vary by resource type (e.g., Worker has `code`, `memory_mb`, etc.)
415///
416/// # Example JSON
417/// ```json
418/// {
419///   "type": "worker",
420///   "id": "my-function",
421///   "code": { "type": "image", "image": "my-image:latest" },
422///   "memoryMb": 512,
423///   "timeoutSeconds": 30
424/// }
425/// ```
426#[cfg(feature = "openapi")]
427impl PartialSchema for Resource {
428    fn schema() -> RefOr<Schema> {
429        RefOr::T(Schema::Object(
430            ObjectBuilder::new()
431                .schema_type(Type::Object)
432                .property("type", Ref::from_schema_name("ResourceType"))
433                .property("id",
434                    ObjectBuilder::new()
435                        .schema_type(Type::String)
436                        .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."))
437                        .build()
438                )
439                .required("type")
440                .required("id")
441                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
442                .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."))
443                .build()
444        ))
445    }
446}
447
448#[cfg(feature = "openapi")]
449impl ToSchema for Resource {
450    fn name() -> std::borrow::Cow<'static, str> {
451        std::borrow::Cow::Borrowed("BaseResource")
452    }
453}
454
455/// Reference to a resource by its stable id and resource type.
456#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
457#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
458#[serde(rename_all = "camelCase")]
459pub struct ResourceRef {
460    #[serde(rename = "type")]
461    pub resource_type: ResourceType,
462    pub id: String,
463}
464
465impl ResourceRef {
466    /// Creates a new ResourceRef
467    pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
468        Self {
469            resource_type,
470            id: id.into(),
471        }
472    }
473
474    /// Returns the resource type
475    pub fn resource_type(&self) -> &ResourceType {
476        &self.resource_type
477    }
478
479    /// Returns the resource id
480    pub fn id(&self) -> &str {
481        &self.id
482    }
483}
484
485impl<T: ResourceDefinition> From<&T> for ResourceRef {
486    fn from(resource: &T) -> Self {
487        Self::new(resource.get_resource_type(), resource.id())
488    }
489}
490
491impl From<&Resource> for ResourceRef {
492    fn from(resource: &Resource) -> Self {
493        Self::new(resource.resource_type(), resource.id())
494    }
495}
496
497/// Trait that defines the interface for all resource output types in the Alien system.
498/// This trait enables extensibility by allowing new resource output types to be registered
499/// and managed alongside built-in resource outputs.
500/// Resource observations may gain fields as providers and servers are upgraded.
501/// Implementations should accept unknown output fields so older readers remain compatible;
502/// user-authored resource configuration is validated separately.
503pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
504    /// Whether dependents may reconcile. Temporary unavailability preserves their
505    /// identities and controller progress until the dependency recovers.
506    fn is_available(&self) -> bool {
507        true
508    }
509
510    /// Returns the resource type for this instance
511    fn get_resource_type(&self) -> ResourceType;
512
513    /// Provides access to the underlying concrete type for downcasting
514    fn as_any(&self) -> &dyn Any;
515
516    /// Creates a boxed clone of this resource outputs
517    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
518
519    /// For equality comparison between resource outputs
520    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
521
522    /// Serialize this resource outputs to a JSON value (without the "type" tag - that's added by ResourceOutputs)
523    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
524}
525
526/// Clone implementation for boxed ResourceOutputsDefinition trait objects
527impl Clone for Box<dyn ResourceOutputsDefinition> {
528    fn clone(&self) -> Self {
529        self.box_clone()
530    }
531}
532
533/// New Resource outputs wrapper that can hold any ResourceOutputsDefinition.
534/// This replaces the old ResourceOutputs enum to enable runtime extensibility.
535#[derive(Debug, Clone)]
536pub struct ResourceOutputs {
537    inner: Box<dyn ResourceOutputsDefinition>,
538}
539
540impl Serialize for ResourceOutputs {
541    fn serialize<S: serde::Serializer>(
542        &self,
543        serializer: S,
544    ) -> std::result::Result<S::Ok, S::Error> {
545        let mut v = self
546            .inner
547            .to_json_value()
548            .map_err(serde::ser::Error::custom)?;
549        v.as_object_mut()
550            .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
551            .insert(
552                "type".into(),
553                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
554            );
555        v.serialize(serializer)
556    }
557}
558
559impl<'de> Deserialize<'de> for ResourceOutputs {
560    fn deserialize<D: serde::Deserializer<'de>>(
561        deserializer: D,
562    ) -> std::result::Result<Self, D::Error> {
563        let mut value = serde_json::Value::deserialize(deserializer)?;
564        let type_tag = value
565            .get("type")
566            .and_then(|v| v.as_str())
567            .ok_or_else(|| serde::de::Error::missing_field("type"))?
568            .to_string();
569
570        // Remove the "type" tag before passing to concrete deserializer
571        // (structs with deny_unknown_fields would reject it)
572        if let Some(obj) = value.as_object_mut() {
573            obj.remove("type");
574        }
575
576        let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
577            "vault" => Box::new(
578                serde_json::from_value::<crate::resources::VaultOutputs>(value)
579                    .map_err(serde::de::Error::custom)?,
580            ),
581            "worker" => Box::new(
582                serde_json::from_value::<crate::resources::WorkerOutputs>(value)
583                    .map_err(serde::de::Error::custom)?,
584            ),
585            "daemon" => Box::new(
586                serde_json::from_value::<crate::resources::DaemonOutputs>(value)
587                    .map_err(serde::de::Error::custom)?,
588            ),
589            "container" => Box::new(
590                serde_json::from_value::<crate::resources::ContainerOutputs>(value)
591                    .map_err(serde::de::Error::custom)?,
592            ),
593            "compute-cluster" => Box::new(
594                serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
595                    .map_err(serde::de::Error::custom)?,
596            ),
597            "storage" => Box::new(
598                serde_json::from_value::<crate::resources::StorageOutputs>(value)
599                    .map_err(serde::de::Error::custom)?,
600            ),
601            "key" => Box::new(
602                serde_json::from_value::<crate::resources::KeyOutputs>(value)
603                    .map_err(serde::de::Error::custom)?,
604            ),
605            "queue" => Box::new(
606                serde_json::from_value::<crate::resources::QueueOutputs>(value)
607                    .map_err(serde::de::Error::custom)?,
608            ),
609            "sandbox" => Box::new(
610                serde_json::from_value::<crate::resources::SandboxOutputs>(value)
611                    .map_err(serde::de::Error::custom)?,
612            ),
613            "email" => Box::new(
614                serde_json::from_value::<crate::resources::EmailOutputs>(value)
615                    .map_err(serde::de::Error::custom)?,
616            ),
617            "kv" => Box::new(
618                serde_json::from_value::<crate::resources::KvOutputs>(value)
619                    .map_err(serde::de::Error::custom)?,
620            ),
621            "postgres" => Box::new(
622                serde_json::from_value::<crate::resources::PostgresOutputs>(value)
623                    .map_err(serde::de::Error::custom)?,
624            ),
625            "ai" => Box::new(
626                serde_json::from_value::<crate::resources::AiOutputs>(value)
627                    .map_err(serde::de::Error::custom)?,
628            ),
629            "network" => Box::new(
630                serde_json::from_value::<crate::resources::NetworkOutputs>(value)
631                    .map_err(serde::de::Error::custom)?,
632            ),
633            "build" => Box::new(
634                serde_json::from_value::<crate::resources::BuildOutputs>(value)
635                    .map_err(serde::de::Error::custom)?,
636            ),
637            "service-account" => Box::new(
638                serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
639                    .map_err(serde::de::Error::custom)?,
640            ),
641            "artifact-registry" => Box::new(
642                serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
643                    .map_err(serde::de::Error::custom)?,
644            ),
645            "service_activation" => Box::new(
646                serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
647                    .map_err(serde::de::Error::custom)?,
648            ),
649            "remote-stack-management" => Box::new(
650                serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
651                    .map_err(serde::de::Error::custom)?,
652            ),
653            "resource-access" => Box::new(
654                serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
655                    .map_err(serde::de::Error::custom)?,
656            ),
657            "kubernetes-cluster" => Box::new(
658                serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
659                    .map_err(serde::de::Error::custom)?,
660            ),
661            "azure_resource_group" => Box::new(
662                serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
663                    .map_err(serde::de::Error::custom)?,
664            ),
665            "azure_storage_account" => Box::new(
666                serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
667                    .map_err(serde::de::Error::custom)?,
668            ),
669            "azure_container_apps_environment" => Box::new(
670                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
671                    value,
672                )
673                .map_err(serde::de::Error::custom)?,
674            ),
675            "azure_service_bus_namespace" => Box::new(
676                serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
677                    .map_err(serde::de::Error::custom)?,
678            ),
679            "experimental/aws-opensearch" => Box::new(
680                serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
681                    .map_err(serde::de::Error::custom)?,
682            ),
683            other => {
684                return Err(serde::de::Error::unknown_variant(
685                    other,
686                    &[
687                        "vault",
688                        "worker",
689                        "daemon",
690                        "container",
691                        "compute-cluster",
692                        "storage",
693                        "key",
694                        "queue",
695                        "sandbox",
696                        "email",
697                        "kv",
698                        "postgres",
699                        "ai",
700                        "network",
701                        "build",
702                        "service-account",
703                        "artifact-registry",
704                        "service_activation",
705                        "remote-stack-management",
706                        "resource-access",
707                        "kubernetes-cluster",
708                        "azure_resource_group",
709                        "azure_storage_account",
710                        "azure_container_apps_environment",
711                        "azure_service_bus_namespace",
712                        "experimental/aws-opensearch",
713                    ],
714                ))
715            }
716        };
717
718        Ok(ResourceOutputs { inner })
719    }
720}
721
722impl ResourceOutputs {
723    /// Creates a new ResourceOutputs from any type that implements ResourceOutputsDefinition
724    pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
725        Self {
726            inner: Box::new(outputs),
727        }
728    }
729
730    /// Provides access to the underlying ResourceOutputsDefinition trait object
731    pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
732        self.inner.as_ref()
733    }
734
735    /// Generic downcasting for any type
736    pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
737        self.inner.as_any().downcast_ref::<T>()
738    }
739}
740
741impl PartialEq for ResourceOutputs {
742    fn eq(&self, other: &Self) -> bool {
743        self.inner.outputs_eq(other.inner.as_ref())
744    }
745}
746
747impl Eq for ResourceOutputs {}
748
749/// OpenAPI schema implementation for ResourceOutputs.
750///
751/// The schema represents the flattened JSON structure of any resource outputs in the Alien system.
752/// All resource outputs have a common base structure with a `type` field, plus type-specific
753/// additional properties that vary depending on the concrete resource implementation.
754///
755/// # Schema Structure
756/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
757/// - Additional properties: Type-specific output fields that vary by resource type
758///
759/// # Example JSON
760/// ```json
761/// {
762///   "type": "worker",
763///   "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
764///   "functionUrl": "https://abc123.lambda-url.us-east-1.on.aws/"
765/// }
766/// ```
767#[cfg(feature = "openapi")]
768impl PartialSchema for ResourceOutputs {
769    fn schema() -> RefOr<Schema> {
770        RefOr::T(Schema::Object(
771            ObjectBuilder::new()
772                .schema_type(Type::Object)
773                .property("type", Ref::from_schema_name("ResourceType"))
774                .required("type")
775                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
776                .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."))
777                .build()
778        ))
779    }
780}
781
782#[cfg(feature = "openapi")]
783impl ToSchema for ResourceOutputs {
784    fn name() -> std::borrow::Cow<'static, str> {
785        std::borrow::Cow::Borrowed("BaseResourceOutputs")
786    }
787}
788
789/// Represents the high-level status of a resource during its lifecycle.
790#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
791#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
792#[serde(rename_all = "kebab-case")]
793pub enum ResourceStatus {
794    Pending,      // Initial state before any action starts
795    Provisioning, // Resource is being created or updated
796    ProvisionFailed,
797    Running, // Resource is active and configured as desired
798    Updating,
799    UpdateFailed,
800    Deleting, // Resource is being removed
801    DeleteFailed,
802    TeardownRequired, // Runtime-owned parts were removed; setup-owned parts remain
803    Deleted,          // Resource has been successfully removed (terminal state)
804    RefreshFailed,    // Resource heartbeat/health check failed
805}
806
807impl ResourceStatus {
808    pub fn is_terminal(&self) -> bool {
809        match self {
810            ResourceStatus::TeardownRequired => true,
811            ResourceStatus::Deleted => true,
812            ResourceStatus::ProvisionFailed => true,
813            ResourceStatus::UpdateFailed => true,
814            ResourceStatus::DeleteFailed => true,
815            ResourceStatus::RefreshFailed => true,
816            _ => false, // Pending, Provisioning, Updating, Deleting are not terminal
817        }
818    }
819}
820
821/// Describes the lifecycle of a resource within a stack, determining how it's managed and deployed.
822#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
823#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
824#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
825#[serde(rename_all = "kebab-case")]
826pub enum ResourceLifecycle {
827    /// Frozen resources are owned by setup. Setup creates, updates, and
828    /// deletes them. Alien may heartbeat them and may run explicit management
829    /// operations when setup granted management permissions.
830    Frozen,
831
832    /// Live resources are owned by Alien. Alien creates, updates, deletes, and
833    /// replaces them after setup, so Live resources require provision
834    /// permissions.
835    Live,
836}