Skip to main content

alien_core/
external_bindings.rs

1//! External bindings for pre-existing infrastructure services.
2//!
3//! External bindings allow using existing infrastructure (MinIO, Kafka, Redis, etc.)
4//! instead of having Alien provision cloud resources. This is required for Kubernetes
5//! platform deployments and optional for cloud platforms (to override specific resources).
6
7use std::collections::HashMap;
8
9use alien_error::AlienError;
10use serde::{Deserialize, Serialize};
11
12use crate::bindings::{
13    ArtifactRegistryBinding, BindingValue, ContainerAppsEnvironmentBinding, ExternalAi, KvBinding,
14    PostgresBinding, QueueBinding, RedisBinding, StorageBinding, VaultBinding,
15};
16use crate::error::ErrorData;
17use crate::resource::ResourceOutputs;
18use crate::resources::AzureContainerAppsEnvironmentOutputs;
19use crate::Resource;
20
21/// Represents a binding to pre-existing infrastructure.
22///
23/// The binding type must match the resource type it's applied to.
24/// Validated at runtime by the executor.
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
27#[serde(tag = "type", rename_all = "snake_case")]
28pub enum ExternalBinding {
29    /// External storage binding (S3-compatible, GCS, Blob Storage)
30    Storage(StorageBinding),
31    /// External queue binding (Kafka, SQS, etc.)
32    Queue(QueueBinding),
33    /// External KV binding (Redis, etc.)
34    Kv(KvBinding),
35    /// External artifact registry binding (OCI registry)
36    ArtifactRegistry(ArtifactRegistryBinding),
37    /// External vault binding (HashiCorp Vault, etc.)
38    Vault(VaultBinding),
39    /// External Azure Container Apps Environment binding (pre-existing environment)
40    ContainerAppsEnvironment(ContainerAppsEnvironmentBinding),
41    /// External Postgres binding (operator-provided / BYO database)
42    Postgres(PostgresBinding),
43    /// External Redis binding (operator-provided Redis-compatible server)
44    Redis(RedisBinding),
45    /// External AI binding: a BYO-key provider (OpenAI/Anthropic, etc.) or a cloud AI service
46    /// reached with the workload's own identity (Bedrock)
47    Ai(ExternalAi),
48}
49
50/// Map from resource ID to external binding.
51///
52/// Validated at runtime: binding type must match resource type.
53#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
54#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
55#[serde(transparent)]
56pub struct ExternalBindings(pub HashMap<String, ExternalBinding>);
57
58impl ExternalBindings {
59    /// Creates an empty ExternalBindings map.
60    pub fn new() -> Self {
61        Self(HashMap::new())
62    }
63
64    /// Returns true if there are no external bindings.
65    pub fn is_empty(&self) -> bool {
66        self.0.is_empty()
67    }
68
69    /// Checks if a binding exists for the given resource ID.
70    pub fn has(&self, resource_id: &str) -> bool {
71        self.0.contains_key(resource_id)
72    }
73
74    /// Gets an external binding by resource ID.
75    pub fn get(&self, resource_id: &str) -> Option<&ExternalBinding> {
76        self.0.get(resource_id)
77    }
78
79    /// Gets a storage binding for the given resource ID.
80    /// Returns an error if the binding exists but is not a Storage type.
81    pub fn get_storage(&self, id: &str) -> crate::error::Result<Option<&StorageBinding>> {
82        match self.0.get(id) {
83            Some(ExternalBinding::Storage(b)) => Ok(Some(b)),
84            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
85                resource_id: id.to_string(),
86                expected: "storage".to_string(),
87                actual: other.binding_type().to_string(),
88            })),
89            None => Ok(None),
90        }
91    }
92
93    /// Gets a queue binding for the given resource ID.
94    /// Returns an error if the binding exists but is not a Queue type.
95    pub fn get_queue(&self, id: &str) -> crate::error::Result<Option<&QueueBinding>> {
96        match self.0.get(id) {
97            Some(ExternalBinding::Queue(b)) => Ok(Some(b)),
98            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
99                resource_id: id.to_string(),
100                expected: "queue".to_string(),
101                actual: other.binding_type().to_string(),
102            })),
103            None => Ok(None),
104        }
105    }
106
107    /// Gets a KV binding for the given resource ID.
108    /// Returns an error if the binding exists but is not a Kv type.
109    pub fn get_kv(&self, id: &str) -> crate::error::Result<Option<&KvBinding>> {
110        match self.0.get(id) {
111            Some(ExternalBinding::Kv(b)) => Ok(Some(b)),
112            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
113                resource_id: id.to_string(),
114                expected: "kv".to_string(),
115                actual: other.binding_type().to_string(),
116            })),
117            None => Ok(None),
118        }
119    }
120
121    /// Gets an artifact registry binding for the given resource ID.
122    /// Returns an error if the binding exists but is not an ArtifactRegistry type.
123    pub fn get_artifact_registry(
124        &self,
125        id: &str,
126    ) -> crate::error::Result<Option<&ArtifactRegistryBinding>> {
127        match self.0.get(id) {
128            Some(ExternalBinding::ArtifactRegistry(b)) => Ok(Some(b)),
129            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
130                resource_id: id.to_string(),
131                expected: "artifact_registry".to_string(),
132                actual: other.binding_type().to_string(),
133            })),
134            None => Ok(None),
135        }
136    }
137
138    /// Gets a vault binding for the given resource ID.
139    /// Returns an error if the binding exists but is not a Vault type.
140    pub fn get_vault(&self, id: &str) -> crate::error::Result<Option<&VaultBinding>> {
141        match self.0.get(id) {
142            Some(ExternalBinding::Vault(b)) => Ok(Some(b)),
143            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
144                resource_id: id.to_string(),
145                expected: "vault".to_string(),
146                actual: other.binding_type().to_string(),
147            })),
148            None => Ok(None),
149        }
150    }
151
152    /// Gets an AI binding for the given resource ID.
153    /// Returns an error if the binding exists but is not an Ai type.
154    pub fn get_ai(&self, id: &str) -> crate::error::Result<Option<&ExternalAi>> {
155        match self.0.get(id) {
156            Some(ExternalBinding::Ai(b)) => Ok(Some(b)),
157            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
158                resource_id: id.to_string(),
159                expected: "ai".to_string(),
160                actual: other.binding_type().to_string(),
161            })),
162            None => Ok(None),
163        }
164    }
165
166    /// Gets a container apps environment binding for the given resource ID.
167    /// Returns an error if the binding exists but is not a ContainerAppsEnvironment type.
168    pub fn get_container_apps_environment(
169        &self,
170        id: &str,
171    ) -> crate::error::Result<Option<&ContainerAppsEnvironmentBinding>> {
172        match self.0.get(id) {
173            Some(ExternalBinding::ContainerAppsEnvironment(b)) => Ok(Some(b)),
174            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
175                resource_id: id.to_string(),
176                expected: "azure_container_apps_environment".to_string(),
177                actual: other.binding_type().to_string(),
178            })),
179            None => Ok(None),
180        }
181    }
182
183    /// Returns an error if the binding exists but is not a Postgres type.
184    pub fn get_postgres(&self, id: &str) -> crate::error::Result<Option<&PostgresBinding>> {
185        match self.0.get(id) {
186            Some(ExternalBinding::Postgres(b)) => Ok(Some(b)),
187            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
188                resource_id: id.to_string(),
189                expected: "postgres".to_string(),
190                actual: other.binding_type().to_string(),
191            })),
192            None => Ok(None),
193        }
194    }
195
196    /// Returns an error if the binding exists but is not a Redis type.
197    pub fn get_redis(&self, id: &str) -> crate::error::Result<Option<&RedisBinding>> {
198        match self.0.get(id) {
199            Some(ExternalBinding::Redis(b)) => Ok(Some(b)),
200            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
201                resource_id: id.to_string(),
202                expected: "redis".to_string(),
203                actual: other.binding_type().to_string(),
204            })),
205            None => Ok(None),
206        }
207    }
208
209    /// Inserts an external binding for a resource.
210    pub fn insert(&mut self, resource_id: impl Into<String>, binding: ExternalBinding) {
211        self.0.insert(resource_id.into(), binding);
212    }
213}
214
215impl ExternalBinding {
216    /// Returns the type name of this binding variant.
217    pub fn binding_type(&self) -> &'static str {
218        match self {
219            ExternalBinding::Storage(_) => "storage",
220            ExternalBinding::Queue(_) => "queue",
221            ExternalBinding::Kv(_) => "kv",
222            ExternalBinding::ArtifactRegistry(_) => "artifact_registry",
223            ExternalBinding::Vault(_) => "vault",
224            ExternalBinding::ContainerAppsEnvironment(_) => "azure_container_apps_environment",
225            ExternalBinding::Postgres(_) => "postgres",
226            ExternalBinding::Redis(_) => "redis",
227            ExternalBinding::Ai(_) => "ai",
228        }
229    }
230
231    /// Converts this external binding into resource outputs that dependent resources
232    /// can read via `get_resource_outputs()`.
233    ///
234    /// Infrastructure bindings (Container Apps Environment) produce typed outputs so that
235    /// dependent resources like functions and builds can read the environment's name,
236    /// resource ID, and resource group. Application-level bindings (Storage, Queue, KV, etc.)
237    /// return `None` — they are consumed via `remote_binding_params` and environment variables
238    /// rather than `get_resource_outputs()`.
239    pub fn to_resource_outputs(&self) -> Option<ResourceOutputs> {
240        match self {
241            ExternalBinding::ContainerAppsEnvironment(binding) => {
242                // Extract concrete values from BindingValue wrappers.
243                // External bindings for pre-provisioned resources always use concrete values.
244                let environment_name = match &binding.environment_name {
245                    BindingValue::Value(v) => v.clone(),
246                    _ => return None,
247                };
248                let resource_id = match &binding.resource_id {
249                    BindingValue::Value(v) => v.clone(),
250                    _ => return None,
251                };
252                let resource_group_name = match &binding.resource_group_name {
253                    BindingValue::Value(v) => v.clone(),
254                    _ => return None,
255                };
256                let default_domain = match &binding.default_domain {
257                    BindingValue::Value(v) => v.clone(),
258                    _ => return None,
259                };
260                let static_ip = binding.static_ip.as_ref().and_then(|v| match v {
261                    BindingValue::Value(v) => Some(v.clone()),
262                    _ => None,
263                });
264
265                Some(ResourceOutputs::new(AzureContainerAppsEnvironmentOutputs {
266                    environment_name,
267                    resource_id,
268                    resource_group_name,
269                    default_domain,
270                    static_ip,
271                    custom_domain_verification_id: None,
272                }))
273            }
274            // Application-level bindings are consumed via remote_binding_params, not outputs
275            _ => None,
276        }
277    }
278
279    /// Serializes this external binding to the JSON value injected into the worker
280    /// environment as `ALIEN_<NAME>_BINDING`, matching the shape the SDK parses.
281    ///
282    /// The AI arm converts to an `AiBinding` so the value keeps the `service` tag the
283    /// SDK's `ai(name)` parser discriminates on: `external-ai` for a BYO key, `bedrock`
284    /// for ambient credentials. Every other arm serializes the
285    /// carried binding directly, like the runtime controllers' `get_binding_params`.
286    pub fn to_env_binding_value(&self) -> serde_json::Result<serde_json::Value> {
287        match self {
288            ExternalBinding::Storage(b) => serde_json::to_value(b),
289            ExternalBinding::Queue(b) => serde_json::to_value(b),
290            ExternalBinding::Kv(b) => serde_json::to_value(b),
291            ExternalBinding::ArtifactRegistry(b) => serde_json::to_value(b),
292            ExternalBinding::Vault(b) => serde_json::to_value(b),
293            ExternalBinding::ContainerAppsEnvironment(b) => serde_json::to_value(b),
294            ExternalBinding::Postgres(b) => serde_json::to_value(b),
295            ExternalBinding::Redis(b) => serde_json::to_value(b),
296            ExternalBinding::Ai(b) => serde_json::to_value(b.to_ai_binding()),
297        }
298    }
299}
300
301/// Validates that an external binding type matches the resource type.
302pub fn validate_binding_type(
303    resource: &Resource,
304    binding: &ExternalBinding,
305) -> crate::error::Result<()> {
306    let resource_type = resource.resource_type();
307    let resource_type_str = resource_type.as_ref();
308
309    let valid = match (resource_type_str, binding) {
310        ("storage", ExternalBinding::Storage(_)) => true,
311        ("queue", ExternalBinding::Queue(_)) => true,
312        ("kv", ExternalBinding::Kv(_)) => true,
313        ("artifact_registry", ExternalBinding::ArtifactRegistry(_)) => true,
314        ("vault", ExternalBinding::Vault(_)) => true,
315        ("azure_container_apps_environment", ExternalBinding::ContainerAppsEnvironment(_)) => true,
316        ("postgres", ExternalBinding::Postgres(_)) => true,
317        ("redis", ExternalBinding::Redis(_)) => true,
318        ("ai", ExternalBinding::Ai(_)) => true,
319        _ => false,
320    };
321
322    if !valid {
323        return Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
324            resource_id: resource.id().to_string(),
325            expected: resource_type_str.to_string(),
326            actual: binding.binding_type().to_string(),
327        }));
328    }
329    Ok(())
330}
331
332#[cfg(test)]
333mod tests {
334    use super::*;
335    use crate::bindings::{KvBinding, StorageBinding};
336
337    #[test]
338    fn test_external_bindings_storage() {
339        let mut bindings = ExternalBindings::new();
340        bindings.insert(
341            "data-storage",
342            ExternalBinding::Storage(StorageBinding::s3("my-bucket")),
343        );
344
345        assert!(bindings.has("data-storage"));
346        assert!(bindings.get_storage("data-storage").unwrap().is_some());
347        assert!(bindings.get_queue("data-storage").is_err()); // Wrong type
348    }
349
350    #[test]
351    fn test_external_bindings_kv() {
352        let mut bindings = ExternalBindings::new();
353        bindings.insert(
354            "cache",
355            ExternalBinding::Kv(KvBinding::redis("redis://localhost:6379")),
356        );
357
358        assert!(bindings.has("cache"));
359        assert!(bindings.get_kv("cache").unwrap().is_some());
360        assert!(bindings.get_storage("cache").is_err()); // Wrong type
361    }
362
363    #[test]
364    fn test_external_bindings_ai() {
365        use crate::bindings::ExternalAiBinding;
366
367        let mut bindings = ExternalBindings::new();
368        bindings.insert(
369            "llm",
370            ExternalBinding::Ai(
371                ExternalAiBinding {
372                    provider: "openai".to_string(),
373                    api_key: "sk-test".into(),
374                }
375                .into(),
376            ),
377        );
378
379        assert!(bindings.has("llm"));
380        assert_eq!(bindings.get("llm").unwrap().binding_type(), "ai");
381        assert!(matches!(
382            bindings.get_ai("llm").unwrap().unwrap(),
383            ExternalAi::ApiKey(b) if b.provider == "openai"
384        ));
385        assert!(bindings.get_kv("llm").is_err()); // Wrong type
386    }
387
388    #[test]
389    fn external_ai_bedrock_with_ambient_credentials_parses_and_reaches_the_workload() {
390        let binding: ExternalBinding = serde_json::from_value(serde_json::json!({
391            "type": "ai", "service": "bedrock", "region": "us-east-1"
392        }))
393        .expect("ambient Bedrock external binding should parse");
394
395        // The workload env value is the first-class Bedrock binding: no key, no secret.
396        let value = binding.to_env_binding_value().unwrap();
397        assert_eq!(
398            value,
399            serde_json::json!({"service": "bedrock", "region": "us-east-1"})
400        );
401        assert_eq!(
402            serde_json::from_value::<crate::bindings::AiBinding>(value).unwrap(),
403            crate::bindings::AiBinding::bedrock("us-east-1")
404        );
405        // Round-trips as stored.
406        let stored = serde_json::to_value(&binding).unwrap();
407        assert_eq!(
408            serde_json::from_value::<ExternalBinding>(stored).unwrap(),
409            binding
410        );
411    }
412
413    #[test]
414    fn external_ai_byo_key_input_still_parses_unchanged() {
415        let binding: ExternalBinding = serde_json::from_value(serde_json::json!({
416            "type": "ai", "provider": "openai", "apiKey": "sk-test"
417        }))
418        .expect("stored BYO-key input must keep parsing");
419        assert_eq!(
420            binding.to_env_binding_value().unwrap(),
421            serde_json::json!({
422                "service": "external-ai", "provider": "openai", "apiKey": "sk-test"
423            })
424        );
425    }
426
427    #[test]
428    fn external_ai_rejects_a_bedrock_binding_without_region() {
429        assert!(
430            serde_json::from_value::<ExternalBinding>(serde_json::json!({
431                "type": "ai", "service": "bedrock"
432            }))
433            .is_err()
434        );
435    }
436
437    #[test]
438    fn test_external_bindings_serialization() {
439        let mut bindings = ExternalBindings::new();
440        bindings.insert(
441            "data",
442            ExternalBinding::Storage(StorageBinding::s3("test-bucket")),
443        );
444
445        let json = serde_json::to_string(&bindings).unwrap();
446        let deserialized: ExternalBindings = serde_json::from_str(&json).unwrap();
447        assert_eq!(bindings, deserialized);
448    }
449}
450
451/// Resource types an installer can bind to existing infrastructure with an
452/// [`ExternalBinding`].
453pub const EXTERNAL_BINDING_TYPES: &[&str] = &[
454    "storage",
455    "queue",
456    "kv",
457    "artifact-registry",
458    "vault",
459    "postgres",
460    "redis",
461    "ai",
462];