alien-core 1.10.5

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
use crate::error::Result;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::borrow::Cow;
use std::fmt::Debug;
#[cfg(feature = "openapi")]
use utoipa::openapi::schema::AdditionalProperties;
#[cfg(feature = "openapi")]
use utoipa::openapi::{ObjectBuilder, Ref, RefOr, Schema, Type};
#[cfg(feature = "openapi")]
use utoipa::{PartialSchema, ToSchema};

/// Type alias for resource type identifiers
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ResourceType(pub Cow<'static, str>);

impl ResourceType {
    /// Create a new ResourceType from a static string (const-friendly)
    pub const fn from_static(s: &'static str) -> Self {
        Self(Cow::Borrowed(s))
    }
}

impl From<String> for ResourceType {
    fn from(s: String) -> Self {
        Self(Cow::Owned(s))
    }
}

impl From<&str> for ResourceType {
    fn from(s: &str) -> Self {
        Self(Cow::Owned(s.to_string()))
    }
}

impl std::fmt::Display for ResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<ResourceType> for String {
    fn from(val: ResourceType) -> Self {
        val.0.into_owned()
    }
}

impl AsRef<str> for ResourceType {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "openapi")]
impl PartialSchema for ResourceType {
    fn schema() -> RefOr<Schema> {
        RefOr::T(Schema::Object(
            ObjectBuilder::new()
                .schema_type(Type::String)
                .description(Some("Resource type identifier that determines the specific kind of resource. This field is used for polymorphic deserialization and resource-specific behavior."))
                .examples([
                    "worker",
                    "storage",
                    "queue",
                    "redis",
                    "postgres"
                ])
                .build()
        ))
    }
}

#[cfg(feature = "openapi")]
impl ToSchema for ResourceType {
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("ResourceType")
    }
}

/// Trait that defines the interface for all resource types in the Alien system.
/// This trait enables extensibility by allowing new resource types to be registered
/// and managed alongside built-in resources.
pub trait ResourceDefinition: Debug + Send + Sync + 'static {
    /// Returns the resource type for this instance
    fn get_resource_type(&self) -> ResourceType;

    /// Returns the unique identifier for this specific resource instance
    fn id(&self) -> &str;

    /// Returns the list of other resources this resource depends on
    fn get_dependencies(&self) -> Vec<ResourceRef>;

    /// Returns the permission profile name for this resource, if it has one.
    ///
    /// Used by `ServiceAccountDependenciesMutation` to wire the corresponding
    /// `{profile}-sa` service account as a declared dependency so the executor
    /// enforces ordering and propagates SA changes automatically.
    ///
    /// Override in concrete types that carry a `permissions` field (Container, Worker).
    fn get_permissions(&self) -> Option<&str> {
        None
    }

    /// Validates if an update from the current configuration to a new configuration is allowed
    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()>;

    /// Provides access to the underlying concrete type for downcasting
    fn as_any(&self) -> &dyn Any;

    /// Provides mutable access to the underlying concrete type for downcasting
    fn as_any_mut(&mut self) -> &mut dyn Any;

    /// Creates a boxed clone of this resource definition
    fn box_clone(&self) -> Box<dyn ResourceDefinition>;

    /// For equality comparison between resource definitions
    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool;

    /// Serialize this resource to a JSON value (without the "type" tag - that's added by Resource)
    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
}

/// Clone implementation for boxed ResourceDefinition trait objects
impl Clone for Box<dyn ResourceDefinition> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

#[derive(Debug, Clone)]
pub struct Resource {
    inner: Box<dyn ResourceDefinition>,
}

impl Serialize for Resource {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        let mut v = self
            .inner
            .to_json_value()
            .map_err(serde::ser::Error::custom)?;
        v.as_object_mut()
            .ok_or_else(|| serde::ser::Error::custom("resource must serialize as object"))?
            .insert(
                "type".into(),
                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
            );
        v.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Resource {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        let mut value = serde_json::Value::deserialize(deserializer)?;
        let type_tag = value
            .get("type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| serde::de::Error::missing_field("type"))?
            .to_string();

        // Remove the "type" tag before passing to concrete deserializer
        // (structs with deny_unknown_fields would reject it)
        if let Some(obj) = value.as_object_mut() {
            obj.remove("type");
        }

        let inner: Box<dyn ResourceDefinition> = match type_tag.as_str() {
            "vault" => Box::new(
                serde_json::from_value::<crate::resources::Vault>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "worker" => Box::new(
                serde_json::from_value::<crate::resources::Worker>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "daemon" => Box::new(
                serde_json::from_value::<crate::resources::Daemon>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "container" => Box::new(
                serde_json::from_value::<crate::resources::Container>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "compute-cluster" => Box::new(
                serde_json::from_value::<crate::resources::ComputeCluster>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "kubernetes-cluster" => Box::new(
                serde_json::from_value::<crate::resources::KubernetesCluster>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "storage" => Box::new(
                serde_json::from_value::<crate::resources::Storage>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "queue" => Box::new(
                serde_json::from_value::<crate::resources::Queue>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "kv" => Box::new(
                serde_json::from_value::<crate::resources::Kv>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "network" => Box::new(
                serde_json::from_value::<crate::resources::Network>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "build" => Box::new(
                serde_json::from_value::<crate::resources::Build>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "service-account" => Box::new(
                serde_json::from_value::<crate::resources::ServiceAccount>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "artifact-registry" => Box::new(
                serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "service_activation" => Box::new(
                serde_json::from_value::<crate::resources::ServiceActivation>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "remote-stack-management" => Box::new(
                serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_resource_group" => Box::new(
                serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_storage_account" => Box::new(
                serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_container_apps_environment" => Box::new(
                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_service_bus_namespace" => Box::new(
                serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            other => {
                return Err(serde::de::Error::unknown_variant(
                    other,
                    &[
                        "vault",
                        "worker",
                        "daemon",
                        "container",
                        "compute-cluster",
                        "kubernetes-cluster",
                        "storage",
                        "queue",
                        "kv",
                        "network",
                        "build",
                        "service-account",
                        "artifact-registry",
                        "service_activation",
                        "remote-stack-management",
                        "azure_resource_group",
                        "azure_storage_account",
                        "azure_container_apps_environment",
                        "azure_service_bus_namespace",
                    ],
                ))
            }
        };

        Ok(Resource { inner })
    }
}

impl Resource {
    /// Creates a new Resource from any type that implements ResourceDefinition
    pub fn new<T: ResourceDefinition>(resource: T) -> Self {
        Self {
            inner: Box::new(resource),
        }
    }

    /// Creates a new Resource from a boxed ResourceDefinition
    pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
        Self {
            inner: boxed_resource,
        }
    }

    /// Returns the resource type identifier
    pub fn resource_type(&self) -> ResourceType {
        self.inner.get_resource_type()
    }

    /// Returns the unique identifier for this resource instance
    pub fn id(&self) -> &str {
        self.inner.id()
    }

    /// Returns the list of other resources this resource depends on
    pub fn get_dependencies(&self) -> Vec<ResourceRef> {
        self.inner.get_dependencies()
    }

    /// Returns the permission profile name for this resource, if it has one.
    pub fn get_permissions(&self) -> Option<&str> {
        self.inner.get_permissions()
    }

    /// Validates if an update from the current configuration to a new configuration is allowed
    pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
        self.inner.validate_update(new_config.inner.as_ref())
    }

    /// Provides access to the underlying ResourceDefinition trait object
    pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
        self.inner.as_ref()
    }

    /// Generic downcasting for any type
    pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
        self.inner.as_any().downcast_ref::<T>()
    }

    /// Generic mutable downcasting for any type
    pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
        self.inner.as_any_mut().downcast_mut::<T>()
    }
}

impl PartialEq for Resource {
    fn eq(&self, other: &Self) -> bool {
        self.inner.resource_eq(other.inner.as_ref())
    }
}

impl Eq for Resource {}

/// OpenAPI schema implementation for Resource.
///
/// The schema represents the flattened JSON structure of any resource type in the Alien system.
/// All resources have a common base structure with `type` and `id` fields, plus type-specific
/// additional properties that vary depending on the concrete resource implementation.
///
/// # Schema Structure
/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
/// - `id` (required): The unique identifier for this specific resource instance
/// - Additional properties: Type-specific fields that vary by resource type (e.g., Worker has `code`, `memory_mb`, etc.)
///
/// # Example JSON
/// ```json
/// {
///   "type": "worker",
///   "id": "my-function",
///   "code": { "type": "image", "image": "my-image:latest" },
///   "memoryMb": 512,
///   "timeoutSeconds": 30
/// }
/// ```
#[cfg(feature = "openapi")]
impl PartialSchema for Resource {
    fn schema() -> RefOr<Schema> {
        RefOr::T(Schema::Object(
            ObjectBuilder::new()
                .schema_type(Type::Object)
                .property("type", Ref::from_schema_name("ResourceType"))
                .property("id",
                    ObjectBuilder::new()
                        .schema_type(Type::String)
                        .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."))
                        .build()
                )
                .required("type")
                .required("id")
                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
                .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."))
                .build()
        ))
    }
}

#[cfg(feature = "openapi")]
impl ToSchema for Resource {
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("BaseResource")
    }
}

/// New ResourceRef that works with any resource type.
/// This can eventually replace the enum-based ResourceRef for full extensibility.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ResourceRef {
    #[serde(rename = "type")]
    pub resource_type: ResourceType,
    pub id: String,
}

impl ResourceRef {
    /// Creates a new ResourceRef
    pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
        Self {
            resource_type,
            id: id.into(),
        }
    }

    /// Returns the resource type
    pub fn resource_type(&self) -> &ResourceType {
        &self.resource_type
    }

    /// Returns the resource id
    pub fn id(&self) -> &str {
        &self.id
    }
}

impl<T: ResourceDefinition> From<&T> for ResourceRef {
    fn from(resource: &T) -> Self {
        Self::new(resource.get_resource_type(), resource.id())
    }
}

impl From<&Resource> for ResourceRef {
    fn from(resource: &Resource) -> Self {
        Self::new(resource.resource_type(), resource.id())
    }
}

/// Trait that defines the interface for all resource output types in the Alien system.
/// This trait enables extensibility by allowing new resource output types to be registered
/// and managed alongside built-in resource outputs.
pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
    /// Returns the resource type for this instance
    fn get_resource_type(&self) -> ResourceType;

    /// Provides access to the underlying concrete type for downcasting
    fn as_any(&self) -> &dyn Any;

    /// Creates a boxed clone of this resource outputs
    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;

    /// For equality comparison between resource outputs
    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;

    /// Serialize this resource outputs to a JSON value (without the "type" tag - that's added by ResourceOutputs)
    fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
}

/// Clone implementation for boxed ResourceOutputsDefinition trait objects
impl Clone for Box<dyn ResourceOutputsDefinition> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

/// New Resource outputs wrapper that can hold any ResourceOutputsDefinition.
/// This replaces the old ResourceOutputs enum to enable runtime extensibility.
#[derive(Debug, Clone)]
pub struct ResourceOutputs {
    inner: Box<dyn ResourceOutputsDefinition>,
}

impl Serialize for ResourceOutputs {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        let mut v = self
            .inner
            .to_json_value()
            .map_err(serde::ser::Error::custom)?;
        v.as_object_mut()
            .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
            .insert(
                "type".into(),
                serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
            );
        v.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for ResourceOutputs {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        let mut value = serde_json::Value::deserialize(deserializer)?;
        let type_tag = value
            .get("type")
            .and_then(|v| v.as_str())
            .ok_or_else(|| serde::de::Error::missing_field("type"))?
            .to_string();

        // Remove the "type" tag before passing to concrete deserializer
        // (structs with deny_unknown_fields would reject it)
        if let Some(obj) = value.as_object_mut() {
            obj.remove("type");
        }

        let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
            "vault" => Box::new(
                serde_json::from_value::<crate::resources::VaultOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "worker" => Box::new(
                serde_json::from_value::<crate::resources::WorkerOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "daemon" => Box::new(
                serde_json::from_value::<crate::resources::DaemonOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "container" => Box::new(
                serde_json::from_value::<crate::resources::ContainerOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "compute-cluster" => Box::new(
                serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "storage" => Box::new(
                serde_json::from_value::<crate::resources::StorageOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "queue" => Box::new(
                serde_json::from_value::<crate::resources::QueueOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "kv" => Box::new(
                serde_json::from_value::<crate::resources::KvOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "network" => Box::new(
                serde_json::from_value::<crate::resources::NetworkOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "build" => Box::new(
                serde_json::from_value::<crate::resources::BuildOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "service-account" => Box::new(
                serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "artifact-registry" => Box::new(
                serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "service_activation" => Box::new(
                serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "remote-stack-management" => Box::new(
                serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "kubernetes-cluster" => Box::new(
                serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_resource_group" => Box::new(
                serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_storage_account" => Box::new(
                serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            "azure_container_apps_environment" => Box::new(
                serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
                    value,
                )
                .map_err(serde::de::Error::custom)?,
            ),
            "azure_service_bus_namespace" => Box::new(
                serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
                    .map_err(serde::de::Error::custom)?,
            ),
            other => {
                return Err(serde::de::Error::unknown_variant(
                    other,
                    &[
                        "vault",
                        "worker",
                        "daemon",
                        "container",
                        "compute-cluster",
                        "storage",
                        "queue",
                        "kv",
                        "network",
                        "build",
                        "service-account",
                        "artifact-registry",
                        "service_activation",
                        "remote-stack-management",
                        "kubernetes-cluster",
                        "azure_resource_group",
                        "azure_storage_account",
                        "azure_container_apps_environment",
                        "azure_service_bus_namespace",
                    ],
                ))
            }
        };

        Ok(ResourceOutputs { inner })
    }
}

impl ResourceOutputs {
    /// Creates a new ResourceOutputs from any type that implements ResourceOutputsDefinition
    pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
        Self {
            inner: Box::new(outputs),
        }
    }

    /// Provides access to the underlying ResourceOutputsDefinition trait object
    pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
        self.inner.as_ref()
    }

    /// Generic downcasting for any type
    pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
        self.inner.as_any().downcast_ref::<T>()
    }
}

impl PartialEq for ResourceOutputs {
    fn eq(&self, other: &Self) -> bool {
        self.inner.outputs_eq(other.inner.as_ref())
    }
}

impl Eq for ResourceOutputs {}

/// OpenAPI schema implementation for ResourceOutputs.
///
/// The schema represents the flattened JSON structure of any resource outputs in the Alien system.
/// All resource outputs have a common base structure with a `type` field, plus type-specific
/// additional properties that vary depending on the concrete resource implementation.
///
/// # Schema Structure
/// - `type` (required): The resource type identifier (e.g., "worker", "storage", "queue")
/// - Additional properties: Type-specific output fields that vary by resource type
///
/// # Example JSON
/// ```json
/// {
///   "type": "worker",
///   "functionArn": "arn:aws:lambda:us-east-1:123456789012:function:my-function",
///   "functionUrl": "https://abc123.lambda-url.us-east-1.on.aws/"
/// }
/// ```
#[cfg(feature = "openapi")]
impl PartialSchema for ResourceOutputs {
    fn schema() -> RefOr<Schema> {
        RefOr::T(Schema::Object(
            ObjectBuilder::new()
                .schema_type(Type::Object)
                .property("type", Ref::from_schema_name("ResourceType"))
                .required("type")
                .additional_properties(Some(AdditionalProperties::FreeForm(true)))
                .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."))
                .build()
        ))
    }
}

#[cfg(feature = "openapi")]
impl ToSchema for ResourceOutputs {
    fn name() -> std::borrow::Cow<'static, str> {
        std::borrow::Cow::Borrowed("BaseResourceOutputs")
    }
}

/// Represents the high-level status of a resource during its lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ResourceStatus {
    Pending,      // Initial state before any action starts
    Provisioning, // Resource is being created or updated
    ProvisionFailed,
    Running, // Resource is active and configured as desired
    Updating,
    UpdateFailed,
    Deleting, // Resource is being removed
    DeleteFailed,
    TeardownRequired, // Runtime-owned parts were removed; setup-owned parts remain
    Deleted,          // Resource has been successfully removed (terminal state)
    RefreshFailed,    // Resource heartbeat/health check failed
}

impl ResourceStatus {
    pub fn is_terminal(&self) -> bool {
        match self {
            ResourceStatus::TeardownRequired => true,
            ResourceStatus::Deleted => true,
            ResourceStatus::ProvisionFailed => true,
            ResourceStatus::UpdateFailed => true,
            ResourceStatus::DeleteFailed => true,
            ResourceStatus::RefreshFailed => true,
            _ => false, // Pending, Provisioning, Updating, Deleting are not terminal
        }
    }
}

/// Describes the lifecycle of a resource within a stack, determining how it's managed and deployed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ResourceLifecycle {
    /// Frozen resources are owned by setup. Setup creates, updates, and
    /// deletes them. Alien may heartbeat them and may run explicit management
    /// operations when setup granted management permissions.
    Frozen,

    /// Live resources are owned by Alien. Alien creates, updates, deletes, and
    /// replaces them after setup, so Live resources require provision
    /// permissions.
    Live,
}