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