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