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 {
504 fn is_available(&self) -> bool {
507 true
508 }
509
510 fn get_resource_type(&self) -> ResourceType;
512
513 fn as_any(&self) -> &dyn Any;
515
516 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
518
519 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
521
522 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
524}
525
526impl Clone for Box<dyn ResourceOutputsDefinition> {
528 fn clone(&self) -> Self {
529 self.box_clone()
530 }
531}
532
533#[derive(Debug, Clone)]
536pub struct ResourceOutputs {
537 inner: Box<dyn ResourceOutputsDefinition>,
538}
539
540impl Serialize for ResourceOutputs {
541 fn serialize<S: serde::Serializer>(
542 &self,
543 serializer: S,
544 ) -> std::result::Result<S::Ok, S::Error> {
545 let mut v = self
546 .inner
547 .to_json_value()
548 .map_err(serde::ser::Error::custom)?;
549 v.as_object_mut()
550 .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
551 .insert(
552 "type".into(),
553 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
554 );
555 v.serialize(serializer)
556 }
557}
558
559impl<'de> Deserialize<'de> for ResourceOutputs {
560 fn deserialize<D: serde::Deserializer<'de>>(
561 deserializer: D,
562 ) -> std::result::Result<Self, D::Error> {
563 let mut value = serde_json::Value::deserialize(deserializer)?;
564 let type_tag = value
565 .get("type")
566 .and_then(|v| v.as_str())
567 .ok_or_else(|| serde::de::Error::missing_field("type"))?
568 .to_string();
569
570 if let Some(obj) = value.as_object_mut() {
573 obj.remove("type");
574 }
575
576 let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
577 "vault" => Box::new(
578 serde_json::from_value::<crate::resources::VaultOutputs>(value)
579 .map_err(serde::de::Error::custom)?,
580 ),
581 "worker" => Box::new(
582 serde_json::from_value::<crate::resources::WorkerOutputs>(value)
583 .map_err(serde::de::Error::custom)?,
584 ),
585 "daemon" => Box::new(
586 serde_json::from_value::<crate::resources::DaemonOutputs>(value)
587 .map_err(serde::de::Error::custom)?,
588 ),
589 "container" => Box::new(
590 serde_json::from_value::<crate::resources::ContainerOutputs>(value)
591 .map_err(serde::de::Error::custom)?,
592 ),
593 "compute-cluster" => Box::new(
594 serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
595 .map_err(serde::de::Error::custom)?,
596 ),
597 "storage" => Box::new(
598 serde_json::from_value::<crate::resources::StorageOutputs>(value)
599 .map_err(serde::de::Error::custom)?,
600 ),
601 "key" => Box::new(
602 serde_json::from_value::<crate::resources::KeyOutputs>(value)
603 .map_err(serde::de::Error::custom)?,
604 ),
605 "queue" => Box::new(
606 serde_json::from_value::<crate::resources::QueueOutputs>(value)
607 .map_err(serde::de::Error::custom)?,
608 ),
609 "sandbox" => Box::new(
610 serde_json::from_value::<crate::resources::SandboxOutputs>(value)
611 .map_err(serde::de::Error::custom)?,
612 ),
613 "email" => Box::new(
614 serde_json::from_value::<crate::resources::EmailOutputs>(value)
615 .map_err(serde::de::Error::custom)?,
616 ),
617 "kv" => Box::new(
618 serde_json::from_value::<crate::resources::KvOutputs>(value)
619 .map_err(serde::de::Error::custom)?,
620 ),
621 "postgres" => Box::new(
622 serde_json::from_value::<crate::resources::PostgresOutputs>(value)
623 .map_err(serde::de::Error::custom)?,
624 ),
625 "ai" => Box::new(
626 serde_json::from_value::<crate::resources::AiOutputs>(value)
627 .map_err(serde::de::Error::custom)?,
628 ),
629 "network" => Box::new(
630 serde_json::from_value::<crate::resources::NetworkOutputs>(value)
631 .map_err(serde::de::Error::custom)?,
632 ),
633 "build" => Box::new(
634 serde_json::from_value::<crate::resources::BuildOutputs>(value)
635 .map_err(serde::de::Error::custom)?,
636 ),
637 "service-account" => Box::new(
638 serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
639 .map_err(serde::de::Error::custom)?,
640 ),
641 "artifact-registry" => Box::new(
642 serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
643 .map_err(serde::de::Error::custom)?,
644 ),
645 "service_activation" => Box::new(
646 serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
647 .map_err(serde::de::Error::custom)?,
648 ),
649 "remote-stack-management" => Box::new(
650 serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
651 .map_err(serde::de::Error::custom)?,
652 ),
653 "resource-access" => Box::new(
654 serde_json::from_value::<crate::resources::RemoteBindingsOutputs>(value)
655 .map_err(serde::de::Error::custom)?,
656 ),
657 "kubernetes-cluster" => Box::new(
658 serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
659 .map_err(serde::de::Error::custom)?,
660 ),
661 "azure_resource_group" => Box::new(
662 serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
663 .map_err(serde::de::Error::custom)?,
664 ),
665 "azure_storage_account" => Box::new(
666 serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
667 .map_err(serde::de::Error::custom)?,
668 ),
669 "azure_container_apps_environment" => Box::new(
670 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
671 value,
672 )
673 .map_err(serde::de::Error::custom)?,
674 ),
675 "azure_service_bus_namespace" => Box::new(
676 serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
677 .map_err(serde::de::Error::custom)?,
678 ),
679 "experimental/aws-opensearch" => Box::new(
680 serde_json::from_value::<crate::resources::AwsOpenSearchOutputs>(value)
681 .map_err(serde::de::Error::custom)?,
682 ),
683 other => {
684 return Err(serde::de::Error::unknown_variant(
685 other,
686 &[
687 "vault",
688 "worker",
689 "daemon",
690 "container",
691 "compute-cluster",
692 "storage",
693 "key",
694 "queue",
695 "sandbox",
696 "email",
697 "kv",
698 "postgres",
699 "ai",
700 "network",
701 "build",
702 "service-account",
703 "artifact-registry",
704 "service_activation",
705 "remote-stack-management",
706 "resource-access",
707 "kubernetes-cluster",
708 "azure_resource_group",
709 "azure_storage_account",
710 "azure_container_apps_environment",
711 "azure_service_bus_namespace",
712 "experimental/aws-opensearch",
713 ],
714 ))
715 }
716 };
717
718 Ok(ResourceOutputs { inner })
719 }
720}
721
722impl ResourceOutputs {
723 pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
725 Self {
726 inner: Box::new(outputs),
727 }
728 }
729
730 pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
732 self.inner.as_ref()
733 }
734
735 pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
737 self.inner.as_any().downcast_ref::<T>()
738 }
739}
740
741impl PartialEq for ResourceOutputs {
742 fn eq(&self, other: &Self) -> bool {
743 self.inner.outputs_eq(other.inner.as_ref())
744 }
745}
746
747impl Eq for ResourceOutputs {}
748
749#[cfg(feature = "openapi")]
768impl PartialSchema for ResourceOutputs {
769 fn schema() -> RefOr<Schema> {
770 RefOr::T(Schema::Object(
771 ObjectBuilder::new()
772 .schema_type(Type::Object)
773 .property("type", Ref::from_schema_name("ResourceType"))
774 .required("type")
775 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
776 .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."))
777 .build()
778 ))
779 }
780}
781
782#[cfg(feature = "openapi")]
783impl ToSchema for ResourceOutputs {
784 fn name() -> std::borrow::Cow<'static, str> {
785 std::borrow::Cow::Borrowed("BaseResourceOutputs")
786 }
787}
788
789#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
791#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
792#[serde(rename_all = "kebab-case")]
793pub enum ResourceStatus {
794 Pending, Provisioning, ProvisionFailed,
797 Running, Updating,
799 UpdateFailed,
800 Deleting, DeleteFailed,
802 TeardownRequired, Deleted, RefreshFailed, }
806
807impl ResourceStatus {
808 pub fn is_terminal(&self) -> bool {
809 match self {
810 ResourceStatus::TeardownRequired => true,
811 ResourceStatus::Deleted => true,
812 ResourceStatus::ProvisionFailed => true,
813 ResourceStatus::UpdateFailed => true,
814 ResourceStatus::DeleteFailed => true,
815 ResourceStatus::RefreshFailed => true,
816 _ => false, }
818 }
819}
820
821#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
823#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
824#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
825#[serde(rename_all = "kebab-case")]
826pub enum ResourceLifecycle {
827 Frozen,
831
832 Live,
836}