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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct ResourceType(pub Cow<'static, str>);
17
18impl ResourceType {
19 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
81pub trait ResourceDefinition: Debug + Send + Sync + 'static {
85 fn get_resource_type(&self) -> ResourceType;
87
88 fn id(&self) -> &str;
90
91 fn get_dependencies(&self) -> Vec<ResourceRef>;
93
94 fn get_permissions(&self) -> Option<&str> {
102 None
103 }
104
105 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()>;
107
108 fn as_any(&self) -> &dyn Any;
110
111 fn as_any_mut(&mut self) -> &mut dyn Any;
113
114 fn box_clone(&self) -> Box<dyn ResourceDefinition>;
116
117 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool;
119
120 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
122}
123
124impl 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 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 "ai" => Box::new(
218 serde_json::from_value::<crate::resources::Ai>(value)
219 .map_err(serde::de::Error::custom)?,
220 ),
221 "network" => Box::new(
222 serde_json::from_value::<crate::resources::Network>(value)
223 .map_err(serde::de::Error::custom)?,
224 ),
225 "build" => Box::new(
226 serde_json::from_value::<crate::resources::Build>(value)
227 .map_err(serde::de::Error::custom)?,
228 ),
229 "service-account" => Box::new(
230 serde_json::from_value::<crate::resources::ServiceAccount>(value)
231 .map_err(serde::de::Error::custom)?,
232 ),
233 "artifact-registry" => Box::new(
234 serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
235 .map_err(serde::de::Error::custom)?,
236 ),
237 "service_activation" => Box::new(
238 serde_json::from_value::<crate::resources::ServiceActivation>(value)
239 .map_err(serde::de::Error::custom)?,
240 ),
241 "remote-stack-management" => Box::new(
242 serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
243 .map_err(serde::de::Error::custom)?,
244 ),
245 "azure_resource_group" => Box::new(
246 serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
247 .map_err(serde::de::Error::custom)?,
248 ),
249 "azure_storage_account" => Box::new(
250 serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
251 .map_err(serde::de::Error::custom)?,
252 ),
253 "azure_container_apps_environment" => Box::new(
254 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
255 .map_err(serde::de::Error::custom)?,
256 ),
257 "azure_service_bus_namespace" => Box::new(
258 serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
259 .map_err(serde::de::Error::custom)?,
260 ),
261 "experimental/aws-opensearch" => Box::new(
262 serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
263 .map_err(serde::de::Error::custom)?,
264 ),
265 other => {
266 return Err(serde::de::Error::unknown_variant(
267 other,
268 &[
269 "vault",
270 "worker",
271 "daemon",
272 "container",
273 "compute-cluster",
274 "kubernetes-cluster",
275 "storage",
276 "queue",
277 "email",
278 "kv",
279 "postgres",
280 "ai",
281 "network",
282 "build",
283 "service-account",
284 "artifact-registry",
285 "service_activation",
286 "remote-stack-management",
287 "azure_resource_group",
288 "azure_storage_account",
289 "azure_container_apps_environment",
290 "azure_service_bus_namespace",
291 "experimental/aws-opensearch",
292 ],
293 ))
294 }
295 };
296
297 Ok(Resource { inner })
298 }
299}
300
301impl Resource {
302 pub fn new<T: ResourceDefinition>(resource: T) -> Self {
304 Self {
305 inner: Box::new(resource),
306 }
307 }
308
309 pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
311 Self {
312 inner: boxed_resource,
313 }
314 }
315
316 pub fn resource_type(&self) -> ResourceType {
318 self.inner.get_resource_type()
319 }
320
321 pub fn id(&self) -> &str {
323 self.inner.id()
324 }
325
326 pub fn get_dependencies(&self) -> Vec<ResourceRef> {
328 self.inner.get_dependencies()
329 }
330
331 pub fn get_permissions(&self) -> Option<&str> {
333 self.inner.get_permissions()
334 }
335
336 pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
338 self.inner.validate_update(new_config.inner.as_ref())
339 }
340
341 pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
343 self.inner.as_ref()
344 }
345
346 pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
348 self.inner.as_any().downcast_ref::<T>()
349 }
350
351 pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
353 self.inner.as_any_mut().downcast_mut::<T>()
354 }
355}
356
357impl PartialEq for Resource {
358 fn eq(&self, other: &Self) -> bool {
359 self.inner.resource_eq(other.inner.as_ref())
360 }
361}
362
363impl Eq for Resource {}
364
365#[cfg(feature = "openapi")]
387impl PartialSchema for Resource {
388 fn schema() -> RefOr<Schema> {
389 RefOr::T(Schema::Object(
390 ObjectBuilder::new()
391 .schema_type(Type::Object)
392 .property("type", Ref::from_schema_name("ResourceType"))
393 .property("id",
394 ObjectBuilder::new()
395 .schema_type(Type::String)
396 .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."))
397 .build()
398 )
399 .required("type")
400 .required("id")
401 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
402 .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."))
403 .build()
404 ))
405 }
406}
407
408#[cfg(feature = "openapi")]
409impl ToSchema for Resource {
410 fn name() -> std::borrow::Cow<'static, str> {
411 std::borrow::Cow::Borrowed("BaseResource")
412 }
413}
414
415#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
417#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
418#[serde(rename_all = "camelCase")]
419pub struct ResourceRef {
420 #[serde(rename = "type")]
421 pub resource_type: ResourceType,
422 pub id: String,
423}
424
425impl ResourceRef {
426 pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
428 Self {
429 resource_type,
430 id: id.into(),
431 }
432 }
433
434 pub fn resource_type(&self) -> &ResourceType {
436 &self.resource_type
437 }
438
439 pub fn id(&self) -> &str {
441 &self.id
442 }
443}
444
445impl<T: ResourceDefinition> From<&T> for ResourceRef {
446 fn from(resource: &T) -> Self {
447 Self::new(resource.get_resource_type(), resource.id())
448 }
449}
450
451impl From<&Resource> for ResourceRef {
452 fn from(resource: &Resource) -> Self {
453 Self::new(resource.resource_type(), resource.id())
454 }
455}
456
457pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
461 fn get_resource_type(&self) -> ResourceType;
463
464 fn as_any(&self) -> &dyn Any;
466
467 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
469
470 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
472
473 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
475}
476
477impl Clone for Box<dyn ResourceOutputsDefinition> {
479 fn clone(&self) -> Self {
480 self.box_clone()
481 }
482}
483
484#[derive(Debug, Clone)]
487pub struct ResourceOutputs {
488 inner: Box<dyn ResourceOutputsDefinition>,
489}
490
491impl Serialize for ResourceOutputs {
492 fn serialize<S: serde::Serializer>(
493 &self,
494 serializer: S,
495 ) -> std::result::Result<S::Ok, S::Error> {
496 let mut v = self
497 .inner
498 .to_json_value()
499 .map_err(serde::ser::Error::custom)?;
500 v.as_object_mut()
501 .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
502 .insert(
503 "type".into(),
504 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
505 );
506 v.serialize(serializer)
507 }
508}
509
510impl<'de> Deserialize<'de> for ResourceOutputs {
511 fn deserialize<D: serde::Deserializer<'de>>(
512 deserializer: D,
513 ) -> std::result::Result<Self, D::Error> {
514 let mut value = serde_json::Value::deserialize(deserializer)?;
515 let type_tag = value
516 .get("type")
517 .and_then(|v| v.as_str())
518 .ok_or_else(|| serde::de::Error::missing_field("type"))?
519 .to_string();
520
521 if let Some(obj) = value.as_object_mut() {
524 obj.remove("type");
525 }
526
527 let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
528 "vault" => Box::new(
529 serde_json::from_value::<crate::resources::VaultOutputs>(value)
530 .map_err(serde::de::Error::custom)?,
531 ),
532 "worker" => Box::new(
533 serde_json::from_value::<crate::resources::WorkerOutputs>(value)
534 .map_err(serde::de::Error::custom)?,
535 ),
536 "daemon" => Box::new(
537 serde_json::from_value::<crate::resources::DaemonOutputs>(value)
538 .map_err(serde::de::Error::custom)?,
539 ),
540 "container" => Box::new(
541 serde_json::from_value::<crate::resources::ContainerOutputs>(value)
542 .map_err(serde::de::Error::custom)?,
543 ),
544 "compute-cluster" => Box::new(
545 serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
546 .map_err(serde::de::Error::custom)?,
547 ),
548 "storage" => Box::new(
549 serde_json::from_value::<crate::resources::StorageOutputs>(value)
550 .map_err(serde::de::Error::custom)?,
551 ),
552 "queue" => Box::new(
553 serde_json::from_value::<crate::resources::QueueOutputs>(value)
554 .map_err(serde::de::Error::custom)?,
555 ),
556 "email" => Box::new(
557 serde_json::from_value::<crate::resources::EmailOutputs>(value)
558 .map_err(serde::de::Error::custom)?,
559 ),
560 "kv" => Box::new(
561 serde_json::from_value::<crate::resources::KvOutputs>(value)
562 .map_err(serde::de::Error::custom)?,
563 ),
564 "postgres" => Box::new(
565 serde_json::from_value::<crate::resources::PostgresOutputs>(value)
566 .map_err(serde::de::Error::custom)?,
567 ),
568 "ai" => Box::new(
569 serde_json::from_value::<crate::resources::AiOutputs>(value)
570 .map_err(serde::de::Error::custom)?,
571 ),
572 "network" => Box::new(
573 serde_json::from_value::<crate::resources::NetworkOutputs>(value)
574 .map_err(serde::de::Error::custom)?,
575 ),
576 "build" => Box::new(
577 serde_json::from_value::<crate::resources::BuildOutputs>(value)
578 .map_err(serde::de::Error::custom)?,
579 ),
580 "service-account" => Box::new(
581 serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
582 .map_err(serde::de::Error::custom)?,
583 ),
584 "artifact-registry" => Box::new(
585 serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
586 .map_err(serde::de::Error::custom)?,
587 ),
588 "service_activation" => Box::new(
589 serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
590 .map_err(serde::de::Error::custom)?,
591 ),
592 "remote-stack-management" => Box::new(
593 serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
594 .map_err(serde::de::Error::custom)?,
595 ),
596 "kubernetes-cluster" => Box::new(
597 serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
598 .map_err(serde::de::Error::custom)?,
599 ),
600 "azure_resource_group" => Box::new(
601 serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
602 .map_err(serde::de::Error::custom)?,
603 ),
604 "azure_storage_account" => Box::new(
605 serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
606 .map_err(serde::de::Error::custom)?,
607 ),
608 "azure_container_apps_environment" => Box::new(
609 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
610 value,
611 )
612 .map_err(serde::de::Error::custom)?,
613 ),
614 "azure_service_bus_namespace" => Box::new(
615 serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
616 .map_err(serde::de::Error::custom)?,
617 ),
618 "experimental/aws-opensearch" => Box::new(
619 serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
620 .map_err(serde::de::Error::custom)?,
621 ),
622 other => {
623 return Err(serde::de::Error::unknown_variant(
624 other,
625 &[
626 "vault",
627 "worker",
628 "daemon",
629 "container",
630 "compute-cluster",
631 "storage",
632 "queue",
633 "email",
634 "kv",
635 "postgres",
636 "ai",
637 "network",
638 "build",
639 "service-account",
640 "artifact-registry",
641 "service_activation",
642 "remote-stack-management",
643 "kubernetes-cluster",
644 "azure_resource_group",
645 "azure_storage_account",
646 "azure_container_apps_environment",
647 "azure_service_bus_namespace",
648 "experimental/aws-opensearch",
649 ],
650 ))
651 }
652 };
653
654 Ok(ResourceOutputs { inner })
655 }
656}
657
658impl ResourceOutputs {
659 pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
661 Self {
662 inner: Box::new(outputs),
663 }
664 }
665
666 pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
668 self.inner.as_ref()
669 }
670
671 pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
673 self.inner.as_any().downcast_ref::<T>()
674 }
675}
676
677impl PartialEq for ResourceOutputs {
678 fn eq(&self, other: &Self) -> bool {
679 self.inner.outputs_eq(other.inner.as_ref())
680 }
681}
682
683impl Eq for ResourceOutputs {}
684
685#[cfg(feature = "openapi")]
704impl PartialSchema for ResourceOutputs {
705 fn schema() -> RefOr<Schema> {
706 RefOr::T(Schema::Object(
707 ObjectBuilder::new()
708 .schema_type(Type::Object)
709 .property("type", Ref::from_schema_name("ResourceType"))
710 .required("type")
711 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
712 .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."))
713 .build()
714 ))
715 }
716}
717
718#[cfg(feature = "openapi")]
719impl ToSchema for ResourceOutputs {
720 fn name() -> std::borrow::Cow<'static, str> {
721 std::borrow::Cow::Borrowed("BaseResourceOutputs")
722 }
723}
724
725#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
727#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
728#[serde(rename_all = "kebab-case")]
729pub enum ResourceStatus {
730 Pending, Provisioning, ProvisionFailed,
733 Running, Updating,
735 UpdateFailed,
736 Deleting, DeleteFailed,
738 TeardownRequired, Deleted, RefreshFailed, }
742
743impl ResourceStatus {
744 pub fn is_terminal(&self) -> bool {
745 match self {
746 ResourceStatus::TeardownRequired => true,
747 ResourceStatus::Deleted => true,
748 ResourceStatus::ProvisionFailed => true,
749 ResourceStatus::UpdateFailed => true,
750 ResourceStatus::DeleteFailed => true,
751 ResourceStatus::RefreshFailed => true,
752 _ => false, }
754 }
755}
756
757#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
759#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
760#[serde(rename_all = "kebab-case")]
761pub enum ResourceLifecycle {
762 Frozen,
766
767 Live,
771}