Skip to main content

alien_core/
runtime_environment.rs

1use crate::{bindings::binding_env_var_name, ErrorData, Platform, ResourceRef, Result};
2use alien_error::AlienError;
3use std::collections::HashMap;
4
5pub const ENV_ALIEN_CURRENT_WORKER_BINDING_NAME: &str = "ALIEN_CURRENT_WORKER_BINDING_NAME";
6pub const ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME: &str = "ALIEN_CURRENT_CONTAINER_BINDING_NAME";
7pub const ENV_OPERATOR_BASE_PLATFORM: &str = "OPERATOR_BASE_PLATFORM";
8/// Where application pods reach the Kubernetes sandbox session broker. The Helm chart sets it
9/// on the operator from the Service it renders in front of the operator, which serves the
10/// broker; the Sandbox controller publishes it in the sandbox binding.
11pub const ENV_ALIEN_SANDBOX_BROKER_URL: &str = "ALIEN_SANDBOX_BROKER_URL";
12/// JSON object mapping workload priority levels (`critical`, `high`, `normal`, `low`) to
13/// Kubernetes PriorityClass names. The Helm chart sets it on the operator only when the
14/// cluster administrator mapped at least one level.
15pub const ENV_ALIEN_KUBERNETES_PRIORITY_CLASSES: &str = "ALIEN_KUBERNETES_PRIORITY_CLASSES";
16pub const ENV_ALIEN_DEPLOYMENT_TYPE: &str = "ALIEN_DEPLOYMENT_TYPE";
17pub const ENV_ALIEN_LAMBDA_MODE: &str = "ALIEN_LAMBDA_MODE";
18pub const ENV_ALIEN_RUNTIME_SEND_OTLP: &str = "ALIEN_RUNTIME_SEND_OTLP";
19pub const ENV_ALIEN_RUNTIME_SECRETS: &str = "ALIEN_RUNTIME_SECRETS";
20pub const ENV_ALIEN_SECRETS: &str = "ALIEN_SECRETS";
21/// Opaque deployment-managed revision that rolls workloads when referenced
22/// secret values change without exposing secret-derived data in the spec.
23pub const ENV_ALIEN_SECRET_ENV_REVISION: &str = "ALIEN_SECRET_ENV_REVISION";
24pub const ENV_ALIEN_TRANSPORT: &str = "ALIEN_TRANSPORT";
25pub const ENV_ALIEN_DEPLOYMENT_ID: &str = "ALIEN_DEPLOYMENT_ID";
26pub const ENV_ALIEN_DEPLOYMENT_NAME: &str = "ALIEN_DEPLOYMENT_NAME";
27/// Identifies the current app resource within its deployment stack. Unlike
28/// command-specific target variables, this is the universal resource identity
29/// name.
30pub const ENV_ALIEN_RESOURCE_ID: &str = "ALIEN_RESOURCE_ID";
31pub const ENV_ALIEN_PUBLIC_ENDPOINTS_JSON: &str = "ALIEN_PUBLIC_ENDPOINTS_JSON";
32pub const ENV_ALIEN_COMMANDS_TOKEN: &str = "ALIEN_COMMANDS_TOKEN";
33/// File containing the command receiver bearer token. Receivers re-read this
34/// file after an unauthorized response so controllers can rotate credentials
35/// without restarting the workload.
36pub const ENV_ALIEN_COMMANDS_TOKEN_FILE: &str = "ALIEN_COMMANDS_TOKEN_FILE";
37/// Lease duration requested by app-owned command receivers, in seconds.
38pub const ENV_ALIEN_COMMANDS_LEASE_SECONDS: &str = "ALIEN_COMMANDS_LEASE_SECONDS";
39/// Maximum command leases requested by an app-owned receiver per poll.
40pub const ENV_ALIEN_COMMANDS_MAX_LEASES: &str = "ALIEN_COMMANDS_MAX_LEASES";
41/// Base command receiver poll interval, in milliseconds.
42pub const ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS: &str = "ALIEN_COMMANDS_POLL_INTERVAL_MS";
43/// Maximum command receiver poll interval after adaptive backoff, in milliseconds.
44pub const ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS: &str = "ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS";
45/// Fractional jitter applied to command receiver poll intervals.
46pub const ENV_ALIEN_COMMANDS_POLL_JITTER: &str = "ALIEN_COMMANDS_POLL_JITTER";
47/// Graceful command receiver drain timeout, in milliseconds.
48pub const ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS: &str = "ALIEN_COMMANDS_DRAIN_TIMEOUT_MS";
49/// Identifies which stack resource an app-owned command receiver leases for.
50pub const ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID: &str = "ALIEN_COMMANDS_TARGET_RESOURCE_ID";
51/// Base URL of the command server API an app-owned pull `Receiver`
52/// (Container/Daemon) leases commands from. Pinned by the receiver contract;
53/// the TypeScript receiver reads the same variable. Missing or
54/// invalid values fail fast with `COMMAND_RECEIVER_CONFIG_INVALID`. Injected
55/// by the manager and operator controllers, scoped per command-enabled
56/// resource.
57pub const ENV_ALIEN_COMMANDS_URL: &str = "ALIEN_COMMANDS_URL";
58/// Type of the command target a pull `Receiver` leases for (`container` |
59/// `daemon`). Lease requests require a typed target and a receiver must not
60/// guess it (the worker runtime hardcodes `worker`; a Container/Daemon
61/// receiver gets its type injected). Companion to
62/// [`ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID`].
63pub const ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE: &str = "ALIEN_COMMANDS_TARGET_RESOURCE_TYPE";
64/// Base URL of the deployment's manager.
65pub const ENV_ALIEN_MANAGER_URL: &str = "ALIEN_MANAGER_URL";
66/// Deployment bearer token, distinct from command delivery tokens.
67pub const ENV_ALIEN_DEPLOYMENT_TOKEN: &str = "ALIEN_DEPLOYMENT_TOKEN";
68/// Address of the worker app protocol gRPC server. The runtime binds its
69/// Control + WaitUntil services here and injects the same value for the
70/// application it spawns; the app connects as the gRPC client. Presence of this
71/// variable is what selects the worker-protocol gRPC channel in the app SDK.
72pub const ENV_ALIEN_WORKER_GRPC_ADDRESS: &str = "ALIEN_WORKER_GRPC_ADDRESS";
73/// JSON batch limits keyed by logical queue resource ID.
74pub const ENV_ALIEN_QUEUE_BATCH_CONFIG: &str = "ALIEN_QUEUE_BATCH_CONFIG";
75
76/// Configured maximum Worker execution time in seconds, injected from the trusted resource.
77pub const ENV_ALIEN_WORKER_TIMEOUT_SECONDS: &str = "ALIEN_WORKER_TIMEOUT_SECONDS";
78pub const ENV_AWS_ACCOUNT_ID: &str = "AWS_ACCOUNT_ID";
79pub const ENV_AWS_REGION: &str = "AWS_REGION";
80pub const ENV_AZURE_CLIENT_ID: &str = "AZURE_CLIENT_ID";
81pub const ENV_AZURE_REGION: &str = "AZURE_REGION";
82pub const ENV_AZURE_SUBSCRIPTION_ID: &str = "AZURE_SUBSCRIPTION_ID";
83pub const ENV_AZURE_TENANT_ID: &str = "AZURE_TENANT_ID";
84pub const ENV_GCP_PROJECT_ID: &str = "GCP_PROJECT_ID";
85pub const ENV_GCP_REGION: &str = "GCP_REGION";
86pub const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum RuntimeEnvironmentValue {
90    Literal(&'static str),
91    AwsAccountId,
92    AwsRegion,
93    AzureClientId,
94    AzureRegion,
95    AzureSubscriptionId,
96    AzureTenantId,
97    BasePlatform,
98    CurrentContainerBindingName,
99    CurrentWorkerBindingName,
100    GcpProjectId,
101    GcpRegion,
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct RuntimeEnvironmentEntry {
106    pub name: &'static str,
107    pub value: RuntimeEnvironmentValue,
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum RuntimeEnvironmentBindingSource {
112    LinkedResource(ResourceRef),
113    CurrentContainer,
114    CurrentWorker,
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct RuntimeEnvironmentBindingEntry {
119    pub env_name: String,
120    pub binding_name: String,
121    pub source: RuntimeEnvironmentBindingSource,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum RuntimeEnvironmentPlanEntry {
126    Scalar(RuntimeEnvironmentEntry),
127    Binding(RuntimeEnvironmentBindingEntry),
128}
129
130#[derive(Debug, Clone, Default, PartialEq, Eq)]
131pub struct RuntimeEnvironmentPlan {
132    entries: Vec<RuntimeEnvironmentPlanEntry>,
133}
134
135impl RuntimeEnvironmentPlan {
136    pub fn new() -> Self {
137        Self::default()
138    }
139
140    pub fn add_scalar_entries(
141        mut self,
142        entries: impl IntoIterator<Item = RuntimeEnvironmentEntry>,
143    ) -> Self {
144        self.entries
145            .extend(entries.into_iter().map(RuntimeEnvironmentPlanEntry::Scalar));
146        self
147    }
148
149    pub fn add_linked_bindings(mut self, links: &[ResourceRef]) -> Self {
150        self.entries.extend(links.iter().cloned().map(|link| {
151            let binding_name = link.id().to_string();
152            RuntimeEnvironmentPlanEntry::Binding(RuntimeEnvironmentBindingEntry {
153                env_name: binding_env_var_name(&binding_name),
154                binding_name,
155                source: RuntimeEnvironmentBindingSource::LinkedResource(link),
156            })
157        }));
158        self
159    }
160
161    pub fn add_current_worker_binding(mut self, worker_id: &str) -> Self {
162        self.entries.push(RuntimeEnvironmentPlanEntry::Binding(
163            RuntimeEnvironmentBindingEntry {
164                env_name: binding_env_var_name(worker_id),
165                binding_name: worker_id.to_string(),
166                source: RuntimeEnvironmentBindingSource::CurrentWorker,
167            },
168        ));
169        self
170    }
171
172    pub fn add_current_container_binding(mut self, container_id: &str) -> Self {
173        self.entries.push(RuntimeEnvironmentPlanEntry::Binding(
174            RuntimeEnvironmentBindingEntry {
175                env_name: binding_env_var_name(container_id),
176                binding_name: container_id.to_string(),
177                source: RuntimeEnvironmentBindingSource::CurrentContainer,
178            },
179        ));
180        self
181    }
182
183    pub fn entries(&self) -> &[RuntimeEnvironmentPlanEntry] {
184        &self.entries
185    }
186}
187
188pub trait RuntimeEnvironmentRenderer {
189    type Value;
190
191    fn render_runtime_environment_value(
192        &self,
193        value: RuntimeEnvironmentValue,
194    ) -> Result<Option<Self::Value>>;
195
196    fn render_runtime_environment_binding(
197        &self,
198        entry: &RuntimeEnvironmentBindingEntry,
199    ) -> Result<Option<Self::Value>>;
200}
201
202pub fn standard_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
203    let mut entries = vec![RuntimeEnvironmentEntry {
204        name: ENV_ALIEN_DEPLOYMENT_TYPE,
205        value: RuntimeEnvironmentValue::Literal(platform.as_str()),
206    }];
207
208    match platform {
209        Platform::Aws => entries.push(RuntimeEnvironmentEntry {
210            name: ENV_AWS_ACCOUNT_ID,
211            value: RuntimeEnvironmentValue::AwsAccountId,
212        }),
213        Platform::Gcp => entries.extend([
214            RuntimeEnvironmentEntry {
215                name: ENV_GOOGLE_CLOUD_PROJECT,
216                value: RuntimeEnvironmentValue::GcpProjectId,
217            },
218            RuntimeEnvironmentEntry {
219                name: ENV_GCP_PROJECT_ID,
220                value: RuntimeEnvironmentValue::GcpProjectId,
221            },
222            RuntimeEnvironmentEntry {
223                name: ENV_GCP_REGION,
224                value: RuntimeEnvironmentValue::GcpRegion,
225            },
226        ]),
227        Platform::Azure => entries.extend([
228            RuntimeEnvironmentEntry {
229                name: ENV_AZURE_SUBSCRIPTION_ID,
230                value: RuntimeEnvironmentValue::AzureSubscriptionId,
231            },
232            RuntimeEnvironmentEntry {
233                name: ENV_AZURE_TENANT_ID,
234                value: RuntimeEnvironmentValue::AzureTenantId,
235            },
236            RuntimeEnvironmentEntry {
237                name: ENV_AZURE_REGION,
238                value: RuntimeEnvironmentValue::AzureRegion,
239            },
240        ]),
241        Platform::Kubernetes => entries.push(RuntimeEnvironmentEntry {
242            name: ENV_OPERATOR_BASE_PLATFORM,
243            value: RuntimeEnvironmentValue::BasePlatform,
244        }),
245        Platform::Machines | Platform::Local | Platform::Test => {}
246    }
247
248    entries
249}
250
251pub fn kubernetes_base_platform_runtime_environment_plan(
252    base_platform: Option<Platform>,
253) -> Vec<RuntimeEnvironmentEntry> {
254    match base_platform {
255        Some(Platform::Aws) => vec![
256            RuntimeEnvironmentEntry {
257                name: ENV_AWS_ACCOUNT_ID,
258                value: RuntimeEnvironmentValue::AwsAccountId,
259            },
260            RuntimeEnvironmentEntry {
261                name: ENV_AWS_REGION,
262                value: RuntimeEnvironmentValue::AwsRegion,
263            },
264        ],
265        Some(Platform::Gcp) => vec![
266            RuntimeEnvironmentEntry {
267                name: ENV_GOOGLE_CLOUD_PROJECT,
268                value: RuntimeEnvironmentValue::GcpProjectId,
269            },
270            RuntimeEnvironmentEntry {
271                name: ENV_GCP_PROJECT_ID,
272                value: RuntimeEnvironmentValue::GcpProjectId,
273            },
274            RuntimeEnvironmentEntry {
275                name: ENV_GCP_REGION,
276                value: RuntimeEnvironmentValue::GcpRegion,
277            },
278        ],
279        Some(Platform::Azure) => vec![
280            RuntimeEnvironmentEntry {
281                name: ENV_AZURE_SUBSCRIPTION_ID,
282                value: RuntimeEnvironmentValue::AzureSubscriptionId,
283            },
284            RuntimeEnvironmentEntry {
285                name: ENV_AZURE_TENANT_ID,
286                value: RuntimeEnvironmentValue::AzureTenantId,
287            },
288            RuntimeEnvironmentEntry {
289                name: ENV_AZURE_REGION,
290                value: RuntimeEnvironmentValue::AzureRegion,
291            },
292            RuntimeEnvironmentEntry {
293                name: ENV_AZURE_CLIENT_ID,
294                value: RuntimeEnvironmentValue::AzureClientId,
295            },
296        ],
297        _ => Vec::new(),
298    }
299}
300
301pub fn worker_transport_runtime_environment_plan(
302    platform: Platform,
303) -> Vec<RuntimeEnvironmentEntry> {
304    match platform {
305        Platform::Aws => vec![
306            RuntimeEnvironmentEntry {
307                name: ENV_ALIEN_TRANSPORT,
308                value: RuntimeEnvironmentValue::Literal("lambda"),
309            },
310            RuntimeEnvironmentEntry {
311                name: ENV_ALIEN_LAMBDA_MODE,
312                value: RuntimeEnvironmentValue::Literal("buffered"),
313            },
314        ],
315        Platform::Gcp => vec![RuntimeEnvironmentEntry {
316            name: ENV_ALIEN_TRANSPORT,
317            value: RuntimeEnvironmentValue::Literal("cloud-run"),
318        }],
319        Platform::Azure => vec![RuntimeEnvironmentEntry {
320            name: ENV_ALIEN_TRANSPORT,
321            value: RuntimeEnvironmentValue::Literal("container-app"),
322        }],
323        Platform::Kubernetes | Platform::Machines => vec![RuntimeEnvironmentEntry {
324            name: ENV_ALIEN_TRANSPORT,
325            value: RuntimeEnvironmentValue::Literal("http"),
326        }],
327        Platform::Local | Platform::Test => vec![RuntimeEnvironmentEntry {
328            name: ENV_ALIEN_TRANSPORT,
329            // Local/Test Workers run under the runtime's `local` transport (the
330            // in-process HTTP invocation proxy the worker manager selects via
331            // `TransportType::Local`). The env-plan value now matches that reality,
332            // so `ALIEN_TRANSPORT` for Workers is exactly the transport set
333            // `lambda | cloud-run | container-app | http | local`.
334            value: RuntimeEnvironmentValue::Literal("local"),
335        }],
336    }
337}
338
339pub fn worker_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
340    let mut entries = standard_runtime_environment_plan(platform);
341    entries.extend(worker_transport_runtime_environment_plan(platform));
342    entries.push(RuntimeEnvironmentEntry {
343        name: ENV_ALIEN_RUNTIME_SEND_OTLP,
344        value: RuntimeEnvironmentValue::Literal("true"),
345    });
346    entries.push(RuntimeEnvironmentEntry {
347        name: ENV_ALIEN_CURRENT_WORKER_BINDING_NAME,
348        value: RuntimeEnvironmentValue::CurrentWorkerBindingName,
349    });
350    if platform == Platform::Azure {
351        entries.push(RuntimeEnvironmentEntry {
352            name: ENV_AZURE_CLIENT_ID,
353            value: RuntimeEnvironmentValue::AzureClientId,
354        });
355    }
356    entries
357}
358
359pub fn worker_runtime_environment_contract(
360    platform: Platform,
361    worker_id: &str,
362    links: &[ResourceRef],
363) -> RuntimeEnvironmentPlan {
364    RuntimeEnvironmentPlan::new()
365        .add_scalar_entries(worker_runtime_environment_plan(platform))
366        .add_linked_bindings(links)
367        .add_current_worker_binding(worker_id)
368}
369
370pub fn container_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
371    let mut entries = standard_runtime_environment_plan(platform);
372    // `ALIEN_TRANSPORT` is Worker-only. Command-enabled Containers run the pull
373    // receiver configured per resource through the `ALIEN_COMMANDS_*` contract.
374    entries.push(RuntimeEnvironmentEntry {
375        name: ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME,
376        value: RuntimeEnvironmentValue::CurrentContainerBindingName,
377    });
378    entries
379}
380
381pub fn container_runtime_environment_contract(
382    platform: Platform,
383    container_id: &str,
384    links: &[ResourceRef],
385) -> RuntimeEnvironmentPlan {
386    RuntimeEnvironmentPlan::new()
387        .add_scalar_entries(container_runtime_environment_plan(platform))
388        .add_linked_bindings(links)
389        .add_current_container_binding(container_id)
390}
391
392pub fn daemon_runtime_environment_plan(platform: Platform) -> Vec<RuntimeEnvironmentEntry> {
393    // Daemons run under direct supervision and receive only the standard
394    // platform-identity vars. `ALIEN_TRANSPORT` and the container self-binding
395    // var are not part of the Daemon contract. Command-enabled Daemons get their
396    // `ALIEN_COMMANDS_*` receiver config from the resource controller.
397    standard_runtime_environment_plan(platform)
398}
399
400pub fn daemon_runtime_environment_contract(
401    platform: Platform,
402    links: &[ResourceRef],
403) -> RuntimeEnvironmentPlan {
404    RuntimeEnvironmentPlan::new()
405        .add_scalar_entries(daemon_runtime_environment_plan(platform))
406        .add_linked_bindings(links)
407}
408
409pub fn render_runtime_environment_entries<R>(
410    entries: impl IntoIterator<Item = RuntimeEnvironmentEntry>,
411    renderer: &R,
412) -> Result<Vec<(&'static str, R::Value)>>
413where
414    R: RuntimeEnvironmentRenderer,
415{
416    let mut rendered = Vec::new();
417    for entry in entries {
418        if let Some(value) = renderer.render_runtime_environment_value(entry.value)? {
419            rendered.push((entry.name, value));
420        }
421    }
422    Ok(rendered)
423}
424
425pub fn render_runtime_environment_plan<R>(
426    plan: &RuntimeEnvironmentPlan,
427    renderer: &R,
428) -> Result<Vec<(String, R::Value)>>
429where
430    R: RuntimeEnvironmentRenderer,
431{
432    let mut rendered = Vec::new();
433    for entry in plan.entries() {
434        match entry {
435            RuntimeEnvironmentPlanEntry::Scalar(entry) => {
436                if let Some(value) = renderer.render_runtime_environment_value(entry.value)? {
437                    rendered.push((entry.name.to_string(), value));
438                }
439            }
440            RuntimeEnvironmentPlanEntry::Binding(entry) => {
441                if let Some(value) = renderer.render_runtime_environment_binding(entry)? {
442                    rendered.push((entry.env_name.clone(), value));
443                }
444            }
445        }
446    }
447    Ok(rendered)
448}
449
450pub fn is_runtime_environment_contract_name(name: &str) -> bool {
451    matches!(
452        name,
453        ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME
454            | ENV_ALIEN_CURRENT_WORKER_BINDING_NAME
455            | ENV_OPERATOR_BASE_PLATFORM
456            | ENV_ALIEN_DEPLOYMENT_TYPE
457            | ENV_ALIEN_LAMBDA_MODE
458            | ENV_ALIEN_RUNTIME_SEND_OTLP
459            | ENV_ALIEN_TRANSPORT
460            | ENV_AWS_ACCOUNT_ID
461            | ENV_AWS_REGION
462            | ENV_AZURE_CLIENT_ID
463            | ENV_AZURE_REGION
464            | ENV_AZURE_SUBSCRIPTION_ID
465            | ENV_AZURE_TENANT_ID
466            | ENV_GCP_PROJECT_ID
467            | ENV_GCP_REGION
468            | ENV_GOOGLE_CLOUD_PROJECT
469    ) || (name.starts_with("ALIEN_") && name.ends_with("_BINDING"))
470}
471
472pub fn is_reserved_runtime_environment_name(name: &str) -> bool {
473    is_runtime_environment_contract_name(name)
474        || matches!(
475            name,
476            ENV_ALIEN_WORKER_GRPC_ADDRESS
477                | ENV_ALIEN_QUEUE_BATCH_CONFIG
478                | ENV_ALIEN_WORKER_TIMEOUT_SECONDS
479                | ENV_ALIEN_COMMANDS_TOKEN
480                | ENV_ALIEN_COMMANDS_TOKEN_FILE
481                | ENV_ALIEN_COMMANDS_LEASE_SECONDS
482                | ENV_ALIEN_COMMANDS_MAX_LEASES
483                | ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS
484                | ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS
485                | ENV_ALIEN_COMMANDS_POLL_JITTER
486                | ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS
487                | ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID
488                | ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE
489                | ENV_ALIEN_COMMANDS_URL
490                | ENV_ALIEN_DEPLOYMENT_ID
491                | ENV_ALIEN_DEPLOYMENT_NAME
492                | "ALIEN_DEPLOYMENT_SERVICE_ACCOUNT"
493                | ENV_ALIEN_DEPLOYMENT_TOKEN
494                | ENV_ALIEN_MANAGER_URL
495                | ENV_ALIEN_RESOURCE_ID
496                | ENV_ALIEN_PUBLIC_ENDPOINTS_JSON
497                | ENV_ALIEN_RUNTIME_SECRETS
498                | ENV_ALIEN_SECRET_ENV_REVISION
499                | ENV_ALIEN_SECRETS
500        )
501        || name.starts_with("ALIEN_BINDING_")
502}
503
504pub fn validate_runtime_environment_user_vars<'a>(
505    names: impl IntoIterator<Item = &'a str>,
506) -> Result<()> {
507    let reserved: Vec<String> = names
508        .into_iter()
509        .filter(|name| is_reserved_runtime_environment_name(name))
510        .map(ToString::to_string)
511        .collect();
512    if reserved.is_empty() {
513        return Ok(());
514    }
515
516    Err(AlienError::new(ErrorData::GenericError {
517        message: format!(
518            "Environment variables use reserved Alien runtime names: {}",
519            reserved.join(", ")
520        ),
521    }))
522}
523
524pub fn validate_runtime_environment_user_map(env: &HashMap<String, String>) -> Result<()> {
525    validate_runtime_environment_user_vars(env.keys().map(String::as_str))
526}
527
528pub fn validate_prepared_runtime_environment_vars<'a>(
529    names: impl IntoIterator<Item = &'a str>,
530) -> Result<()> {
531    let reserved: Vec<String> = names
532        .into_iter()
533        .filter(|name| is_runtime_environment_contract_name(name))
534        .map(ToString::to_string)
535        .collect();
536    if reserved.is_empty() {
537        return Ok(());
538    }
539
540    Err(AlienError::new(ErrorData::GenericError {
541        message: format!(
542            "Environment variables collide with Alien runtime contract names: {}",
543            reserved.join(", ")
544        ),
545    }))
546}
547
548pub fn validate_prepared_runtime_environment_map(env: &HashMap<String, String>) -> Result<()> {
549    validate_prepared_runtime_environment_vars(env.keys().map(String::as_str))
550}
551
552#[cfg(test)]
553mod tests {
554    use super::*;
555
556    #[test]
557    fn reserves_builtin_and_binding_environment_names() {
558        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_TRANSPORT));
559        assert!(is_reserved_runtime_environment_name(
560            ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME
561        ));
562        assert!(is_reserved_runtime_environment_name(
563            ENV_OPERATOR_BASE_PLATFORM
564        ));
565        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_SECRETS));
566        assert!(is_reserved_runtime_environment_name(
567            ENV_ALIEN_SECRET_ENV_REVISION
568        ));
569        assert!(is_reserved_runtime_environment_name(
570            ENV_ALIEN_WORKER_GRPC_ADDRESS
571        ));
572        assert_eq!(ENV_ALIEN_WORKER_GRPC_ADDRESS, "ALIEN_WORKER_GRPC_ADDRESS");
573        assert!(is_reserved_runtime_environment_name(
574            ENV_ALIEN_WORKER_TIMEOUT_SECONDS
575        ));
576        assert_eq!(
577            ENV_ALIEN_WORKER_TIMEOUT_SECONDS,
578            "ALIEN_WORKER_TIMEOUT_SECONDS"
579        );
580        assert!(is_reserved_runtime_environment_name(
581            "ALIEN_STORAGE_BINDING"
582        ));
583        assert!(is_reserved_runtime_environment_name(
584            "ALIEN_BINDING_STORAGE_URL"
585        ));
586        assert!(!is_reserved_runtime_environment_name("USER_DEFINED"));
587    }
588
589    #[test]
590    fn reserves_deployment_identity_names() {
591        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_MANAGER_URL));
592        assert!(is_reserved_runtime_environment_name(
593            ENV_ALIEN_DEPLOYMENT_TOKEN
594        ));
595        assert!(is_reserved_runtime_environment_name(
596            "ALIEN_DEPLOYMENT_SERVICE_ACCOUNT"
597        ));
598        assert!(is_reserved_runtime_environment_name(ENV_ALIEN_RESOURCE_ID));
599        assert_eq!(ENV_ALIEN_MANAGER_URL, "ALIEN_MANAGER_URL");
600        assert_eq!(ENV_ALIEN_DEPLOYMENT_TOKEN, "ALIEN_DEPLOYMENT_TOKEN");
601        assert_eq!(ENV_ALIEN_RESOURCE_ID, "ALIEN_RESOURCE_ID");
602    }
603
604    #[test]
605    fn reserves_commands_target_resource_id() {
606        assert!(is_reserved_runtime_environment_name(
607            ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID
608        ));
609        assert_eq!(
610            ENV_ALIEN_COMMANDS_TARGET_RESOURCE_ID,
611            "ALIEN_COMMANDS_TARGET_RESOURCE_ID"
612        );
613    }
614
615    #[test]
616    fn reserves_command_receiver_names() {
617        for (constant, expected) in [
618            (ENV_ALIEN_COMMANDS_URL, "ALIEN_COMMANDS_URL"),
619            (ENV_ALIEN_COMMANDS_TOKEN_FILE, "ALIEN_COMMANDS_TOKEN_FILE"),
620            (
621                ENV_ALIEN_COMMANDS_LEASE_SECONDS,
622                "ALIEN_COMMANDS_LEASE_SECONDS",
623            ),
624            (ENV_ALIEN_COMMANDS_MAX_LEASES, "ALIEN_COMMANDS_MAX_LEASES"),
625            (
626                ENV_ALIEN_COMMANDS_POLL_INTERVAL_MS,
627                "ALIEN_COMMANDS_POLL_INTERVAL_MS",
628            ),
629            (
630                ENV_ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS,
631                "ALIEN_COMMANDS_POLL_MAX_INTERVAL_MS",
632            ),
633            (ENV_ALIEN_COMMANDS_POLL_JITTER, "ALIEN_COMMANDS_POLL_JITTER"),
634            (
635                ENV_ALIEN_COMMANDS_DRAIN_TIMEOUT_MS,
636                "ALIEN_COMMANDS_DRAIN_TIMEOUT_MS",
637            ),
638            (
639                ENV_ALIEN_COMMANDS_TARGET_RESOURCE_TYPE,
640                "ALIEN_COMMANDS_TARGET_RESOURCE_TYPE",
641            ),
642        ] {
643            assert_eq!(constant, expected);
644            assert!(is_reserved_runtime_environment_name(constant));
645        }
646    }
647
648    #[test]
649    fn rejects_reserved_user_environment_names() {
650        let error = validate_runtime_environment_user_vars(["USER_DEFINED", ENV_ALIEN_TRANSPORT])
651            .unwrap_err();
652
653        assert!(error.to_string().contains(ENV_ALIEN_TRANSPORT));
654    }
655
656    #[test]
657    fn prepared_environment_allows_deployment_managed_names() {
658        validate_prepared_runtime_environment_vars([
659            ENV_ALIEN_SECRETS,
660            ENV_ALIEN_DEPLOYMENT_ID,
661            ENV_ALIEN_DEPLOYMENT_NAME,
662            ENV_ALIEN_PUBLIC_ENDPOINTS_JSON,
663        ])
664        .unwrap();
665
666        let error =
667            validate_prepared_runtime_environment_vars([ENV_ALIEN_SECRETS, ENV_ALIEN_TRANSPORT])
668                .unwrap_err();
669
670        assert!(error.to_string().contains(ENV_ALIEN_TRANSPORT));
671        assert!(!error.to_string().contains(ENV_ALIEN_SECRETS));
672    }
673
674    #[test]
675    fn kubernetes_standard_environment_declares_base_platform() {
676        let entries = standard_runtime_environment_plan(Platform::Kubernetes);
677
678        assert!(entries.iter().any(|entry| {
679            entry.name == ENV_OPERATOR_BASE_PLATFORM
680                && entry.value == RuntimeEnvironmentValue::BasePlatform
681        }));
682    }
683
684    #[test]
685    fn kubernetes_gcp_base_environment_declares_gcp_identity() {
686        let entries = kubernetes_base_platform_runtime_environment_plan(Some(Platform::Gcp));
687
688        assert!(entries.iter().any(|entry| {
689            entry.name == ENV_GOOGLE_CLOUD_PROJECT
690                && entry.value == RuntimeEnvironmentValue::GcpProjectId
691        }));
692        assert!(entries.iter().any(|entry| {
693            entry.name == ENV_GCP_PROJECT_ID && entry.value == RuntimeEnvironmentValue::GcpProjectId
694        }));
695        assert!(entries.iter().any(|entry| {
696            entry.name == ENV_GCP_REGION && entry.value == RuntimeEnvironmentValue::GcpRegion
697        }));
698    }
699
700    #[test]
701    fn kubernetes_worker_environment_uses_http_proxy_transport() {
702        let entries = worker_transport_runtime_environment_plan(Platform::Kubernetes);
703
704        assert!(entries.iter().any(|entry| {
705            entry.name == ENV_ALIEN_TRANSPORT
706                && entry.value == RuntimeEnvironmentValue::Literal("http")
707        }));
708    }
709
710    #[test]
711    fn container_environment_does_not_inject_worker_transport() {
712        for platform in [
713            Platform::Local,
714            Platform::Kubernetes,
715            Platform::Aws,
716            Platform::Gcp,
717            Platform::Azure,
718            Platform::Test,
719        ] {
720            let entries = container_runtime_environment_plan(platform);
721            assert!(
722                !entries
723                    .iter()
724                    .any(|entry| entry.name == ENV_ALIEN_TRANSPORT),
725                "container plan for {platform:?} must not set ALIEN_TRANSPORT"
726            );
727            // The container binding-name var is still present.
728            assert!(
729                entries
730                    .iter()
731                    .any(|entry| entry.name == ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME),
732                "container plan for {platform:?} must still declare the binding-name var"
733            );
734        }
735    }
736
737    #[test]
738    fn daemon_environment_is_standard_identity_only() {
739        // Daemons use the standard platform-identity set. Receiver config is
740        // injected per resource, not by the static environment plan.
741        for platform in [
742            Platform::Local,
743            Platform::Kubernetes,
744            Platform::Aws,
745            Platform::Gcp,
746            Platform::Azure,
747            Platform::Test,
748        ] {
749            let entries = daemon_runtime_environment_plan(platform);
750            assert!(
751                !entries
752                    .iter()
753                    .any(|entry| entry.name == ENV_ALIEN_TRANSPORT),
754                "daemon plan for {platform:?} must not set ALIEN_TRANSPORT"
755            );
756            assert!(
757                !entries
758                    .iter()
759                    .any(|entry| entry.name == ENV_ALIEN_CURRENT_CONTAINER_BINDING_NAME),
760                "daemon plan for {platform:?} must not set the container self-binding var"
761            );
762            // The standard deployment-type identity var is always present.
763            assert!(
764                entries
765                    .iter()
766                    .any(|entry| entry.name == ENV_ALIEN_DEPLOYMENT_TYPE),
767                "daemon plan for {platform:?} must declare ALIEN_DEPLOYMENT_TYPE"
768            );
769        }
770    }
771
772    #[test]
773    fn worker_local_transport_uses_local_proxy() {
774        // Local/Test Workers run under `TransportType::Local`, selected by the
775        // Worker manager.
776        for platform in [Platform::Local, Platform::Test] {
777            let entries = worker_transport_runtime_environment_plan(platform);
778            assert!(entries.iter().any(|entry| {
779                entry.name == ENV_ALIEN_TRANSPORT
780                    && entry.value == RuntimeEnvironmentValue::Literal("local")
781            }));
782        }
783    }
784}