alien-core 3.3.65

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! External bindings for pre-existing infrastructure services.
//!
//! External bindings allow using existing infrastructure (MinIO, Kafka, Redis, etc.)
//! instead of having Alien provision cloud resources. This is required for Kubernetes
//! platform deployments and optional for cloud platforms (to override specific resources).

use std::collections::HashMap;

use alien_error::AlienError;
use serde::{Deserialize, Serialize};

use crate::bindings::{
    ArtifactRegistryBinding, BindingValue, ContainerAppsEnvironmentBinding, ExternalAiBinding,
    KvBinding, PostgresBinding, QueueBinding, RedisBinding, StorageBinding, VaultBinding,
};
use crate::error::ErrorData;
use crate::resource::ResourceOutputs;
use crate::resources::AzureContainerAppsEnvironmentOutputs;
use crate::Resource;

/// Represents a binding to pre-existing infrastructure.
///
/// The binding type must match the resource type it's applied to.
/// Validated at runtime by the executor.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ExternalBinding {
    /// External storage binding (S3-compatible, GCS, Blob Storage)
    Storage(StorageBinding),
    /// External queue binding (Kafka, SQS, etc.)
    Queue(QueueBinding),
    /// External KV binding (Redis, etc.)
    Kv(KvBinding),
    /// External artifact registry binding (OCI registry)
    ArtifactRegistry(ArtifactRegistryBinding),
    /// External vault binding (HashiCorp Vault, etc.)
    Vault(VaultBinding),
    /// External Azure Container Apps Environment binding (pre-existing environment)
    ContainerAppsEnvironment(ContainerAppsEnvironmentBinding),
    /// External Postgres binding (operator-provided / BYO database)
    Postgres(PostgresBinding),
    /// External Redis binding (operator-provided Redis-compatible server)
    Redis(RedisBinding),
    /// External AI provider binding (BYO-key OpenAI/Anthropic, etc.)
    Ai(ExternalAiBinding),
}

/// Map from resource ID to external binding.
///
/// Validated at runtime: binding type must match resource type.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(transparent)]
pub struct ExternalBindings(pub HashMap<String, ExternalBinding>);

impl ExternalBindings {
    /// Creates an empty ExternalBindings map.
    pub fn new() -> Self {
        Self(HashMap::new())
    }

    /// Returns true if there are no external bindings.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Checks if a binding exists for the given resource ID.
    pub fn has(&self, resource_id: &str) -> bool {
        self.0.contains_key(resource_id)
    }

    /// Gets an external binding by resource ID.
    pub fn get(&self, resource_id: &str) -> Option<&ExternalBinding> {
        self.0.get(resource_id)
    }

    /// Gets a storage binding for the given resource ID.
    /// Returns an error if the binding exists but is not a Storage type.
    pub fn get_storage(&self, id: &str) -> crate::error::Result<Option<&StorageBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Storage(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "storage".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets a queue binding for the given resource ID.
    /// Returns an error if the binding exists but is not a Queue type.
    pub fn get_queue(&self, id: &str) -> crate::error::Result<Option<&QueueBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Queue(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "queue".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets a KV binding for the given resource ID.
    /// Returns an error if the binding exists but is not a Kv type.
    pub fn get_kv(&self, id: &str) -> crate::error::Result<Option<&KvBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Kv(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "kv".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets an artifact registry binding for the given resource ID.
    /// Returns an error if the binding exists but is not an ArtifactRegistry type.
    pub fn get_artifact_registry(
        &self,
        id: &str,
    ) -> crate::error::Result<Option<&ArtifactRegistryBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::ArtifactRegistry(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "artifact_registry".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets a vault binding for the given resource ID.
    /// Returns an error if the binding exists but is not a Vault type.
    pub fn get_vault(&self, id: &str) -> crate::error::Result<Option<&VaultBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Vault(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "vault".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets an AI binding for the given resource ID.
    /// Returns an error if the binding exists but is not an Ai type.
    pub fn get_ai(&self, id: &str) -> crate::error::Result<Option<&ExternalAiBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Ai(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "ai".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Gets a container apps environment binding for the given resource ID.
    /// Returns an error if the binding exists but is not a ContainerAppsEnvironment type.
    pub fn get_container_apps_environment(
        &self,
        id: &str,
    ) -> crate::error::Result<Option<&ContainerAppsEnvironmentBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::ContainerAppsEnvironment(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "azure_container_apps_environment".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Returns an error if the binding exists but is not a Postgres type.
    pub fn get_postgres(&self, id: &str) -> crate::error::Result<Option<&PostgresBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Postgres(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "postgres".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Returns an error if the binding exists but is not a Redis type.
    pub fn get_redis(&self, id: &str) -> crate::error::Result<Option<&RedisBinding>> {
        match self.0.get(id) {
            Some(ExternalBinding::Redis(b)) => Ok(Some(b)),
            Some(other) => Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
                resource_id: id.to_string(),
                expected: "redis".to_string(),
                actual: other.binding_type().to_string(),
            })),
            None => Ok(None),
        }
    }

    /// Inserts an external binding for a resource.
    pub fn insert(&mut self, resource_id: impl Into<String>, binding: ExternalBinding) {
        self.0.insert(resource_id.into(), binding);
    }
}

impl ExternalBinding {
    /// Returns the type name of this binding variant.
    pub fn binding_type(&self) -> &'static str {
        match self {
            ExternalBinding::Storage(_) => "storage",
            ExternalBinding::Queue(_) => "queue",
            ExternalBinding::Kv(_) => "kv",
            ExternalBinding::ArtifactRegistry(_) => "artifact_registry",
            ExternalBinding::Vault(_) => "vault",
            ExternalBinding::ContainerAppsEnvironment(_) => "azure_container_apps_environment",
            ExternalBinding::Postgres(_) => "postgres",
            ExternalBinding::Redis(_) => "redis",
            ExternalBinding::Ai(_) => "ai",
        }
    }

    /// Converts this external binding into resource outputs that dependent resources
    /// can read via `get_resource_outputs()`.
    ///
    /// Infrastructure bindings (Container Apps Environment) produce typed outputs so that
    /// dependent resources like functions and builds can read the environment's name,
    /// resource ID, and resource group. Application-level bindings (Storage, Queue, KV, etc.)
    /// return `None` — they are consumed via `remote_binding_params` and environment variables
    /// rather than `get_resource_outputs()`.
    pub fn to_resource_outputs(&self) -> Option<ResourceOutputs> {
        match self {
            ExternalBinding::ContainerAppsEnvironment(binding) => {
                // Extract concrete values from BindingValue wrappers.
                // External bindings for pre-provisioned resources always use concrete values.
                let environment_name = match &binding.environment_name {
                    BindingValue::Value(v) => v.clone(),
                    _ => return None,
                };
                let resource_id = match &binding.resource_id {
                    BindingValue::Value(v) => v.clone(),
                    _ => return None,
                };
                let resource_group_name = match &binding.resource_group_name {
                    BindingValue::Value(v) => v.clone(),
                    _ => return None,
                };
                let default_domain = match &binding.default_domain {
                    BindingValue::Value(v) => v.clone(),
                    _ => return None,
                };
                let static_ip = binding.static_ip.as_ref().and_then(|v| match v {
                    BindingValue::Value(v) => Some(v.clone()),
                    _ => None,
                });

                Some(ResourceOutputs::new(AzureContainerAppsEnvironmentOutputs {
                    environment_name,
                    resource_id,
                    resource_group_name,
                    default_domain,
                    static_ip,
                    custom_domain_verification_id: None,
                }))
            }
            // Application-level bindings are consumed via remote_binding_params, not outputs
            _ => None,
        }
    }

    /// Serializes this external binding to the JSON value injected into the worker
    /// environment as `ALIEN_<NAME>_BINDING`, matching the shape the SDK parses.
    ///
    /// The AI arm wraps the carried `ExternalAiBinding` in `AiBinding::External` so
    /// the value keeps the `service` tag the SDK's `ai(name)` parser discriminates
    /// on; a bare `ExternalAiBinding` would lack it. Every other arm serializes the
    /// carried binding directly, like the runtime controllers' `get_binding_params`.
    pub fn to_env_binding_value(&self) -> serde_json::Result<serde_json::Value> {
        match self {
            ExternalBinding::Storage(b) => serde_json::to_value(b),
            ExternalBinding::Queue(b) => serde_json::to_value(b),
            ExternalBinding::Kv(b) => serde_json::to_value(b),
            ExternalBinding::ArtifactRegistry(b) => serde_json::to_value(b),
            ExternalBinding::Vault(b) => serde_json::to_value(b),
            ExternalBinding::ContainerAppsEnvironment(b) => serde_json::to_value(b),
            ExternalBinding::Postgres(b) => serde_json::to_value(b),
            ExternalBinding::Redis(b) => serde_json::to_value(b),
            ExternalBinding::Ai(b) => {
                serde_json::to_value(crate::bindings::AiBinding::External(b.clone()))
            }
        }
    }
}

/// Validates that an external binding type matches the resource type.
pub fn validate_binding_type(
    resource: &Resource,
    binding: &ExternalBinding,
) -> crate::error::Result<()> {
    let resource_type = resource.resource_type();
    let resource_type_str = resource_type.as_ref();

    let valid = match (resource_type_str, binding) {
        ("storage", ExternalBinding::Storage(_)) => true,
        ("queue", ExternalBinding::Queue(_)) => true,
        ("kv", ExternalBinding::Kv(_)) => true,
        ("artifact_registry", ExternalBinding::ArtifactRegistry(_)) => true,
        ("vault", ExternalBinding::Vault(_)) => true,
        ("azure_container_apps_environment", ExternalBinding::ContainerAppsEnvironment(_)) => true,
        ("postgres", ExternalBinding::Postgres(_)) => true,
        ("redis", ExternalBinding::Redis(_)) => true,
        ("ai", ExternalBinding::Ai(_)) => true,
        _ => false,
    };

    if !valid {
        return Err(AlienError::new(ErrorData::ExternalBindingTypeMismatch {
            resource_id: resource.id().to_string(),
            expected: resource_type_str.to_string(),
            actual: binding.binding_type().to_string(),
        }));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bindings::{KvBinding, StorageBinding};

    #[test]
    fn test_external_bindings_storage() {
        let mut bindings = ExternalBindings::new();
        bindings.insert(
            "data-storage",
            ExternalBinding::Storage(StorageBinding::s3("my-bucket")),
        );

        assert!(bindings.has("data-storage"));
        assert!(bindings.get_storage("data-storage").unwrap().is_some());
        assert!(bindings.get_queue("data-storage").is_err()); // Wrong type
    }

    #[test]
    fn test_external_bindings_kv() {
        let mut bindings = ExternalBindings::new();
        bindings.insert(
            "cache",
            ExternalBinding::Kv(KvBinding::redis("redis://localhost:6379")),
        );

        assert!(bindings.has("cache"));
        assert!(bindings.get_kv("cache").unwrap().is_some());
        assert!(bindings.get_storage("cache").is_err()); // Wrong type
    }

    #[test]
    fn test_external_bindings_ai() {
        use crate::bindings::ExternalAiBinding;

        let mut bindings = ExternalBindings::new();
        bindings.insert(
            "llm",
            ExternalBinding::Ai(ExternalAiBinding {
                provider: "openai".to_string(),
                api_key: "sk-test".into(),
            }),
        );

        assert!(bindings.has("llm"));
        assert_eq!(bindings.get("llm").unwrap().binding_type(), "ai");
        assert_eq!(bindings.get_ai("llm").unwrap().unwrap().provider, "openai");
        assert!(bindings.get_kv("llm").is_err()); // Wrong type
    }

    #[test]
    fn test_external_bindings_serialization() {
        let mut bindings = ExternalBindings::new();
        bindings.insert(
            "data",
            ExternalBinding::Storage(StorageBinding::s3("test-bucket")),
        );

        let json = serde_json::to_string(&bindings).unwrap();
        let deserialized: ExternalBindings = serde_json::from_str(&json).unwrap();
        assert_eq!(bindings, deserialized);
    }
}

/// Resource types an installer can bind to existing infrastructure with an
/// [`ExternalBinding`].
pub const EXTERNAL_BINDING_TYPES: &[&str] = &[
    "storage",
    "queue",
    "kv",
    "artifact-registry",
    "vault",
    "postgres",
    "redis",
    "ai",
];