Skip to main content

alien_core/
resource.rs

1use crate::error::Result;
2use serde::{Deserialize, Serialize};
3use std::any::Any;
4use std::borrow::Cow;
5use std::fmt::Debug;
6#[cfg(feature = "openapi")]
7use utoipa::openapi::schema::AdditionalProperties;
8#[cfg(feature = "openapi")]
9use utoipa::openapi::{ObjectBuilder, Ref, RefOr, Schema, Type};
10#[cfg(feature = "openapi")]
11use utoipa::{PartialSchema, ToSchema};
12
13/// Type alias for resource type identifiers
14#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct ResourceType(pub Cow<'static, str>);
17
18impl ResourceType {
19    /// Create a new ResourceType from a static string (const-friendly)
20    pub const fn from_static(s: &'static str) -> Self {
21        Self(Cow::Borrowed(s))
22    }
23}
24
25impl From<String> for ResourceType {
26    fn from(s: String) -> Self {
27        Self(Cow::Owned(s))
28    }
29}
30
31impl From<&str> for ResourceType {
32    fn from(s: &str) -> Self {
33        Self(Cow::Owned(s.to_string()))
34    }
35}
36
37impl std::fmt::Display for ResourceType {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        write!(f, "{}", self.0)
40    }
41}
42
43impl From<ResourceType> for String {
44    fn from(val: ResourceType) -> Self {
45        val.0.into_owned()
46    }
47}
48
49impl AsRef<str> for ResourceType {
50    fn as_ref(&self) -> &str {
51        &self.0
52    }
53}
54
55#[cfg(feature = "openapi")]
56impl PartialSchema for ResourceType {
57    fn schema() -> RefOr<Schema> {
58        RefOr::T(Schema::Object(
59            ObjectBuilder::new()
60                .schema_type(Type::String)
61                .description(Some("Resource type identifier that determines the specific kind of resource. This field is used for polymorphic deserialization and resource-specific behavior."))
62                .examples([
63                    "worker",
64                    "storage",
65                    "queue",
66                    "redis",
67                    "postgres"
68                ])
69                .build()
70        ))
71    }
72}
73
74#[cfg(feature = "openapi")]
75impl ToSchema for ResourceType {
76    fn name() -> std::borrow::Cow<'static, str> {
77        std::borrow::Cow::Borrowed("ResourceType")
78    }
79}
80
81/// Trait that defines the interface for all resource types in the Alien system.
82/// This trait enables extensibility by allowing new resource types to be registered
83/// and managed alongside built-in resources.
84pub trait ResourceDefinition: Debug + Send + Sync + 'static {
85    /// Returns the resource type for this instance
86    fn get_resource_type(&self) -> ResourceType;
87
88    /// Returns the unique identifier for this specific resource instance
89    fn id(&self) -> &str;
90
91    /// Returns the list of other resources this resource depends on
92    fn get_dependencies(&self) -> Vec<ResourceRef>;
93
94    /// Returns the permission profile name for this resource, if it has one.
95    ///
96    /// Used by `ServiceAccountDependenciesMutation` to wire the corresponding
97    /// `{profile}-sa` service account as a declared dependency so the executor
98    /// enforces ordering and propagates SA changes automatically.
99    ///
100    /// Override in concrete types that carry a `permissions` field (Container, Worker).
101    fn get_permissions(&self) -> Option<&str> {
102        None
103    }
104
105    /// Validates if an update from the current configuration to a new configuration is allowed
106    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()>;
107
108    /// Whether the executor may delete this resource and create it again when its create
109    /// failed and its config changed since.
110    ///
111    /// That replace is unsafe when deleting the half-created resource can destroy something the
112    /// create already holds: user data (a create can adopt an existing bucket, table or
113    /// database with the same name, and a key decrypts data stored elsewhere) or live capacity
114    /// (replicas a timed-out create already started, instances that already launched). Such a
115    /// resource is created again in place instead. That create may adopt the existing resource
116    /// by name, or fail on the name until the conflict is resolved by hand, but it never deletes
117    /// what is there.
118    fn replace_after_failed_create_is_safe(&self) -> bool {
119        true
120    }
121
122    /// Provides access to the underlying concrete type for downcasting
123    fn as_any(&self) -> &dyn Any;
124
125    /// Provides mutable access to the underlying concrete type for downcasting
126    fn as_any_mut(&mut self) -> &mut dyn Any;
127
128    /// Creates a boxed clone of this resource definition
129    fn box_clone(&self) -> Box<dyn ResourceDefinition>;
130
131    /// For equality comparison between resource definitions
132    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool;
133
134    /// Serialize this resource to a JSON value (without the "type" tag - that's added by Resource)
135    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
136
137    /// Resolves the fields of this config that point at a deployer stack input.
138    ///
139    /// A config can name an input instead of holding a value (for example the artifact
140    /// registry's `replicationRegionsInput`). The value is known only when a deployment is
141    /// prepared, so an update that adds such a reference can compare equal to the recorded,
142    /// reference-free config once the answer is empty. Return `None` when there is nothing to
143    /// resolve, or when the resolution cannot be made equal to a config without references (the
144    /// input is undeclared or answered with a value). Return the config with the references
145    /// that resolve to "no value" removed when it can. The frozen-resource check uses only
146    /// that last case, for a recorded config that lacks the reference.
147    ///
148    /// The next input-backed field implements this method instead of special-casing the check.
149    fn with_empty_input_references_removed(
150        &self,
151        _inputs: &crate::InputAnswers<'_>,
152    ) -> Option<Box<dyn ResourceDefinition>> {
153        None
154    }
155
156    /// The `(config field, input id)` pairs this config reads from deployer inputs. Names the
157    /// field in the message when a setup update is needed because an input now has a value.
158    fn input_references(&self) -> Vec<(&'static str, String)> {
159        Vec::new()
160    }
161}
162
163/// Clone implementation for boxed ResourceDefinition trait objects
164impl Clone for Box<dyn ResourceDefinition> {
165    fn clone(&self) -> Self {
166        self.box_clone()
167    }
168}
169
170#[derive(Debug, Clone)]
171pub struct Resource {
172    inner: Box<dyn ResourceDefinition>,
173}
174
175impl Serialize for Resource {
176    fn serialize<S: serde::Serializer>(
177        &self,
178        serializer: S,
179    ) -> std::result::Result<S::Ok, S::Error> {
180        let mut v = self
181            .inner
182            .to_json_value()
183            .map_err(serde::ser::Error::custom)?;
184        v.as_object_mut()
185            .ok_or_else(|| serde::ser::Error::custom("resource must serialize as object"))?
186            .insert(
187                "type".into(),
188                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
189            );
190        v.serialize(serializer)
191    }
192}
193
194impl<'de> Deserialize<'de> for Resource {
195    fn deserialize<D: serde::Deserializer<'de>>(
196        deserializer: D,
197    ) -> std::result::Result<Self, D::Error> {
198        let mut value = serde_json::Value::deserialize(deserializer)?;
199        let type_tag = value
200            .get("type")
201            .and_then(|v| v.as_str())
202            .ok_or_else(|| serde::de::Error::missing_field("type"))?
203            .to_string();
204
205        // Remove the "type" tag before passing to concrete deserializer
206        // (structs with deny_unknown_fields would reject it)
207        if let Some(obj) = value.as_object_mut() {
208            obj.remove("type");
209        }
210
211        let inner: Box<dyn ResourceDefinition> = match type_tag.as_str() {
212            "vault" => Box::new(
213                serde_json::from_value::<crate::resources::Vault>(value)
214                    .map_err(serde::de::Error::custom)?,
215            ),
216            "worker" => Box::new(
217                serde_json::from_value::<crate::resources::Worker>(value)
218                    .map_err(serde::de::Error::custom)?,
219            ),
220            "daemon" => Box::new(
221                serde_json::from_value::<crate::resources::Daemon>(value)
222                    .map_err(serde::de::Error::custom)?,
223            ),
224            "container" => Box::new(
225                serde_json::from_value::<crate::resources::Container>(value)
226                    .map_err(serde::de::Error::custom)?,
227            ),
228            "compute-cluster" => Box::new(
229                serde_json::from_value::<crate::resources::ComputeCluster>(value)
230                    .map_err(serde::de::Error::custom)?,
231            ),
232            "kubernetes-cluster" => Box::new(
233                serde_json::from_value::<crate::resources::KubernetesCluster>(value)
234                    .map_err(serde::de::Error::custom)?,
235            ),
236            "storage" => Box::new(
237                serde_json::from_value::<crate::resources::Storage>(value)
238                    .map_err(serde::de::Error::custom)?,
239            ),
240            "key" => Box::new(
241                serde_json::from_value::<crate::resources::Key>(value)
242                    .map_err(serde::de::Error::custom)?,
243            ),
244            "queue" => Box::new(
245                serde_json::from_value::<crate::resources::Queue>(value)
246                    .map_err(serde::de::Error::custom)?,
247            ),
248            "sandbox" => Box::new(
249                serde_json::from_value::<crate::resources::Sandbox>(value)
250                    .map_err(serde::de::Error::custom)?,
251            ),
252            "email" => Box::new(
253                serde_json::from_value::<crate::resources::Email>(value)
254                    .map_err(serde::de::Error::custom)?,
255            ),
256            "kv" => Box::new(
257                serde_json::from_value::<crate::resources::Kv>(value)
258                    .map_err(serde::de::Error::custom)?,
259            ),
260            "postgres" => Box::new(
261                serde_json::from_value::<crate::resources::Postgres>(value)
262                    .map_err(serde::de::Error::custom)?,
263            ),
264            "redis" => Box::new(
265                serde_json::from_value::<crate::resources::Redis>(value)
266                    .map_err(serde::de::Error::custom)?,
267            ),
268            "ai" => Box::new(
269                serde_json::from_value::<crate::resources::Ai>(value)
270                    .map_err(serde::de::Error::custom)?,
271            ),
272            "network" => Box::new(
273                serde_json::from_value::<crate::resources::Network>(value)
274                    .map_err(serde::de::Error::custom)?,
275            ),
276            "build" => Box::new(
277                serde_json::from_value::<crate::resources::Build>(value)
278                    .map_err(serde::de::Error::custom)?,
279            ),
280            "service-account" => Box::new(
281                serde_json::from_value::<crate::resources::ServiceAccount>(value)
282                    .map_err(serde::de::Error::custom)?,
283            ),
284            "artifact-registry" => Box::new(
285                serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
286                    .map_err(serde::de::Error::custom)?,
287            ),
288            "service_activation" => Box::new(
289                serde_json::from_value::<crate::resources::ServiceActivation>(value)
290                    .map_err(serde::de::Error::custom)?,
291            ),
292            "remote-stack-management" => Box::new(
293                serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
294                    .map_err(serde::de::Error::custom)?,
295            ),
296            "resource-access" => Box::new(
297                serde_json::from_value::<crate::resources::RemoteBindings>(value)
298                    .map_err(serde::de::Error::custom)?,
299            ),
300            "verifier" => Box::new(
301                serde_json::from_value::<crate::resources::SigningVerifier>(value)
302                    .map_err(serde::de::Error::custom)?,
303            ),
304            "azure_resource_group" => Box::new(
305                serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
306                    .map_err(serde::de::Error::custom)?,
307            ),
308            "gcp_agent_platform_engine" => Box::new(
309                serde_json::from_value::<crate::resources::GcpAgentPlatformEngine>(value)
310                    .map_err(serde::de::Error::custom)?,
311            ),
312            "azure_storage_account" => Box::new(
313                serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
314                    .map_err(serde::de::Error::custom)?,
315            ),
316            "azure_container_apps_environment" => Box::new(
317                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
318                    .map_err(serde::de::Error::custom)?,
319            ),
320            "azure_service_bus_namespace" => Box::new(
321                serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
322                    .map_err(serde::de::Error::custom)?,
323            ),
324            "experimental/aws-opensearch" => Box::new(
325                serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
326                    .map_err(serde::de::Error::custom)?,
327            ),
328            other => {
329                return Err(serde::de::Error::unknown_variant(
330                    other,
331                    &[
332                        "vault",
333                        "worker",
334                        "daemon",
335                        "container",
336                        "compute-cluster",
337                        "kubernetes-cluster",
338                        "storage",
339                        "key",
340                        "queue",
341                        "sandbox",
342                        "email",
343                        "kv",
344                        "postgres",
345                        "redis",
346                        "ai",
347                        "network",
348                        "build",
349                        "service-account",
350                        "artifact-registry",
351                        "service_activation",
352                        "remote-stack-management",
353                        "resource-access",
354                        "verifier",
355                        "azure_resource_group",
356                        "gcp_agent_platform_engine",
357                        "azure_storage_account",
358                        "azure_container_apps_environment",
359                        "azure_service_bus_namespace",
360                        "experimental/aws-opensearch",
361                    ],
362                ))
363            }
364        };
365
366        Ok(Resource { inner })
367    }
368}
369
370impl Resource {
371    /// Creates a new Resource from any type that implements ResourceDefinition
372    pub fn new<T: ResourceDefinition>(resource: T) -> Self {
373        Self {
374            inner: Box::new(resource),
375        }
376    }
377
378    /// Creates a new Resource from a boxed ResourceDefinition
379    pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
380        Self {
381            inner: boxed_resource,
382        }
383    }
384
385    /// Returns the resource type identifier
386    pub fn resource_type(&self) -> ResourceType {
387        self.inner.get_resource_type()
388    }
389
390    /// Returns the unique identifier for this resource instance
391    pub fn id(&self) -> &str {
392        self.inner.id()
393    }
394
395    /// Returns the list of other resources this resource depends on
396    pub fn get_dependencies(&self) -> Vec<ResourceRef> {
397        self.inner.get_dependencies()
398    }
399
400    /// Returns the permission profile name for this resource, if it has one.
401    pub fn get_permissions(&self) -> Option<&str> {
402        self.inner.get_permissions()
403    }
404
405    /// Validates if an update from the current configuration to a new configuration is allowed
406    pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
407        self.inner.validate_update(new_config.inner.as_ref())
408    }
409
410    /// Whether a failed create may be deleted and created again. See
411    /// [`ResourceDefinition::replace_after_failed_create_is_safe`].
412    pub fn replace_after_failed_create_is_safe(&self) -> bool {
413        self.inner.replace_after_failed_create_is_safe()
414    }
415
416    /// See [`ResourceDefinition::with_empty_input_references_removed`].
417    pub fn with_empty_input_references_removed(
418        &self,
419        inputs: &crate::InputAnswers<'_>,
420    ) -> Option<Resource> {
421        self.inner
422            .with_empty_input_references_removed(inputs)
423            .map(Resource::from_boxed)
424    }
425
426    /// See [`ResourceDefinition::input_references`].
427    pub fn input_references(&self) -> Vec<(&'static str, String)> {
428        self.inner.input_references()
429    }
430
431    /// Provides access to the underlying ResourceDefinition trait object
432    pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
433        self.inner.as_ref()
434    }
435
436    /// Generic downcasting for any type
437    pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
438        self.inner.as_any().downcast_ref::<T>()
439    }
440
441    /// Generic mutable downcasting for any type
442    pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
443        self.inner.as_any_mut().downcast_mut::<T>()
444    }
445}
446
447impl PartialEq for Resource {
448    fn eq(&self, other: &Self) -> bool {
449        self.inner.resource_eq(other.inner.as_ref())
450    }
451}
452
453impl Eq for Resource {}
454
455/// OpenAPI schema implementation for Resource.
456///
457/// The schema represents the flattened JSON structure of any resource type in the Alien system.
458/// All resources have a common base structure with `type` and `id` fields, plus type-specific
459/// additional properties that vary depending on the concrete resource implementation.
460///
461/// # Schema Structure
462/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
463/// - `id` (required): The unique identifier for this specific resource instance
464/// - Additional properties: Type-specific fields that vary by resource type (e.g., Worker has `code`, `memory_mb`, etc.)
465///
466/// # Example JSON
467/// ```json
468/// {
469///   "type": "worker",
470///   "id": "my-function",
471///   "code": { "type": "image", "image": "my-image:latest" },
472///   "memoryMb": 512,
473///   "timeoutSeconds": 30
474/// }
475/// ```
476#[cfg(feature = "openapi")]
477impl PartialSchema for Resource {
478    fn schema() -> RefOr<Schema> {
479        RefOr::T(Schema::Object(
480            ObjectBuilder::new()
481                .schema_type(Type::Object)
482                .property("type", Ref::from_schema_name("ResourceType"))
483                .property("id",
484                    ObjectBuilder::new()
485                        .schema_type(Type::String)
486                        .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."))
487                        .build()
488                )
489                .required("type")
490                .required("id")
491                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
492                .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."))
493                .build()
494        ))
495    }
496}
497
498#[cfg(feature = "openapi")]
499impl ToSchema for Resource {
500    fn name() -> std::borrow::Cow<'static, str> {
501        std::borrow::Cow::Borrowed("BaseResource")
502    }
503}
504
505/// Reference to a resource by its stable id and resource type.
506#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
507#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
508#[serde(rename_all = "camelCase")]
509pub struct ResourceRef {
510    #[serde(rename = "type")]
511    pub resource_type: ResourceType,
512    pub id: String,
513}
514
515impl ResourceRef {
516    /// Creates a new ResourceRef
517    pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
518        Self {
519            resource_type,
520            id: id.into(),
521        }
522    }
523
524    /// Returns the resource type
525    pub fn resource_type(&self) -> &ResourceType {
526        &self.resource_type
527    }
528
529    /// Returns the resource id
530    pub fn id(&self) -> &str {
531        &self.id
532    }
533}
534
535impl<T: ResourceDefinition> From<&T> for ResourceRef {
536    fn from(resource: &T) -> Self {
537        Self::new(resource.get_resource_type(), resource.id())
538    }
539}
540
541impl From<&Resource> for ResourceRef {
542    fn from(resource: &Resource) -> Self {
543        Self::new(resource.resource_type(), resource.id())
544    }
545}
546
547/// Trait that defines the interface for all resource output types in the Alien system.
548/// This trait enables extensibility by allowing new resource output types to be registered
549/// and managed alongside built-in resource outputs.
550/// Resource observations may gain fields as providers and servers are upgraded.
551/// Implementations should accept unknown output fields so older readers remain compatible;
552/// user-authored resource configuration is validated separately.
553pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
554    /// Whether dependents may reconcile. Temporary unavailability preserves their
555    /// identities and controller progress until the dependency recovers.
556    fn is_available(&self) -> bool {
557        true
558    }
559
560    /// Returns the resource type for this instance
561    fn get_resource_type(&self) -> ResourceType;
562
563    /// Provides access to the underlying concrete type for downcasting
564    fn as_any(&self) -> &dyn Any;
565
566    /// Creates a boxed clone of this resource outputs
567    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
568
569    /// For equality comparison between resource outputs
570    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
571
572    /// Serialize this resource outputs to a JSON value (without the "type" tag - that's added by ResourceOutputs)
573    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
574}
575
576/// Clone implementation for boxed ResourceOutputsDefinition trait objects
577impl Clone for Box<dyn ResourceOutputsDefinition> {
578    fn clone(&self) -> Self {
579        self.box_clone()
580    }
581}
582
583/// New Resource outputs wrapper that can hold any ResourceOutputsDefinition.
584/// This replaces the old ResourceOutputs enum to enable runtime extensibility.
585#[derive(Debug, Clone)]
586pub struct ResourceOutputs {
587    inner: Box<dyn ResourceOutputsDefinition>,
588}
589
590impl Serialize for ResourceOutputs {
591    fn serialize<S: serde::Serializer>(
592        &self,
593        serializer: S,
594    ) -> std::result::Result<S::Ok, S::Error> {
595        let mut v = self
596            .inner
597            .to_json_value()
598            .map_err(serde::ser::Error::custom)?;
599        v.as_object_mut()
600            .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
601            .insert(
602                "type".into(),
603                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
604            );
605        v.serialize(serializer)
606    }
607}
608
609impl<'de> Deserialize<'de> for ResourceOutputs {
610    fn deserialize<D: serde::Deserializer<'de>>(
611        deserializer: D,
612    ) -> std::result::Result<Self, D::Error> {
613        let mut value = serde_json::Value::deserialize(deserializer)?;
614        let type_tag = value
615            .get("type")
616            .and_then(|v| v.as_str())
617            .ok_or_else(|| serde::de::Error::missing_field("type"))?
618            .to_string();
619
620        // Remove the "type" tag before passing to concrete deserializer
621        // (structs with deny_unknown_fields would reject it)
622        if let Some(obj) = value.as_object_mut() {
623            obj.remove("type");
624        }
625
626        let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
627            "vault" => Box::new(
628                serde_json::from_value::<crate::resources::VaultOutputs>(value)
629                    .map_err(serde::de::Error::custom)?,
630            ),
631            "worker" => Box::new(
632                serde_json::from_value::<crate::resources::WorkerOutputs>(value)
633                    .map_err(serde::de::Error::custom)?,
634            ),
635            "daemon" => Box::new(
636                serde_json::from_value::<crate::resources::DaemonOutputs>(value)
637                    .map_err(serde::de::Error::custom)?,
638            ),
639            "container" => Box::new(
640                serde_json::from_value::<crate::resources::ContainerOutputs>(value)
641                    .map_err(serde::de::Error::custom)?,
642            ),
643            "compute-cluster" => Box::new(
644                serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
645                    .map_err(serde::de::Error::custom)?,
646            ),
647            "storage" => Box::new(
648                serde_json::from_value::<crate::resources::StorageOutputs>(value)
649                    .map_err(serde::de::Error::custom)?,
650            ),
651            "key" => Box::new(
652                serde_json::from_value::<crate::resources::KeyOutputs>(value)
653                    .map_err(serde::de::Error::custom)?,
654            ),
655            "queue" => Box::new(
656                serde_json::from_value::<crate::resources::QueueOutputs>(value)
657                    .map_err(serde::de::Error::custom)?,
658            ),
659            "sandbox" => Box::new(
660                serde_json::from_value::<crate::resources::SandboxOutputs>(value)
661                    .map_err(serde::de::Error::custom)?,
662            ),
663            "email" => Box::new(
664                serde_json::from_value::<crate::resources::EmailOutputs>(value)
665                    .map_err(serde::de::Error::custom)?,
666            ),
667            "kv" => Box::new(
668                serde_json::from_value::<crate::resources::KvOutputs>(value)
669                    .map_err(serde::de::Error::custom)?,
670            ),
671            "postgres" => Box::new(
672                serde_json::from_value::<crate::resources::PostgresOutputs>(value)
673                    .map_err(serde::de::Error::custom)?,
674            ),
675            "redis" => Box::new(
676                serde_json::from_value::<crate::resources::RedisOutputs>(value)
677                    .map_err(serde::de::Error::custom)?,
678            ),
679            "ai" => Box::new(
680                serde_json::from_value::<crate::resources::AiOutputs>(value)
681                    .map_err(serde::de::Error::custom)?,
682            ),
683            "network" => Box::new(
684                serde_json::from_value::<crate::resources::NetworkOutputs>(value)
685                    .map_err(serde::de::Error::custom)?,
686            ),
687            "build" => Box::new(
688                serde_json::from_value::<crate::resources::BuildOutputs>(value)
689                    .map_err(serde::de::Error::custom)?,
690            ),
691            "service-account" => Box::new(
692                serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
693                    .map_err(serde::de::Error::custom)?,
694            ),
695            "artifact-registry" => Box::new(
696                serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
697                    .map_err(serde::de::Error::custom)?,
698            ),
699            "service_activation" => Box::new(
700                serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
701                    .map_err(serde::de::Error::custom)?,
702            ),
703            "remote-stack-management" => Box::new(
704                serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
705                    .map_err(serde::de::Error::custom)?,
706            ),
707            "resource-access" => Box::new(
708                serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
709                    .map_err(serde::de::Error::custom)?,
710            ),
711            "verifier" => Box::new(
712                serde_json::from_value::<crate::resources::SigningVerifierOutputs>(value)
713                    .map_err(serde::de::Error::custom)?,
714            ),
715            "kubernetes-cluster" => Box::new(
716                serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
717                    .map_err(serde::de::Error::custom)?,
718            ),
719            "azure_resource_group" => Box::new(
720                serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
721                    .map_err(serde::de::Error::custom)?,
722            ),
723            "azure_storage_account" => Box::new(
724                serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
725                    .map_err(serde::de::Error::custom)?,
726            ),
727            "azure_container_apps_environment" => Box::new(
728                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
729                    value,
730                )
731                .map_err(serde::de::Error::custom)?,
732            ),
733            "azure_service_bus_namespace" => Box::new(
734                serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
735                    .map_err(serde::de::Error::custom)?,
736            ),
737            "experimental/aws-opensearch" => Box::new(
738                serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
739                    .map_err(serde::de::Error::custom)?,
740            ),
741            other => {
742                return Err(serde::de::Error::unknown_variant(
743                    other,
744                    &[
745                        "vault",
746                        "worker",
747                        "daemon",
748                        "container",
749                        "compute-cluster",
750                        "storage",
751                        "key",
752                        "queue",
753                        "sandbox",
754                        "email",
755                        "kv",
756                        "postgres",
757                        "redis",
758                        "ai",
759                        "network",
760                        "build",
761                        "service-account",
762                        "artifact-registry",
763                        "service_activation",
764                        "remote-stack-management",
765                        "resource-access",
766                        "verifier",
767                        "kubernetes-cluster",
768                        "azure_resource_group",
769                        "azure_storage_account",
770                        "azure_container_apps_environment",
771                        "azure_service_bus_namespace",
772                        "experimental/aws-opensearch",
773                    ],
774                ))
775            }
776        };
777
778        Ok(ResourceOutputs { inner })
779    }
780}
781
782impl ResourceOutputs {
783    /// Creates a new ResourceOutputs from any type that implements ResourceOutputsDefinition
784    pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
785        Self {
786            inner: Box::new(outputs),
787        }
788    }
789
790    /// Provides access to the underlying ResourceOutputsDefinition trait object
791    pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
792        self.inner.as_ref()
793    }
794
795    /// Generic downcasting for any type
796    pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
797        self.inner.as_any().downcast_ref::<T>()
798    }
799}
800
801impl PartialEq for ResourceOutputs {
802    fn eq(&self, other: &Self) -> bool {
803        self.inner.outputs_eq(other.inner.as_ref())
804    }
805}
806
807impl Eq for ResourceOutputs {}
808
809/// OpenAPI schema implementation for ResourceOutputs.
810///
811/// The schema represents the flattened JSON structure of any resource outputs in the Alien system.
812/// All resource outputs have a common base structure with a `type` field, plus type-specific
813/// additional properties that vary depending on the concrete resource implementation.
814///
815/// # Schema Structure
816/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
817/// - Additional properties: Type-specific output fields that vary by resource type
818///
819/// # Example JSON
820/// ```json
821/// {
822///   "type": "worker",
823///   "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
824///   "functionUrl": "https://abc123.lambda-url.us-east-1.on.aws/"
825/// }
826/// ```
827#[cfg(feature = "openapi")]
828impl PartialSchema for ResourceOutputs {
829    fn schema() -> RefOr<Schema> {
830        RefOr::T(Schema::Object(
831            ObjectBuilder::new()
832                .schema_type(Type::Object)
833                .property("type", Ref::from_schema_name("ResourceType"))
834                .required("type")
835                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
836                .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."))
837                .build()
838        ))
839    }
840}
841
842#[cfg(feature = "openapi")]
843impl ToSchema for ResourceOutputs {
844    fn name() -> std::borrow::Cow<'static, str> {
845        std::borrow::Cow::Borrowed("BaseResourceOutputs")
846    }
847}
848
849/// Represents the high-level status of a resource during its lifecycle.
850#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
851#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
852#[serde(rename_all = "kebab-case")]
853pub enum ResourceStatus {
854    Pending,      // Initial state before any action starts
855    Provisioning, // Resource is being created or updated
856    ProvisionFailed,
857    Running, // Resource is active and configured as desired
858    Updating,
859    UpdateFailed,
860    Deleting, // Resource is being removed
861    DeleteFailed,
862    TeardownRequired, // Runtime-owned parts were removed; setup-owned parts remain
863    Deleted,          // Resource has been successfully removed (terminal state)
864    RefreshFailed,    // Resource heartbeat/health check failed
865}
866
867impl ResourceStatus {
868    pub fn is_terminal(&self) -> bool {
869        match self {
870            ResourceStatus::TeardownRequired => true,
871            ResourceStatus::Deleted => true,
872            ResourceStatus::ProvisionFailed => true,
873            ResourceStatus::UpdateFailed => true,
874            ResourceStatus::DeleteFailed => true,
875            ResourceStatus::RefreshFailed => true,
876            _ => false, // Pending, Provisioning, Updating, Deleting are not terminal
877        }
878    }
879}
880
881/// Describes the lifecycle of a resource within a stack, determining how it's managed and deployed.
882#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
883#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
884#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
885#[serde(rename_all = "kebab-case")]
886pub enum ResourceLifecycle {
887    /// Frozen resources are owned by setup. Setup creates, updates, and
888    /// deletes them. Alien may heartbeat them and may run explicit management
889    /// operations when setup granted management permissions.
890    Frozen,
891
892    /// Live resources are owned by Alien. Alien creates, updates, deletes, and
893    /// replaces them after setup, so Live resources require provision
894    /// permissions.
895    Live,
896}