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 "key" => Box::new(
202 serde_json::from_value::<crate::resources::Key>(value)
203 .map_err(serde::de::Error::custom)?,
204 ),
205 "queue" => Box::new(
206 serde_json::from_value::<crate::resources::Queue>(value)
207 .map_err(serde::de::Error::custom)?,
208 ),
209 "email" => Box::new(
210 serde_json::from_value::<crate::resources::Email>(value)
211 .map_err(serde::de::Error::custom)?,
212 ),
213 "kv" => Box::new(
214 serde_json::from_value::<crate::resources::Kv>(value)
215 .map_err(serde::de::Error::custom)?,
216 ),
217 "postgres" => Box::new(
218 serde_json::from_value::<crate::resources::Postgres>(value)
219 .map_err(serde::de::Error::custom)?,
220 ),
221 "ai" => Box::new(
222 serde_json::from_value::<crate::resources::Ai>(value)
223 .map_err(serde::de::Error::custom)?,
224 ),
225 "network" => Box::new(
226 serde_json::from_value::<crate::resources::Network>(value)
227 .map_err(serde::de::Error::custom)?,
228 ),
229 "build" => Box::new(
230 serde_json::from_value::<crate::resources::Build>(value)
231 .map_err(serde::de::Error::custom)?,
232 ),
233 "service-account" => Box::new(
234 serde_json::from_value::<crate::resources::ServiceAccount>(value)
235 .map_err(serde::de::Error::custom)?,
236 ),
237 "artifact-registry" => Box::new(
238 serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
239 .map_err(serde::de::Error::custom)?,
240 ),
241 "service_activation" => Box::new(
242 serde_json::from_value::<crate::resources::ServiceActivation>(value)
243 .map_err(serde::de::Error::custom)?,
244 ),
245 "remote-stack-management" => Box::new(
246 serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
247 .map_err(serde::de::Error::custom)?,
248 ),
249 "resource-access" => Box::new(
250 serde_json::from_value::<crate::resources::RemoteBindings>(value)
251 .map_err(serde::de::Error::custom)?,
252 ),
253 "azure_resource_group" => Box::new(
254 serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
255 .map_err(serde::de::Error::custom)?,
256 ),
257 "azure_storage_account" => Box::new(
258 serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
259 .map_err(serde::de::Error::custom)?,
260 ),
261 "azure_container_apps_environment" => Box::new(
262 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
263 .map_err(serde::de::Error::custom)?,
264 ),
265 "azure_service_bus_namespace" => Box::new(
266 serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
267 .map_err(serde::de::Error::custom)?,
268 ),
269 "experimental/aws-opensearch" => Box::new(
270 serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
271 .map_err(serde::de::Error::custom)?,
272 ),
273 other => {
274 return Err(serde::de::Error::unknown_variant(
275 other,
276 &[
277 "vault",
278 "worker",
279 "daemon",
280 "container",
281 "compute-cluster",
282 "kubernetes-cluster",
283 "storage",
284 "key",
285 "queue",
286 "email",
287 "kv",
288 "postgres",
289 "ai",
290 "network",
291 "build",
292 "service-account",
293 "artifact-registry",
294 "service_activation",
295 "remote-stack-management",
296 "resource-access",
297 "azure_resource_group",
298 "azure_storage_account",
299 "azure_container_apps_environment",
300 "azure_service_bus_namespace",
301 "experimental/aws-opensearch",
302 ],
303 ))
304 }
305 };
306
307 Ok(Resource { inner })
308 }
309}
310
311impl Resource {
312 pub fn new<T: ResourceDefinition>(resource: T) -> Self {
314 Self {
315 inner: Box::new(resource),
316 }
317 }
318
319 pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
321 Self {
322 inner: boxed_resource,
323 }
324 }
325
326 pub fn resource_type(&self) -> ResourceType {
328 self.inner.get_resource_type()
329 }
330
331 pub fn id(&self) -> &str {
333 self.inner.id()
334 }
335
336 pub fn get_dependencies(&self) -> Vec<ResourceRef> {
338 self.inner.get_dependencies()
339 }
340
341 pub fn get_permissions(&self) -> Option<&str> {
343 self.inner.get_permissions()
344 }
345
346 pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
348 self.inner.validate_update(new_config.inner.as_ref())
349 }
350
351 pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
353 self.inner.as_ref()
354 }
355
356 pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
358 self.inner.as_any().downcast_ref::<T>()
359 }
360
361 pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
363 self.inner.as_any_mut().downcast_mut::<T>()
364 }
365}
366
367impl PartialEq for Resource {
368 fn eq(&self, other: &Self) -> bool {
369 self.inner.resource_eq(other.inner.as_ref())
370 }
371}
372
373impl Eq for Resource {}
374
375#[cfg(feature = "openapi")]
397impl PartialSchema for Resource {
398 fn schema() -> RefOr<Schema> {
399 RefOr::T(Schema::Object(
400 ObjectBuilder::new()
401 .schema_type(Type::Object)
402 .property("type", Ref::from_schema_name("ResourceType"))
403 .property("id",
404 ObjectBuilder::new()
405 .schema_type(Type::String)
406 .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."))
407 .build()
408 )
409 .required("type")
410 .required("id")
411 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
412 .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."))
413 .build()
414 ))
415 }
416}
417
418#[cfg(feature = "openapi")]
419impl ToSchema for Resource {
420 fn name() -> std::borrow::Cow<'static, str> {
421 std::borrow::Cow::Borrowed("BaseResource")
422 }
423}
424
425#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
427#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
428#[serde(rename_all = "camelCase")]
429pub struct ResourceRef {
430 #[serde(rename = "type")]
431 pub resource_type: ResourceType,
432 pub id: String,
433}
434
435impl ResourceRef {
436 pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
438 Self {
439 resource_type,
440 id: id.into(),
441 }
442 }
443
444 pub fn resource_type(&self) -> &ResourceType {
446 &self.resource_type
447 }
448
449 pub fn id(&self) -> &str {
451 &self.id
452 }
453}
454
455impl<T: ResourceDefinition> From<&T> for ResourceRef {
456 fn from(resource: &T) -> Self {
457 Self::new(resource.get_resource_type(), resource.id())
458 }
459}
460
461impl From<&Resource> for ResourceRef {
462 fn from(resource: &Resource) -> Self {
463 Self::new(resource.resource_type(), resource.id())
464 }
465}
466
467pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
471 fn get_resource_type(&self) -> ResourceType;
473
474 fn as_any(&self) -> &dyn Any;
476
477 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
479
480 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
482
483 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
485}
486
487impl Clone for Box<dyn ResourceOutputsDefinition> {
489 fn clone(&self) -> Self {
490 self.box_clone()
491 }
492}
493
494#[derive(Debug, Clone)]
497pub struct ResourceOutputs {
498 inner: Box<dyn ResourceOutputsDefinition>,
499}
500
501impl Serialize for ResourceOutputs {
502 fn serialize<S: serde::Serializer>(
503 &self,
504 serializer: S,
505 ) -> std::result::Result<S::Ok, S::Error> {
506 let mut v = self
507 .inner
508 .to_json_value()
509 .map_err(serde::ser::Error::custom)?;
510 v.as_object_mut()
511 .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
512 .insert(
513 "type".into(),
514 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
515 );
516 v.serialize(serializer)
517 }
518}
519
520impl<'de> Deserialize<'de> for ResourceOutputs {
521 fn deserialize<D: serde::Deserializer<'de>>(
522 deserializer: D,
523 ) -> std::result::Result<Self, D::Error> {
524 let mut value = serde_json::Value::deserialize(deserializer)?;
525 let type_tag = value
526 .get("type")
527 .and_then(|v| v.as_str())
528 .ok_or_else(|| serde::de::Error::missing_field("type"))?
529 .to_string();
530
531 if let Some(obj) = value.as_object_mut() {
534 obj.remove("type");
535 }
536
537 let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
538 "vault" => Box::new(
539 serde_json::from_value::<crate::resources::VaultOutputs>(value)
540 .map_err(serde::de::Error::custom)?,
541 ),
542 "worker" => Box::new(
543 serde_json::from_value::<crate::resources::WorkerOutputs>(value)
544 .map_err(serde::de::Error::custom)?,
545 ),
546 "daemon" => Box::new(
547 serde_json::from_value::<crate::resources::DaemonOutputs>(value)
548 .map_err(serde::de::Error::custom)?,
549 ),
550 "container" => Box::new(
551 serde_json::from_value::<crate::resources::ContainerOutputs>(value)
552 .map_err(serde::de::Error::custom)?,
553 ),
554 "compute-cluster" => Box::new(
555 serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
556 .map_err(serde::de::Error::custom)?,
557 ),
558 "storage" => Box::new(
559 serde_json::from_value::<crate::resources::StorageOutputs>(value)
560 .map_err(serde::de::Error::custom)?,
561 ),
562 "key" => Box::new(
563 serde_json::from_value::<crate::resources::KeyOutputs>(value)
564 .map_err(serde::de::Error::custom)?,
565 ),
566 "queue" => Box::new(
567 serde_json::from_value::<crate::resources::QueueOutputs>(value)
568 .map_err(serde::de::Error::custom)?,
569 ),
570 "email" => Box::new(
571 serde_json::from_value::<crate::resources::EmailOutputs>(value)
572 .map_err(serde::de::Error::custom)?,
573 ),
574 "kv" => Box::new(
575 serde_json::from_value::<crate::resources::KvOutputs>(value)
576 .map_err(serde::de::Error::custom)?,
577 ),
578 "postgres" => Box::new(
579 serde_json::from_value::<crate::resources::PostgresOutputs>(value)
580 .map_err(serde::de::Error::custom)?,
581 ),
582 "ai" => Box::new(
583 serde_json::from_value::<crate::resources::AiOutputs>(value)
584 .map_err(serde::de::Error::custom)?,
585 ),
586 "network" => Box::new(
587 serde_json::from_value::<crate::resources::NetworkOutputs>(value)
588 .map_err(serde::de::Error::custom)?,
589 ),
590 "build" => Box::new(
591 serde_json::from_value::<crate::resources::BuildOutputs>(value)
592 .map_err(serde::de::Error::custom)?,
593 ),
594 "service-account" => Box::new(
595 serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
596 .map_err(serde::de::Error::custom)?,
597 ),
598 "artifact-registry" => Box::new(
599 serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
600 .map_err(serde::de::Error::custom)?,
601 ),
602 "service_activation" => Box::new(
603 serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
604 .map_err(serde::de::Error::custom)?,
605 ),
606 "remote-stack-management" => Box::new(
607 serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
608 .map_err(serde::de::Error::custom)?,
609 ),
610 "resource-access" => Box::new(
611 serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
612 .map_err(serde::de::Error::custom)?,
613 ),
614 "kubernetes-cluster" => Box::new(
615 serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
616 .map_err(serde::de::Error::custom)?,
617 ),
618 "azure_resource_group" => Box::new(
619 serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
620 .map_err(serde::de::Error::custom)?,
621 ),
622 "azure_storage_account" => Box::new(
623 serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
624 .map_err(serde::de::Error::custom)?,
625 ),
626 "azure_container_apps_environment" => Box::new(
627 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
628 value,
629 )
630 .map_err(serde::de::Error::custom)?,
631 ),
632 "azure_service_bus_namespace" => Box::new(
633 serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
634 .map_err(serde::de::Error::custom)?,
635 ),
636 "experimental/aws-opensearch" => Box::new(
637 serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
638 .map_err(serde::de::Error::custom)?,
639 ),
640 other => {
641 return Err(serde::de::Error::unknown_variant(
642 other,
643 &[
644 "vault",
645 "worker",
646 "daemon",
647 "container",
648 "compute-cluster",
649 "storage",
650 "key",
651 "queue",
652 "email",
653 "kv",
654 "postgres",
655 "ai",
656 "network",
657 "build",
658 "service-account",
659 "artifact-registry",
660 "service_activation",
661 "remote-stack-management",
662 "resource-access",
663 "kubernetes-cluster",
664 "azure_resource_group",
665 "azure_storage_account",
666 "azure_container_apps_environment",
667 "azure_service_bus_namespace",
668 "experimental/aws-opensearch",
669 ],
670 ))
671 }
672 };
673
674 Ok(ResourceOutputs { inner })
675 }
676}
677
678impl ResourceOutputs {
679 pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
681 Self {
682 inner: Box::new(outputs),
683 }
684 }
685
686 pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
688 self.inner.as_ref()
689 }
690
691 pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
693 self.inner.as_any().downcast_ref::<T>()
694 }
695}
696
697impl PartialEq for ResourceOutputs {
698 fn eq(&self, other: &Self) -> bool {
699 self.inner.outputs_eq(other.inner.as_ref())
700 }
701}
702
703impl Eq for ResourceOutputs {}
704
705#[cfg(feature = "openapi")]
724impl PartialSchema for ResourceOutputs {
725 fn schema() -> RefOr<Schema> {
726 RefOr::T(Schema::Object(
727 ObjectBuilder::new()
728 .schema_type(Type::Object)
729 .property("type", Ref::from_schema_name("ResourceType"))
730 .required("type")
731 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
732 .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."))
733 .build()
734 ))
735 }
736}
737
738#[cfg(feature = "openapi")]
739impl ToSchema for ResourceOutputs {
740 fn name() -> std::borrow::Cow<'static, str> {
741 std::borrow::Cow::Borrowed("BaseResourceOutputs")
742 }
743}
744
745#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
747#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
748#[serde(rename_all = "kebab-case")]
749pub enum ResourceStatus {
750 Pending, Provisioning, ProvisionFailed,
753 Running, Updating,
755 UpdateFailed,
756 Deleting, DeleteFailed,
758 TeardownRequired, Deleted, RefreshFailed, }
762
763impl ResourceStatus {
764 pub fn is_terminal(&self) -> bool {
765 match self {
766 ResourceStatus::TeardownRequired => true,
767 ResourceStatus::Deleted => true,
768 ResourceStatus::ProvisionFailed => true,
769 ResourceStatus::UpdateFailed => true,
770 ResourceStatus::DeleteFailed => true,
771 ResourceStatus::RefreshFailed => true,
772 _ => false, }
774 }
775}
776
777#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
779#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
780#[serde(rename_all = "kebab-case")]
781pub enum ResourceLifecycle {
782 Frozen,
786
787 Live,
791}