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