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 "kv" => Box::new(
206 serde_json::from_value::<crate::resources::Kv>(value)
207 .map_err(serde::de::Error::custom)?,
208 ),
209 "postgres" => Box::new(
210 serde_json::from_value::<crate::resources::Postgres>(value)
211 .map_err(serde::de::Error::custom)?,
212 ),
213 "network" => Box::new(
214 serde_json::from_value::<crate::resources::Network>(value)
215 .map_err(serde::de::Error::custom)?,
216 ),
217 "build" => Box::new(
218 serde_json::from_value::<crate::resources::Build>(value)
219 .map_err(serde::de::Error::custom)?,
220 ),
221 "service-account" => Box::new(
222 serde_json::from_value::<crate::resources::ServiceAccount>(value)
223 .map_err(serde::de::Error::custom)?,
224 ),
225 "artifact-registry" => Box::new(
226 serde_json::from_value::<crate::resources::ArtifactRegistry>(value)
227 .map_err(serde::de::Error::custom)?,
228 ),
229 "service_activation" => Box::new(
230 serde_json::from_value::<crate::resources::ServiceActivation>(value)
231 .map_err(serde::de::Error::custom)?,
232 ),
233 "remote-stack-management" => Box::new(
234 serde_json::from_value::<crate::resources::RemoteStackManagement>(value)
235 .map_err(serde::de::Error::custom)?,
236 ),
237 "azure_resource_group" => Box::new(
238 serde_json::from_value::<crate::resources::AzureResourceGroup>(value)
239 .map_err(serde::de::Error::custom)?,
240 ),
241 "azure_storage_account" => Box::new(
242 serde_json::from_value::<crate::resources::AzureStorageAccount>(value)
243 .map_err(serde::de::Error::custom)?,
244 ),
245 "azure_container_apps_environment" => Box::new(
246 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironment>(value)
247 .map_err(serde::de::Error::custom)?,
248 ),
249 "azure_service_bus_namespace" => Box::new(
250 serde_json::from_value::<crate::resources::AzureServiceBusNamespace>(value)
251 .map_err(serde::de::Error::custom)?,
252 ),
253 other => {
254 return Err(serde::de::Error::unknown_variant(
255 other,
256 &[
257 "vault",
258 "worker",
259 "daemon",
260 "container",
261 "compute-cluster",
262 "kubernetes-cluster",
263 "storage",
264 "queue",
265 "kv",
266 "postgres",
267 "network",
268 "build",
269 "service-account",
270 "artifact-registry",
271 "service_activation",
272 "remote-stack-management",
273 "azure_resource_group",
274 "azure_storage_account",
275 "azure_container_apps_environment",
276 "azure_service_bus_namespace",
277 ],
278 ))
279 }
280 };
281
282 Ok(Resource { inner })
283 }
284}
285
286impl Resource {
287 pub fn new<T: ResourceDefinition>(resource: T) -> Self {
289 Self {
290 inner: Box::new(resource),
291 }
292 }
293
294 pub fn from_boxed(boxed_resource: Box<dyn ResourceDefinition>) -> Self {
296 Self {
297 inner: boxed_resource,
298 }
299 }
300
301 pub fn resource_type(&self) -> ResourceType {
303 self.inner.get_resource_type()
304 }
305
306 pub fn id(&self) -> &str {
308 self.inner.id()
309 }
310
311 pub fn get_dependencies(&self) -> Vec<ResourceRef> {
313 self.inner.get_dependencies()
314 }
315
316 pub fn get_permissions(&self) -> Option<&str> {
318 self.inner.get_permissions()
319 }
320
321 pub fn validate_update(&self, new_config: &Resource) -> Result<()> {
323 self.inner.validate_update(new_config.inner.as_ref())
324 }
325
326 pub fn as_resource_definition(&self) -> &dyn ResourceDefinition {
328 self.inner.as_ref()
329 }
330
331 pub fn downcast_ref<T: ResourceDefinition + 'static>(&self) -> Option<&T> {
333 self.inner.as_any().downcast_ref::<T>()
334 }
335
336 pub fn downcast_mut<T: ResourceDefinition + 'static>(&mut self) -> Option<&mut T> {
338 self.inner.as_any_mut().downcast_mut::<T>()
339 }
340}
341
342impl PartialEq for Resource {
343 fn eq(&self, other: &Self) -> bool {
344 self.inner.resource_eq(other.inner.as_ref())
345 }
346}
347
348impl Eq for Resource {}
349
350#[cfg(feature = "openapi")]
372impl PartialSchema for Resource {
373 fn schema() -> RefOr<Schema> {
374 RefOr::T(Schema::Object(
375 ObjectBuilder::new()
376 .schema_type(Type::Object)
377 .property("type", Ref::from_schema_name("ResourceType"))
378 .property("id",
379 ObjectBuilder::new()
380 .schema_type(Type::String)
381 .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."))
382 .build()
383 )
384 .required("type")
385 .required("id")
386 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
387 .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."))
388 .build()
389 ))
390 }
391}
392
393#[cfg(feature = "openapi")]
394impl ToSchema for Resource {
395 fn name() -> std::borrow::Cow<'static, str> {
396 std::borrow::Cow::Borrowed("BaseResource")
397 }
398}
399
400#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
402#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
403#[serde(rename_all = "camelCase")]
404pub struct ResourceRef {
405 #[serde(rename = "type")]
406 pub resource_type: ResourceType,
407 pub id: String,
408}
409
410impl ResourceRef {
411 pub fn new(resource_type: ResourceType, id: impl Into<String>) -> Self {
413 Self {
414 resource_type,
415 id: id.into(),
416 }
417 }
418
419 pub fn resource_type(&self) -> &ResourceType {
421 &self.resource_type
422 }
423
424 pub fn id(&self) -> &str {
426 &self.id
427 }
428}
429
430impl<T: ResourceDefinition> From<&T> for ResourceRef {
431 fn from(resource: &T) -> Self {
432 Self::new(resource.get_resource_type(), resource.id())
433 }
434}
435
436impl From<&Resource> for ResourceRef {
437 fn from(resource: &Resource) -> Self {
438 Self::new(resource.resource_type(), resource.id())
439 }
440}
441
442pub trait ResourceOutputsDefinition: Debug + Send + Sync + 'static {
446 fn get_resource_type(&self) -> ResourceType;
448
449 fn as_any(&self) -> &dyn Any;
451
452 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition>;
454
455 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool;
457
458 fn to_json_value(&self) -> serde_json::Result<serde_json::Value>;
460}
461
462impl Clone for Box<dyn ResourceOutputsDefinition> {
464 fn clone(&self) -> Self {
465 self.box_clone()
466 }
467}
468
469#[derive(Debug, Clone)]
472pub struct ResourceOutputs {
473 inner: Box<dyn ResourceOutputsDefinition>,
474}
475
476impl Serialize for ResourceOutputs {
477 fn serialize<S: serde::Serializer>(
478 &self,
479 serializer: S,
480 ) -> std::result::Result<S::Ok, S::Error> {
481 let mut v = self
482 .inner
483 .to_json_value()
484 .map_err(serde::ser::Error::custom)?;
485 v.as_object_mut()
486 .ok_or_else(|| serde::ser::Error::custom("resource outputs must serialize as object"))?
487 .insert(
488 "type".into(),
489 serde_json::Value::String(self.inner.get_resource_type().0.into_owned()),
490 );
491 v.serialize(serializer)
492 }
493}
494
495impl<'de> Deserialize<'de> for ResourceOutputs {
496 fn deserialize<D: serde::Deserializer<'de>>(
497 deserializer: D,
498 ) -> std::result::Result<Self, D::Error> {
499 let mut value = serde_json::Value::deserialize(deserializer)?;
500 let type_tag = value
501 .get("type")
502 .and_then(|v| v.as_str())
503 .ok_or_else(|| serde::de::Error::missing_field("type"))?
504 .to_string();
505
506 if let Some(obj) = value.as_object_mut() {
509 obj.remove("type");
510 }
511
512 let inner: Box<dyn ResourceOutputsDefinition> = match type_tag.as_str() {
513 "vault" => Box::new(
514 serde_json::from_value::<crate::resources::VaultOutputs>(value)
515 .map_err(serde::de::Error::custom)?,
516 ),
517 "worker" => Box::new(
518 serde_json::from_value::<crate::resources::WorkerOutputs>(value)
519 .map_err(serde::de::Error::custom)?,
520 ),
521 "daemon" => Box::new(
522 serde_json::from_value::<crate::resources::DaemonOutputs>(value)
523 .map_err(serde::de::Error::custom)?,
524 ),
525 "container" => Box::new(
526 serde_json::from_value::<crate::resources::ContainerOutputs>(value)
527 .map_err(serde::de::Error::custom)?,
528 ),
529 "compute-cluster" => Box::new(
530 serde_json::from_value::<crate::resources::ComputeClusterOutputs>(value)
531 .map_err(serde::de::Error::custom)?,
532 ),
533 "storage" => Box::new(
534 serde_json::from_value::<crate::resources::StorageOutputs>(value)
535 .map_err(serde::de::Error::custom)?,
536 ),
537 "queue" => Box::new(
538 serde_json::from_value::<crate::resources::QueueOutputs>(value)
539 .map_err(serde::de::Error::custom)?,
540 ),
541 "kv" => Box::new(
542 serde_json::from_value::<crate::resources::KvOutputs>(value)
543 .map_err(serde::de::Error::custom)?,
544 ),
545 "postgres" => Box::new(
546 serde_json::from_value::<crate::resources::PostgresOutputs>(value)
547 .map_err(serde::de::Error::custom)?,
548 ),
549 "network" => Box::new(
550 serde_json::from_value::<crate::resources::NetworkOutputs>(value)
551 .map_err(serde::de::Error::custom)?,
552 ),
553 "build" => Box::new(
554 serde_json::from_value::<crate::resources::BuildOutputs>(value)
555 .map_err(serde::de::Error::custom)?,
556 ),
557 "service-account" => Box::new(
558 serde_json::from_value::<crate::resources::ServiceAccountOutputs>(value)
559 .map_err(serde::de::Error::custom)?,
560 ),
561 "artifact-registry" => Box::new(
562 serde_json::from_value::<crate::resources::ArtifactRegistryOutputs>(value)
563 .map_err(serde::de::Error::custom)?,
564 ),
565 "service_activation" => Box::new(
566 serde_json::from_value::<crate::resources::ServiceActivationOutputs>(value)
567 .map_err(serde::de::Error::custom)?,
568 ),
569 "remote-stack-management" => Box::new(
570 serde_json::from_value::<crate::resources::RemoteStackManagementOutputs>(value)
571 .map_err(serde::de::Error::custom)?,
572 ),
573 "kubernetes-cluster" => Box::new(
574 serde_json::from_value::<crate::resources::KubernetesClusterOutputs>(value)
575 .map_err(serde::de::Error::custom)?,
576 ),
577 "azure_resource_group" => Box::new(
578 serde_json::from_value::<crate::resources::AzureResourceGroupOutputs>(value)
579 .map_err(serde::de::Error::custom)?,
580 ),
581 "azure_storage_account" => Box::new(
582 serde_json::from_value::<crate::resources::AzureStorageAccountOutputs>(value)
583 .map_err(serde::de::Error::custom)?,
584 ),
585 "azure_container_apps_environment" => Box::new(
586 serde_json::from_value::<crate::resources::AzureContainerAppsEnvironmentOutputs>(
587 value,
588 )
589 .map_err(serde::de::Error::custom)?,
590 ),
591 "azure_service_bus_namespace" => Box::new(
592 serde_json::from_value::<crate::resources::AzureServiceBusNamespaceOutputs>(value)
593 .map_err(serde::de::Error::custom)?,
594 ),
595 other => {
596 return Err(serde::de::Error::unknown_variant(
597 other,
598 &[
599 "vault",
600 "worker",
601 "daemon",
602 "container",
603 "compute-cluster",
604 "storage",
605 "queue",
606 "kv",
607 "postgres",
608 "network",
609 "build",
610 "service-account",
611 "artifact-registry",
612 "service_activation",
613 "remote-stack-management",
614 "kubernetes-cluster",
615 "azure_resource_group",
616 "azure_storage_account",
617 "azure_container_apps_environment",
618 "azure_service_bus_namespace",
619 ],
620 ))
621 }
622 };
623
624 Ok(ResourceOutputs { inner })
625 }
626}
627
628impl ResourceOutputs {
629 pub fn new<T: ResourceOutputsDefinition>(outputs: T) -> Self {
631 Self {
632 inner: Box::new(outputs),
633 }
634 }
635
636 pub fn as_resource_outputs(&self) -> &dyn ResourceOutputsDefinition {
638 self.inner.as_ref()
639 }
640
641 pub fn downcast_ref<T: ResourceOutputsDefinition + 'static>(&self) -> Option<&T> {
643 self.inner.as_any().downcast_ref::<T>()
644 }
645}
646
647impl PartialEq for ResourceOutputs {
648 fn eq(&self, other: &Self) -> bool {
649 self.inner.outputs_eq(other.inner.as_ref())
650 }
651}
652
653impl Eq for ResourceOutputs {}
654
655#[cfg(feature = "openapi")]
674impl PartialSchema for ResourceOutputs {
675 fn schema() -> RefOr<Schema> {
676 RefOr::T(Schema::Object(
677 ObjectBuilder::new()
678 .schema_type(Type::Object)
679 .property("type", Ref::from_schema_name("ResourceType"))
680 .required("type")
681 .additional_properties(Some(AdditionalProperties::FreeForm(true)))
682 .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."))
683 .build()
684 ))
685 }
686}
687
688#[cfg(feature = "openapi")]
689impl ToSchema for ResourceOutputs {
690 fn name() -> std::borrow::Cow<'static, str> {
691 std::borrow::Cow::Borrowed("BaseResourceOutputs")
692 }
693}
694
695#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
697#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
698#[serde(rename_all = "kebab-case")]
699pub enum ResourceStatus {
700 Pending, Provisioning, ProvisionFailed,
703 Running, Updating,
705 UpdateFailed,
706 Deleting, DeleteFailed,
708 TeardownRequired, Deleted, RefreshFailed, }
712
713impl ResourceStatus {
714 pub fn is_terminal(&self) -> bool {
715 match self {
716 ResourceStatus::TeardownRequired => true,
717 ResourceStatus::Deleted => true,
718 ResourceStatus::ProvisionFailed => true,
719 ResourceStatus::UpdateFailed => true,
720 ResourceStatus::DeleteFailed => true,
721 ResourceStatus::RefreshFailed => true,
722 _ => false, }
724 }
725}
726
727#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash, Deserialize)]
729#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
730#[serde(rename_all = "kebab-case")]
731pub enum ResourceLifecycle {
732 Frozen,
736
737 Live,
741}