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 replace_after_failed_create_is_safe(&self) -> bool {
119 true
120 }
121
122 fn as_any(&self) -> &dyn Any;
124
125 fn as_any_mut(&mut self) -> &mut dyn Any;
127
128 fn box_clone(&self) -> Box<dyn ResourceDefinition>;
130
131 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool;
133
134 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
136}
137
138impl Clone for Box<dyn ResourceDefinition> {
140 fn clone(&self) -> Self {
141 self.box_clone()
142 }
143}
144
145#[derive(Debug, Clone)]
146pub struct Resource {
147 inner: Box<dyn ResourceDefinition>,
148}
149
150impl Serialize for Resource {
151 fn serialize<S: serde::Serializer>(
152 &self,
153 serializer: S,
154 ) -> std::result::Result<S::Ok, S::Error> {
155 let mut v = self
156 .inner
157 .to_json_value()
158 .map_err(serde::ser::Error::custom)?;
159 v.as_object_mut()
160 .ok_or_else(|| serde::ser::Error::custom("resource must serialize as object"))?
161 .insert(
162 "type".into(),
163 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
164 );
165 v.serialize(serializer)
166 }
167}
168
169impl<'de> Deserialize<'de> for Resource {
170 fn deserialize<D: serde::Deserializer<'de>>(
171 deserializer: D,
172 ) -> std::result::Result<Self, D::Error> {
173 let mut value = serde_json::Value::deserialize(deserializer)?;
174 let type_tag = value
175 .get("type")
176 .and_then(|v| v.as_str())
177 .ok_or_else(|| serde::de::Error::missing_field("type"))?
178 .to_string();
179
180 if let Some(obj) = value.as_object_mut() {
183 obj.remove("type");
184 }
185
186 let inner: Box<dyn ResourceDefinition> = match type_tag.as_str() {
187 "vault" => Box::new(
188 serde_json::from_value::<crate::resources::Vault>(value)
189 .map_err(serde::de::Error::custom)?,
190 ),
191 "worker" => Box::new(
192 serde_json::from_value::<crate::resources::Worker>(value)
193 .map_err(serde::de::Error::custom)?,
194 ),
195 "daemon" => Box::new(
196 serde_json::from_value::<crate::resources::Daemon>(value)
197 .map_err(serde::de::Error::custom)?,
198 ),
199 "container" => Box::new(
200 serde_json::from_value::<crate::resources::Container>(value)
201 .map_err(serde::de::Error::custom)?,
202 ),
203 "compute-cluster" => Box::new(
204 serde_json::from_value::<crate::resources::ComputeCluster>(value)
205 .map_err(serde::de::Error::custom)?,
206 ),
207 "kubernetes-cluster" => Box::new(
208 serde_json::from_value::<crate::resources::KubernetesCluster>(value)
209 .map_err(serde::de::Error::custom)?,
210 ),
211 "storage" => Box::new(
212 serde_json::from_value::<crate::resources::Storage>(value)
213 .map_err(serde::de::Error::custom)?,
214 ),
215 "key" => Box::new(
216 serde_json::from_value::<crate::resources::Key>(value)
217 .map_err(serde::de::Error::custom)?,
218 ),
219 "queue" => Box::new(
220 serde_json::from_value::<crate::resources::Queue>(value)
221 .map_err(serde::de::Error::custom)?,
222 ),
223 "sandbox" => Box::new(
224 serde_json::from_value::<crate::resources::Sandbox>(value)
225 .map_err(serde::de::Error::custom)?,
226 ),
227 "email" => Box::new(
228 serde_json::from_value::<crate::resources::Email>(value)
229 .map_err(serde::de::Error::custom)?,
230 ),
231 "kv" => Box::new(
232 serde_json::from_value::<crate::resources::Kv>(value)
233 .map_err(serde::de::Error::custom)?,
234 ),
235 "postgres" => Box::new(
236 serde_json::from_value::<crate::resources::Postgres>(value)
237 .map_err(serde::de::Error::custom)?,
238 ),
239 "ai" => Box::new(
240 serde_json::from_value::<crate::resources::Ai>(value)
241 .map_err(serde::de::Error::custom)?,
242 ),
243 "network" => Box::new(
244 serde_json::from_value::<crate::resources::Network>(value)
245 .map_err(serde::de::Error::custom)?,
246 ),
247 "build" => Box::new(
248 serde_json::from_value::<crate::resources::Build>(value)
249 .map_err(serde::de::Error::custom)?,
250 ),
251 "service-account" => Box::new(
252 serde_json::from_value::<crate::resources::ServiceAccount>(value)
253 .map_err(serde::de::Error::custom)?,
254 ),
255 "artifact-registry" => Box::new(
256 serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
257 .map_err(serde::de::Error::custom)?,
258 ),
259 "service_activation" => Box::new(
260 serde_json::from_value::<crate::resources::ServiceActivation>(value)
261 .map_err(serde::de::Error::custom)?,
262 ),
263 "remote-stack-management" => Box::new(
264 serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
265 .map_err(serde::de::Error::custom)?,
266 ),
267 "resource-access" => Box::new(
268 serde_json::from_value::<crate::resources::RemoteBindings>(value)
269 .map_err(serde::de::Error::custom)?,
270 ),
271 "azure_resource_group" => Box::new(
272 serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
273 .map_err(serde::de::Error::custom)?,
274 ),
275 "gcp_agent_platform_engine" => Box::new(
276 serde_json::from_value::<crate::resources::GcpAgentPlatformEngine>(value)
277 .map_err(serde::de::Error::custom)?,
278 ),
279 "azure_storage_account" => Box::new(
280 serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
281 .map_err(serde::de::Error::custom)?,
282 ),
283 "azure_container_apps_environment" => Box::new(
284 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
285 .map_err(serde::de::Error::custom)?,
286 ),
287 "azure_service_bus_namespace" => Box::new(
288 serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
289 .map_err(serde::de::Error::custom)?,
290 ),
291 "experimental/aws-opensearch" => Box::new(
292 serde_json::from_value::<crate::resources::AwsOpenSearch>(value)
293 .map_err(serde::de::Error::custom)?,
294 ),
295 other => {
296 return Err(serde::de::Error::unknown_variant(
297 other,
298 &[
299 "vault",
300 "worker",
301 "daemon",
302 "container",
303 "compute-cluster",
304 "kubernetes-cluster",
305 "storage",
306 "key",
307 "queue",
308 "sandbox",
309 "email",
310 "kv",
311 "postgres",
312 "ai",
313 "network",
314 "build",
315 "service-account",
316 "artifact-registry",
317 "service_activation",
318 "remote-stack-management",
319 "resource-access",
320 "azure_resource_group",
321 "gcp_agent_platform_engine",
322 "azure_storage_account",
323 "azure_container_apps_environment",
324 "azure_service_bus_namespace",
325 "experimental/aws-opensearch",
326 ],
327 ))
328 }
329 };
330
331 Ok(Resource { inner })
332 }
333}
334
335impl Resource {
336 pub fn new<T: ResourceDefinition>(resource: T) -> Self {
338 Self {
339 inner: Box::new(resource),
340 }
341 }
342
343 pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
345 Self {
346 inner: boxed_resource,
347 }
348 }
349
350 pub fn resource_type(&self) -> ResourceType {
352 self.inner.get_resource_type()
353 }
354
355 pub fn id(&self) -> &str {
357 self.inner.id()
358 }
359
360 pub fn get_dependencies(&self) -> Vec<ResourceRef> {
362 self.inner.get_dependencies()
363 }
364
365 pub fn get_permissions(&self) -> Option<&str> {
367 self.inner.get_permissions()
368 }
369
370 pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
372 self.inner.validate_update(new_config.inner.as_ref())
373 }
374
375 pub fn replace_after_failed_create_is_safe(&self) -> bool {
378 self.inner.replace_after_failed_create_is_safe()
379 }
380
381 pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
383 self.inner.as_ref()
384 }
385
386 pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
388 self.inner.as_any().downcast_ref::<T>()
389 }
390
391 pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
393 self.inner.as_any_mut().downcast_mut::<T>()
394 }
395}
396
397impl PartialEq for Resource {
398 fn eq(&self, other: &Self) -> bool {
399 self.inner.resource_eq(other.inner.as_ref())
400 }
401}
402
403impl Eq for Resource {}
404
405#[cfg(feature = "openapi")]
427impl PartialSchema for Resource {
428 fn schema() -> RefOr<Schema> {
429 RefOr::T(Schema::Object(
430 ObjectBuilder::new()
431 .schema_type(Type::Object)
432 .property("type", Ref::from_schema_name("ResourceType"))
433 .property("id",
434 ObjectBuilder::new()
435 .schema_type(Type::String)
436 .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."))
437 .build()
438 )
439 .required("type")
440 .required("id")
441 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
442 .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."))
443 .build()
444 ))
445 }
446}
447
448#[cfg(feature = "openapi")]
449impl ToSchema for Resource {
450 fn name() -> std::borrow::Cow<'static, str> {
451 std::borrow::Cow::Borrowed("BaseResource")
452 }
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
457#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
458#[serde(rename_all = "camelCase")]
459pub struct ResourceRef {
460 #[serde(rename = "type")]
461 pub resource_type: ResourceType,
462 pub id: String,
463}
464
465impl ResourceRef {
466 pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
468 Self {
469 resource_type,
470 id: id.into(),
471 }
472 }
473
474 pub fn resource_type(&self) -> &ResourceType {
476 &self.resource_type
477 }
478
479 pub fn id(&self) -> &str {
481 &self.id
482 }
483}
484
485impl<T: ResourceDefinition> From<&T> for ResourceRef {
486 fn from(resource: &T) -> Self {
487 Self::new(resource.get_resource_type(), resource.id())
488 }
489}
490
491impl From<&Resource> for ResourceRef {
492 fn from(resource: &Resource) -> Self {
493 Self::new(resource.resource_type(), resource.id())
494 }
495}
496
497pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
501 fn get_resource_type(&self) -> ResourceType;
503
504 fn as_any(&self) -> &dyn Any;
506
507 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
509
510 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
512
513 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
515}
516
517impl Clone for Box<dyn ResourceOutputsDefinition> {
519 fn clone(&self) -> Self {
520 self.box_clone()
521 }
522}
523
524#[derive(Debug, Clone)]
527pub struct ResourceOutputs {
528 inner: Box<dyn ResourceOutputsDefinition>,
529}
530
531impl Serialize for ResourceOutputs {
532 fn serialize<S: serde::Serializer>(
533 &self,
534 serializer: S,
535 ) -> std::result::Result<S::Ok, S::Error> {
536 let mut v = self
537 .inner
538 .to_json_value()
539 .map_err(serde::ser::Error::custom)?;
540 v.as_object_mut()
541 .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
542 .insert(
543 "type".into(),
544 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
545 );
546 v.serialize(serializer)
547 }
548}
549
550impl<'de> Deserialize<'de> for ResourceOutputs {
551 fn deserialize<D: serde::Deserializer<'de>>(
552 deserializer: D,
553 ) -> std::result::Result<Self, D::Error> {
554 let mut value = serde_json::Value::deserialize(deserializer)?;
555 let type_tag = value
556 .get("type")
557 .and_then(|v| v.as_str())
558 .ok_or_else(|| serde::de::Error::missing_field("type"))?
559 .to_string();
560
561 if let Some(obj) = value.as_object_mut() {
564 obj.remove("type");
565 }
566
567 let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
568 "vault" => Box::new(
569 serde_json::from_value::<crate::resources::VaultOutputs>(value)
570 .map_err(serde::de::Error::custom)?,
571 ),
572 "worker" => Box::new(
573 serde_json::from_value::<crate::resources::WorkerOutputs>(value)
574 .map_err(serde::de::Error::custom)?,
575 ),
576 "daemon" => Box::new(
577 serde_json::from_value::<crate::resources::DaemonOutputs>(value)
578 .map_err(serde::de::Error::custom)?,
579 ),
580 "container" => Box::new(
581 serde_json::from_value::<crate::resources::ContainerOutputs>(value)
582 .map_err(serde::de::Error::custom)?,
583 ),
584 "compute-cluster" => Box::new(
585 serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
586 .map_err(serde::de::Error::custom)?,
587 ),
588 "storage" => Box::new(
589 serde_json::from_value::<crate::resources::StorageOutputs>(value)
590 .map_err(serde::de::Error::custom)?,
591 ),
592 "key" => Box::new(
593 serde_json::from_value::<crate::resources::KeyOutputs>(value)
594 .map_err(serde::de::Error::custom)?,
595 ),
596 "queue" => Box::new(
597 serde_json::from_value::<crate::resources::QueueOutputs>(value)
598 .map_err(serde::de::Error::custom)?,
599 ),
600 "sandbox" => Box::new(
601 serde_json::from_value::<crate::resources::SandboxOutputs>(value)
602 .map_err(serde::de::Error::custom)?,
603 ),
604 "email" => Box::new(
605 serde_json::from_value::<crate::resources::EmailOutputs>(value)
606 .map_err(serde::de::Error::custom)?,
607 ),
608 "kv" => Box::new(
609 serde_json::from_value::<crate::resources::KvOutputs>(value)
610 .map_err(serde::de::Error::custom)?,
611 ),
612 "postgres" => Box::new(
613 serde_json::from_value::<crate::resources::PostgresOutputs>(value)
614 .map_err(serde::de::Error::custom)?,
615 ),
616 "ai" => Box::new(
617 serde_json::from_value::<crate::resources::AiOutputs>(value)
618 .map_err(serde::de::Error::custom)?,
619 ),
620 "network" => Box::new(
621 serde_json::from_value::<crate::resources::NetworkOutputs>(value)
622 .map_err(serde::de::Error::custom)?,
623 ),
624 "build" => Box::new(
625 serde_json::from_value::<crate::resources::BuildOutputs>(value)
626 .map_err(serde::de::Error::custom)?,
627 ),
628 "service-account" => Box::new(
629 serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
630 .map_err(serde::de::Error::custom)?,
631 ),
632 "artifact-registry" => Box::new(
633 serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
634 .map_err(serde::de::Error::custom)?,
635 ),
636 "service_activation" => Box::new(
637 serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
638 .map_err(serde::de::Error::custom)?,
639 ),
640 "remote-stack-management" => Box::new(
641 serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
642 .map_err(serde::de::Error::custom)?,
643 ),
644 "resource-access" => Box::new(
645 serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
646 .map_err(serde::de::Error::custom)?,
647 ),
648 "kubernetes-cluster" => Box::new(
649 serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
650 .map_err(serde::de::Error::custom)?,
651 ),
652 "azure_resource_group" => Box::new(
653 serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
654 .map_err(serde::de::Error::custom)?,
655 ),
656 "azure_storage_account" => Box::new(
657 serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
658 .map_err(serde::de::Error::custom)?,
659 ),
660 "azure_container_apps_environment" => Box::new(
661 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
662 value,
663 )
664 .map_err(serde::de::Error::custom)?,
665 ),
666 "azure_service_bus_namespace" => Box::new(
667 serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
668 .map_err(serde::de::Error::custom)?,
669 ),
670 "experimental/aws-opensearch" => Box::new(
671 serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
672 .map_err(serde::de::Error::custom)?,
673 ),
674 other => {
675 return Err(serde::de::Error::unknown_variant(
676 other,
677 &[
678 "vault",
679 "worker",
680 "daemon",
681 "container",
682 "compute-cluster",
683 "storage",
684 "key",
685 "queue",
686 "sandbox",
687 "email",
688 "kv",
689 "postgres",
690 "ai",
691 "network",
692 "build",
693 "service-account",
694 "artifact-registry",
695 "service_activation",
696 "remote-stack-management",
697 "resource-access",
698 "kubernetes-cluster",
699 "azure_resource_group",
700 "azure_storage_account",
701 "azure_container_apps_environment",
702 "azure_service_bus_namespace",
703 "experimental/aws-opensearch",
704 ],
705 ))
706 }
707 };
708
709 Ok(ResourceOutputs { inner })
710 }
711}
712
713impl ResourceOutputs {
714 pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
716 Self {
717 inner: Box::new(outputs),
718 }
719 }
720
721 pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
723 self.inner.as_ref()
724 }
725
726 pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
728 self.inner.as_any().downcast_ref::<T>()
729 }
730}
731
732impl PartialEq for ResourceOutputs {
733 fn eq(&self, other: &Self) -> bool {
734 self.inner.outputs_eq(other.inner.as_ref())
735 }
736}
737
738impl Eq for ResourceOutputs {}
739
740#[cfg(feature = "openapi")]
759impl PartialSchema for ResourceOutputs {
760 fn schema() -> RefOr<Schema> {
761 RefOr::T(Schema::Object(
762 ObjectBuilder::new()
763 .schema_type(Type::Object)
764 .property("type", Ref::from_schema_name("ResourceType"))
765 .required("type")
766 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
767 .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."))
768 .build()
769 ))
770 }
771}
772
773#[cfg(feature = "openapi")]
774impl ToSchema for ResourceOutputs {
775 fn name() -> std::borrow::Cow<'static, str> {
776 std::borrow::Cow::Borrowed("BaseResourceOutputs")
777 }
778}
779
780#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
782#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
783#[serde(rename_all = "kebab-case")]
784pub enum ResourceStatus {
785 Pending, Provisioning, ProvisionFailed,
788 Running, Updating,
790 UpdateFailed,
791 Deleting, DeleteFailed,
793 TeardownRequired, Deleted, RefreshFailed, }
797
798impl ResourceStatus {
799 pub fn is_terminal(&self) -> bool {
800 match self {
801 ResourceStatus::TeardownRequired => true,
802 ResourceStatus::Deleted => true,
803 ResourceStatus::ProvisionFailed => true,
804 ResourceStatus::UpdateFailed => true,
805 ResourceStatus::DeleteFailed => true,
806 ResourceStatus::RefreshFailed => true,
807 _ => false, }
809 }
810}
811
812#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
814#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
815#[serde(rename_all = "kebab-case")]
816pub enum ResourceLifecycle {
817 Frozen,
821
822 Live,
826}