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