Skip to main content

alien_core/resources/
worker.rs

1use crate::error::{ErrorData, Result};
2use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
3use crate::{PublicEndpointOutput, WorkerPublicEndpoint, APEX_HOST_LABEL};
4use alien_error::{AlienError, Context, IntoAlienError};
5use bon::Builder;
6use serde::{Deserialize, Serialize};
7use std::any::Any;
8use std::collections::HashMap;
9use std::fmt::Debug;
10
11/// Specifies the source of the worker's executable code.
12/// This can be a pre-built container image or source code that the system will build.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
15#[serde(rename_all = "camelCase", tag = "type")]
16pub enum WorkerCode {
17    /// Container image.
18    #[serde(rename_all = "camelCase")]
19    Image {
20        /// Container image (e.g., `ghcr.io/myorg/myimage:latest`).
21        image: String,
22    },
23    /// Source code to be built.
24    #[serde(rename_all = "camelCase")]
25    Source {
26        /// The source directory to build from
27        src: String,
28        /// Toolchain configuration with type-safe options
29        toolchain: ToolchainConfig,
30    },
31}
32
33/// Configuration for different programming language toolchains.
34/// Each toolchain provides type-safe build configuration and auto-detection capabilities.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
37#[serde(rename_all = "lowercase", tag = "type")]
38pub enum ToolchainConfig {
39    /// Rust with Cargo build system
40    #[serde(rename_all = "camelCase")]
41    Rust {
42        /// Name of the binary to build and run
43        binary_name: String,
44    },
45    /// TypeScript/JavaScript compiled to single executable with Bun
46    #[serde(rename_all = "camelCase")]
47    TypeScript {
48        /// Name of the compiled binary (defaults to package.json name if not specified)
49        #[serde(default, skip_serializing_if = "Option::is_none")]
50        binary_name: Option<String>,
51    },
52    /// Python application installed from a locked uv project
53    #[serde(rename_all = "camelCase")]
54    Python {
55        /// Python version used by the runtime image (defaults to 3.12)
56        #[serde(default, skip_serializing_if = "Option::is_none")]
57        python_version: Option<String>,
58        /// Workspace package to install (omit for a single-package project)
59        #[serde(default, skip_serializing_if = "Option::is_none")]
60        package: Option<String>,
61        /// Process argv used to start the application
62        command: Vec<String>,
63    },
64    /// Docker build from Dockerfile
65    #[serde(rename_all = "camelCase")]
66    Docker {
67        /// Dockerfile path relative to src (default: "Dockerfile")
68        #[serde(skip_serializing_if = "Option::is_none")]
69        dockerfile: Option<String>,
70        /// Build arguments for docker build
71        #[serde(skip_serializing_if = "Option::is_none")]
72        build_args: Option<HashMap<String, String>>,
73        /// Multi-stage build target
74        #[serde(skip_serializing_if = "Option::is_none")]
75        target: Option<String>,
76    },
77}
78
79/// Opt-in queue batching. Counts and windows are upper bounds, not guarantees.
80/// Providers may deliver smaller batches. Delivery remains at least once and unordered.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
83#[serde(rename_all = "camelCase", deny_unknown_fields)]
84pub struct QueueBatchConfig {
85    /// Maximum deliveries per batch (1–100).
86    #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 100))]
87    pub max_messages: u32,
88    /// Maximum collection window in seconds (0–300).
89    /// AWS may wait up to 20 seconds with sparse traffic even with a shorter window.
90    #[cfg_attr(feature = "openapi", schema(minimum = 0, maximum = 300))]
91    pub max_window_seconds: u32,
92}
93
94impl QueueBatchConfig {
95    /// Reject settings outside the portable range.
96    pub fn validate(&self) -> Result<()> {
97        if !(1..=100).contains(&self.max_messages)
98            || self.max_window_seconds > 300
99            || (self.max_messages > 10 && self.max_window_seconds == 0)
100        {
101            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
102                resource_id: "queue trigger".to_string(),
103                reason: "batch maxMessages must be 1–100, maxWindowSeconds 0–300, and counts above 10 require a nonzero window".to_string(),
104            }));
105        }
106        Ok(())
107    }
108}
109
110fn deserialize_queue_batch<'de, D>(
111    deserializer: D,
112) -> std::result::Result<Option<QueueBatchConfig>, D::Error>
113where
114    D: serde::Deserializer<'de>,
115{
116    let batch = Option::<QueueBatchConfig>::deserialize(deserializer)?;
117    if let Some(batch) = &batch {
118        batch.validate().map_err(serde::de::Error::custom)?;
119    }
120    Ok(batch)
121}
122
123/// Defines what triggers a worker execution.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
126#[serde(tag = "type", rename_all = "camelCase")]
127pub enum WorkerTrigger {
128    /// Worker triggered by queue messages. Single delivery unless batching is configured.
129    Queue {
130        /// Reference to the queue resource
131        queue: ResourceRef,
132        /// Optional batch delivery configuration; omitted preserves single-message handlers.
133        #[serde(
134            default,
135            skip_serializing_if = "Option::is_none",
136            deserialize_with = "deserialize_queue_batch"
137        )]
138        batch: Option<QueueBatchConfig>,
139    },
140    /// Worker triggered by storage events (object created, deleted, etc.)
141    Storage {
142        /// Reference to the storage resource
143        storage: ResourceRef,
144        /// Events to trigger on (e.g., ["created", "deleted"])
145        events: Vec<String>,
146    },
147    /// Worker triggered on a schedule (cron expression)
148    Schedule {
149        /// Cron expression for scheduling (standard 5-field unix cron)
150        cron: String,
151    },
152}
153
154impl WorkerTrigger {
155    /// Creates a queue trigger for the specified queue resource.
156    /// The worker will be automatically invoked when messages arrive in the queue.
157    /// Each message is processed individually (batch size of 1).
158    pub fn queue<R: ?Sized>(queue: &R) -> Self
159    where
160        for<'a> &'a R: Into<ResourceRef>,
161    {
162        let queue_ref: ResourceRef = queue.into();
163        WorkerTrigger::Queue {
164            queue: queue_ref,
165            batch: None,
166        }
167    }
168
169    /// Creates an opt-in batch trigger after validating portable limits.
170    pub fn queue_batch<R: ?Sized>(queue: &R, batch: QueueBatchConfig) -> Result<Self>
171    where
172        for<'a> &'a R: Into<ResourceRef>,
173    {
174        batch.validate()?;
175        Ok(Self::Queue {
176            queue: queue.into(),
177            batch: Some(batch),
178        })
179    }
180
181    /// Creates a storage trigger for the specified storage resource.
182    /// The worker will be invoked when matching events occur on the storage resource.
183    pub fn storage<R: ?Sized>(storage: &R, events: Vec<String>) -> Self
184    where
185        for<'a> &'a R: Into<ResourceRef>,
186    {
187        let storage_ref: ResourceRef = storage.into();
188        WorkerTrigger::Storage {
189            storage: storage_ref,
190            events,
191        }
192    }
193
194    /// Creates a schedule trigger with the specified cron expression.
195    /// Uses standard 5-field unix cron format (minute hour day-of-month month day-of-week).
196    pub fn schedule<S: Into<String>>(cron: S) -> Self {
197        WorkerTrigger::Schedule { cron: cron.into() }
198    }
199}
200
201/// Represents a serverless worker that executes code in response to triggers or direct invocations.
202/// Workers are the primary compute resource in serverless applications, designed to be stateless and ephemeral.
203#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
204#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
205#[serde(rename_all = "camelCase", deny_unknown_fields)]
206#[builder(start_fn = new)]
207pub struct Worker {
208    /// Identifier for the worker. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
209    /// Maximum 64 characters.
210    #[builder(start_fn)]
211    pub id: String,
212
213    /// List of resource references this worker depends on.
214    // TODO: We need to verify that the same link isn't added multiple times.
215    #[builder(field)]
216    pub links: Vec<ResourceRef>,
217
218    /// List of triggers that define what events automatically invoke this worker.
219    /// If empty, the worker is only invokable directly via HTTP calls or platform-specific invocation APIs.
220    /// When configured, the worker will be automatically invoked when any of the specified trigger conditions are met.
221    #[builder(field)]
222    pub triggers: Vec<WorkerTrigger>,
223
224    /// Public endpoints exposed by this worker.
225    #[builder(field)]
226    #[serde(default, skip_serializing_if = "Vec::is_empty")]
227    pub public_endpoints: Vec<WorkerPublicEndpoint>,
228
229    /// Permission profile name that defines the permissions granted to this worker.
230    /// This references a profile defined in the stack's permission definitions.
231    pub permissions: String,
232
233    /// Code for the worker, either a pre-built image or source code to be built.
234    pub code: WorkerCode,
235
236    /// Kubernetes Pod Security profile. Absent means no pod security
237    /// settings are applied and the image runs as built; set
238    /// `profile: restricted` to apply the restricted profile. Other
239    /// platforms ignore it.
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub security: Option<crate::ContainerSecurity>,
242
243    /// Memory allocated to the worker in megabytes (MB).
244    /// Default: 512
245    ///
246    /// Platform-specific constraints:
247    /// - **AWS Lambda**: 128–10240 MB in 1 MB increments
248    /// - **GCP Cloud Run**: 128–32768 MB
249    /// - **Azure Container Apps**: fixed CPU/memory pairs — 512, 1024, 1536, 2048, 2560,
250    ///   3072, 3584, 4096 MB. Values below 512 are automatically rounded up at deploy time.
251    #[builder(default = default_memory_mb())]
252    #[serde(default = "default_memory_mb")]
253    #[cfg_attr(feature = "openapi", schema(default = default_memory_mb))]
254    pub memory_mb: u32,
255
256    /// Maximum execution time for the worker in seconds.
257    /// Constraints: 1‑3600 seconds (platform-specific limits may apply)
258    /// Default: 180
259    #[builder(
260        default = default_timeout_seconds(),
261        with = |timeout_seconds: u32| -> crate::Result<_> {
262            validate_timeout_seconds(timeout_seconds)
263        }
264    )]
265    #[serde(
266        default = "default_timeout_seconds",
267        deserialize_with = "deserialize_timeout_seconds"
268    )]
269    #[cfg_attr(
270        feature = "openapi",
271        schema(default = default_timeout_seconds, minimum = 1, maximum = 3600)
272    )]
273    pub timeout_seconds: u32,
274
275    /// Key-value pairs to set as environment variables for the worker.
276    #[builder(default)]
277    #[serde(default)]
278    pub environment: HashMap<String, String>,
279
280    /// Whether the worker can receive remote commands via the Commands protocol.
281    /// When enabled, the platform pushes commands into the Worker runtime,
282    /// which executes registered handlers.
283    #[builder(default = default_commands_enabled())]
284    #[serde(default = "default_commands_enabled")]
285    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
286    pub commands_enabled: bool,
287
288    /// Maximum number of concurrent executions allowed for the worker.
289    /// None means platform default applies.
290    pub concurrency_limit: Option<u32>,
291
292    /// Optional readiness probe configuration.
293    /// Only applicable for workers with Public ingress.
294    /// When configured, the probe will be executed after provisioning/update to verify the worker is ready.
295    pub readiness_probe: Option<ReadinessProbe>,
296
297    /// Set by `alien build` when the Worker image was built on a runtime that
298    /// exchanges its cloud identity for telemetry credentials. Absent means the
299    /// image may be older and still reads `ALIEN_RUNTIME_SECRETS`, so a deployer
300    /// in identity mode keeps providing them. Build output replaces any value
301    /// written in the stack definition.
302    #[builder(default)]
303    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
304    pub runtime_identity_exchange: bool,
305}
306
307impl Worker {
308    /// The resource type identifier for Workers
309    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("worker");
310
311    /// Bindings needed by explicit links and queue delivery source routing.
312    pub fn runtime_binding_links(&self) -> Vec<ResourceRef> {
313        let mut links = self.links.clone();
314        for trigger in &self.triggers {
315            if let WorkerTrigger::Queue {
316                queue,
317                batch: Some(_),
318            } = trigger
319            {
320                if !links.contains(queue) {
321                    links.push(queue.clone());
322                }
323            }
324        }
325        links
326    }
327
328    /// Whether the worker explicitly opts into queue batching.
329    pub fn has_queue_batches(&self) -> bool {
330        self.triggers
331            .iter()
332            .any(|trigger| matches!(trigger, WorkerTrigger::Queue { batch: Some(_), .. }))
333    }
334
335    /// Batch routing is emitted only for workers that explicitly opt into batching.
336    pub fn queue_batch_environment(&self) -> Result<Option<String>> {
337        if !self.has_queue_batches() {
338            return Ok(None);
339        }
340        let mut batches = std::collections::BTreeMap::new();
341        for trigger in &self.triggers {
342            if let WorkerTrigger::Queue { queue, batch } = trigger {
343                if let Some(batch) = batch {
344                    batch.validate()?;
345                }
346                if batches.insert(&queue.id, batch).is_some() {
347                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
348                        resource_id: self.id.clone(),
349                        reason: "Duplicate queue trigger".into(),
350                    }));
351                }
352            }
353        }
354        if batches.is_empty() {
355            return Ok(None);
356        }
357        serde_json::to_string(&batches)
358            .map(Some)
359            .into_alien_error()
360            .context(ErrorData::GenericError {
361                message: "Failed to serialize queue batch configuration".into(),
362            })
363    }
364
365    /// Batch settings for a queue trigger, absent for legacy single-message delivery.
366    pub fn queue_batch_config(&self, queue_id: &str) -> Option<&QueueBatchConfig> {
367        self.triggers.iter().find_map(|trigger| match trigger {
368            WorkerTrigger::Queue { queue, batch } if queue.id == queue_id => batch.as_ref(),
369            _ => None,
370        })
371    }
372
373    /// Allocate SQS admission across queue mappings. Commands invoke Lambda directly.
374    /// AWS requires at least two per mapping. Below that threshold the function's
375    /// reserved concurrency remains the compute cap; it is not a distributed lock.
376    pub fn queue_source_maximum_concurrency(&self) -> Option<u32> {
377        if !self.has_queue_batches() {
378            return None;
379        }
380        let sources = self
381            .triggers
382            .iter()
383            .filter(|trigger| matches!(trigger, WorkerTrigger::Queue { .. }))
384            .count() as u32;
385        let capacity = self.concurrency_limit?.checked_div(sources)?;
386        (capacity >= 2).then_some(capacity.min(1000))
387    }
388
389    /// Returns the permission profile name for this worker.
390    pub fn get_permissions(&self) -> &str {
391        &self.permissions
392    }
393
394    /// The URL `urls` assigns to this worker's primary public endpoint, the first one
395    /// it declares. See [`crate::primary_public_endpoint_url`].
396    pub fn configured_primary_public_url(
397        &self,
398        urls: Option<&crate::PublicEndpointUrls>,
399    ) -> Option<String> {
400        let first_declared_endpoint = self
401            .public_endpoints
402            .first()
403            .map(|endpoint| endpoint.name.as_str());
404        crate::primary_public_endpoint_url(urls?.get(&self.id)?, first_declared_endpoint).cloned()
405    }
406
407    fn validate_public_endpoints(&self) -> Result<()> {
408        let mut endpoint_names = std::collections::HashSet::new();
409        let mut apex_endpoint_name: Option<&str> = None;
410        for endpoint in &self.public_endpoints {
411            endpoint.validate_for_resource(&self.id)?;
412            if !endpoint_names.insert(endpoint.name.as_str()) {
413                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
414                    resource_id: self.id.clone(),
415                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
416                }));
417            }
418            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
419                if let Some(existing_name) = apex_endpoint_name {
420                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
421                        resource_id: self.id.clone(),
422                        reason: format!(
423                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
424                            existing_name
425                        ),
426                    }));
427                }
428                apex_endpoint_name = Some(endpoint.name.as_str());
429            }
430        }
431
432        Ok(())
433    }
434}
435
436fn default_memory_mb() -> u32 {
437    512
438}
439
440fn default_timeout_seconds() -> u32 {
441    180
442}
443
444/// Longest Worker execution supported by every Commands delivery path.
445pub const MAX_WORKER_TIMEOUT_SECONDS: u32 = 3600;
446
447fn deserialize_timeout_seconds<'de, D>(deserializer: D) -> std::result::Result<u32, D::Error>
448where
449    D: serde::Deserializer<'de>,
450{
451    let value = u32::deserialize(deserializer)?;
452    validate_timeout_seconds(value).map_err(serde::de::Error::custom)
453}
454
455fn validate_timeout_seconds(timeout_seconds: u32) -> Result<u32> {
456    if (1..=MAX_WORKER_TIMEOUT_SECONDS).contains(&timeout_seconds) {
457        return Ok(timeout_seconds);
458    }
459
460    Err(AlienError::new(ErrorData::WorkerTimeoutInvalid {
461        timeout_seconds,
462        max_timeout_seconds: MAX_WORKER_TIMEOUT_SECONDS,
463    }))
464}
465
466fn default_commands_enabled() -> bool {
467    false
468}
469
470/// HTTP method for readiness probe requests.
471#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
472#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
473#[serde(rename_all = "UPPERCASE")]
474#[derive(Default)]
475pub enum HttpMethod {
476    #[default]
477    Get,
478    Post,
479    Put,
480    Delete,
481    Head,
482    Options,
483    Patch,
484}
485
486/// Configuration for HTTP-based readiness probe.
487/// This probe is executed after worker provisioning/update to verify the worker is ready to serve traffic.
488/// Only works with workers that have Public ingress.
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
491#[serde(rename_all = "camelCase")]
492pub struct ReadinessProbe {
493    /// HTTP method to use for the probe request.
494    /// Default: GET
495    #[serde(default)]
496    pub method: HttpMethod,
497
498    /// Path to request for the probe (e.g., "/health", "/ready").
499    /// Default: "/"
500    #[serde(default = "default_probe_path")]
501    pub path: String,
502}
503
504fn default_probe_path() -> String {
505    "/".to_string()
506}
507
508impl Default for ReadinessProbe {
509    fn default() -> Self {
510        Self {
511            method: HttpMethod::default(),
512            path: default_probe_path(),
513        }
514    }
515}
516
517use crate::resources::worker::worker_builder::State;
518
519impl<S: State> WorkerBuilder<S> {
520    /// Links the worker to another resource with specified permissions.
521    /// Accepts a reference to any type `R` where `&R` can be converted into `ResourceRef`.
522    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
523    where
524        for<'a> &'a R: Into<ResourceRef>, // Use Higher-Rank Trait Bound (HRTB)
525    {
526        // Perform the conversion from &R to ResourceRef using .into()
527        let resource_ref: ResourceRef = resource.into();
528        self.links.push(resource_ref);
529        self
530    }
531
532    /// Adds a trigger to the worker. Workers can have multiple triggers.
533    /// Each trigger will independently invoke the worker when its conditions are met.
534    ///
535    /// # Examples
536    /// ```rust
537    /// # use alien_core::{Worker, WorkerTrigger, WorkerCode, Queue};
538    /// # let queue1 = Queue::new("queue-1".to_string()).build();
539    /// # let queue2 = Queue::new("queue-2".to_string()).build();
540    /// let worker = Worker::new("my-worker".to_string())
541    ///     .code(WorkerCode::Image { image: "test:latest".to_string() })
542    ///     .permissions("execution".to_string())
543    ///     .trigger(WorkerTrigger::queue(&queue1))
544    ///     .trigger(WorkerTrigger::queue(&queue2))
545    ///     .build();
546    /// ```
547    pub fn trigger(mut self, trigger: WorkerTrigger) -> Self {
548        self.triggers.push(trigger);
549        self
550    }
551
552    /// Exposes a named public endpoint for the worker.
553    pub fn public_endpoint(mut self, endpoint: WorkerPublicEndpoint) -> Self {
554        self.public_endpoints.push(endpoint);
555        self
556    }
557}
558
559// Implementation of ResourceDefinition trait for Worker
560impl ResourceDefinition for Worker {
561    fn get_resource_type(&self) -> ResourceType {
562        Self::RESOURCE_TYPE
563    }
564
565    fn id(&self) -> &str {
566        &self.id
567    }
568
569    fn get_dependencies(&self) -> Vec<ResourceRef> {
570        let mut dependencies = self.links.clone();
571
572        // Add trigger dependencies
573        for trigger in &self.triggers {
574            match trigger {
575                WorkerTrigger::Queue { queue, .. } => {
576                    dependencies.push(queue.clone());
577                }
578                WorkerTrigger::Storage { storage, .. } => {
579                    dependencies.push(storage.clone());
580                }
581                WorkerTrigger::Schedule { .. } => {
582                    // Schedule triggers don't depend on other resources
583                }
584            }
585        }
586
587        dependencies
588    }
589
590    fn get_permissions(&self) -> Option<&str> {
591        Some(&self.permissions)
592    }
593
594    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
595        // Downcast to Worker type to use the existing validate_update method
596        let new_worker = new_config
597            .as_any()
598            .downcast_ref::<Worker>()
599            .ok_or_else(|| {
600                AlienError::new(ErrorData::UnexpectedResourceType {
601                    resource_id: self.id.clone(),
602                    expected: Self::RESOURCE_TYPE,
603                    actual: new_config.get_resource_type(),
604                })
605            })?;
606
607        if self.id != new_worker.id {
608            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
609                resource_id: self.id.clone(),
610                reason: "the 'id' field is immutable".to_string(),
611            }));
612        }
613        self.validate_public_endpoints()?;
614        new_worker.validate_public_endpoints()?;
615        if self.public_endpoints != new_worker.public_endpoints {
616            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
617                resource_id: self.id.clone(),
618                reason: "the 'publicEndpoints' field is immutable".to_string(),
619            }));
620        }
621        Ok(())
622    }
623
624    fn as_any(&self) -> &dyn Any {
625        self
626    }
627
628    fn as_any_mut(&mut self) -> &mut dyn Any {
629        self
630    }
631
632    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
633        Box::new(self.clone())
634    }
635
636    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
637        other.as_any().downcast_ref::<Worker>() == Some(self)
638    }
639
640    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
641        serde_json::to_value(self)
642    }
643}
644
645/// Outputs generated by a successfully provisioned Worker.
646#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
647#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
648#[serde(rename_all = "camelCase")]
649pub struct WorkerOutputs {
650    /// The platform-specific worker name.
651    pub worker_name: String,
652    /// Public endpoints resolved for this worker.
653    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
654    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
655    /// The ARN or platform-specific identifier.
656    #[serde(skip_serializing_if = "Option::is_none")]
657    pub identifier: Option<String>,
658    /// Push target for commands delivery. Platform-specific:
659    /// - AWS: Lambda function name or ARN
660    /// - GCP: Full Pub/Sub topic path (projects/{project}/topics/{topic})
661    /// - Azure: Service Bus "{namespace}/{queue}"
662    #[serde(default, skip_serializing_if = "Option::is_none")]
663    pub commands_push_target: Option<String>,
664}
665
666impl ResourceOutputsDefinition for WorkerOutputs {
667    fn get_resource_type(&self) -> ResourceType {
668        Worker::RESOURCE_TYPE.clone()
669    }
670
671    fn as_any(&self) -> &dyn Any {
672        self
673    }
674
675    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
676        Box::new(self.clone())
677    }
678
679    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
680        other.as_any().downcast_ref::<WorkerOutputs>() == Some(self)
681    }
682
683    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
684        serde_json::to_value(self)
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691    use crate::Storage;
692
693    #[test]
694    fn test_worker_builder_direct_refs() {
695        let dummy_storage = Storage::new("test-storage".to_string()).build();
696        let dummy_storage_2 = Storage::new("test-storage-2".to_string()).build();
697
698        let worker = Worker::new("my-worker".to_string())
699            .code(WorkerCode::Image {
700                image: "test-image".to_string(),
701            })
702            .permissions("execution".to_string())
703            .link(&dummy_storage) // Pass reference directly
704            .link(&dummy_storage_2) // Add a second link
705            .build();
706
707        assert_eq!(worker.id, "my-worker");
708        assert_eq!(
709            worker.code,
710            WorkerCode::Image {
711                image: "test-image".to_string()
712            }
713        );
714
715        // Verify permissions was set correctly
716        assert_eq!(worker.permissions, "execution");
717
718        // Verify links were added correctly
719        assert!(worker
720            .links
721            .contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage")));
722        assert!(worker
723            .links
724            .contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage-2")));
725        assert_eq!(worker.links.len(), 2); // Expect 2 links now
726    }
727
728    #[test]
729    fn test_worker_with_readiness_probe() {
730        let probe = ReadinessProbe {
731            method: HttpMethod::Post,
732            path: "/health".to_string(),
733        };
734
735        let worker = Worker::new("my-worker".to_string())
736            .code(WorkerCode::Image {
737                image: "test-image".to_string(),
738            })
739            .permissions("execution".to_string())
740            .public_endpoint(WorkerPublicEndpoint {
741                name: "api".to_string(),
742                host_label: None,
743                wildcard_subdomains: false,
744            })
745            .readiness_probe(probe.clone())
746            .build();
747
748        assert_eq!(worker.id, "my-worker");
749        assert_eq!(worker.public_endpoints[0].name, "api");
750        assert_eq!(worker.readiness_probe, Some(probe));
751    }
752
753    #[test]
754    fn test_readiness_probe_defaults() {
755        let probe = ReadinessProbe::default();
756        assert_eq!(probe.method, HttpMethod::Get);
757        assert_eq!(probe.path, "/");
758    }
759
760    #[test]
761    fn test_worker_with_rust_toolchain() {
762        let worker = Worker::new("my-rust-worker".to_string())
763            .code(WorkerCode::Source {
764                src: "./".to_string(),
765                toolchain: ToolchainConfig::Rust {
766                    binary_name: "my-app".to_string(),
767                },
768            })
769            .permissions("execution".to_string())
770            .build();
771
772        assert_eq!(worker.id, "my-rust-worker");
773
774        match &worker.code {
775            WorkerCode::Source { src, toolchain } => {
776                assert_eq!(src, "./");
777                assert_eq!(
778                    toolchain,
779                    &ToolchainConfig::Rust {
780                        binary_name: "my-app".to_string(),
781                    }
782                );
783            }
784            _ => panic!("Expected Source code"),
785        }
786    }
787
788    #[test]
789    fn test_worker_with_typescript_toolchain() {
790        let worker = Worker::new("my-ts-worker".to_string())
791            .code(WorkerCode::Source {
792                src: "./".to_string(),
793                toolchain: ToolchainConfig::TypeScript {
794                    binary_name: Some("my-ts-worker".to_string()),
795                },
796            })
797            .permissions("execution".to_string())
798            .build();
799
800        assert_eq!(worker.id, "my-ts-worker");
801
802        match &worker.code {
803            WorkerCode::Source { src, toolchain } => {
804                assert_eq!(src, "./");
805                assert_eq!(
806                    toolchain,
807                    &ToolchainConfig::TypeScript {
808                        binary_name: Some("my-ts-worker".to_string())
809                    }
810                );
811            }
812            _ => panic!("Expected Source code"),
813        }
814    }
815
816    #[test]
817    fn test_worker_with_queue_trigger() {
818        use crate::Queue;
819
820        let queue = Queue::new("test-queue".to_string()).build();
821
822        let worker = Worker::new("triggered-worker".to_string())
823            .code(WorkerCode::Image {
824                image: "test-image".to_string(),
825            })
826            .permissions("execution".to_string())
827            .trigger(WorkerTrigger::queue(&queue))
828            .build();
829
830        assert_eq!(worker.triggers.len(), 1);
831        if let WorkerTrigger::Queue {
832            queue: queue_ref, ..
833        } = &worker.triggers[0]
834        {
835            assert_eq!(queue_ref.resource_type, Queue::RESOURCE_TYPE);
836            assert_eq!(queue_ref.id, "test-queue");
837        } else {
838            panic!("Expected queue trigger");
839        }
840    }
841
842    #[test]
843    fn test_worker_trigger_dependencies() {
844        use crate::Queue;
845
846        let queue = Queue::new("test-queue".to_string()).build();
847        let storage = Storage::new("test-storage".to_string()).build();
848
849        let worker = Worker::new("triggered-worker".to_string())
850            .code(WorkerCode::Image {
851                image: "test-image".to_string(),
852            })
853            .permissions("execution".to_string())
854            .link(&storage) // regular link dependency
855            .trigger(WorkerTrigger::queue(&queue)) // trigger dependency
856            .build();
857
858        let dependencies = worker.get_dependencies();
859
860        // Should have both link and trigger dependencies
861        assert_eq!(dependencies.len(), 2);
862        assert!(dependencies.contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage")));
863        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "test-queue")));
864    }
865
866    #[test]
867    fn test_worker_trigger_helper_methods() {
868        use crate::Queue;
869
870        let queue = Queue::new("my-queue".to_string()).build();
871
872        // Test the helper method
873        let trigger = WorkerTrigger::queue(&queue);
874
875        if let WorkerTrigger::Queue {
876            queue: queue_ref, ..
877        } = trigger
878        {
879            assert_eq!(queue_ref.resource_type, Queue::RESOURCE_TYPE);
880            assert_eq!(queue_ref.id, "my-queue");
881        } else {
882            panic!("Expected queue trigger");
883        }
884    }
885
886    #[test]
887    fn test_worker_with_multiple_triggers() {
888        use crate::Queue;
889
890        let queue1 = Queue::new("queue-1".to_string()).build();
891        let queue2 = Queue::new("queue-2".to_string()).build();
892
893        let worker = Worker::new("multi-triggered-worker".to_string())
894            .code(WorkerCode::Image {
895                image: "test-image".to_string(),
896            })
897            .permissions("execution".to_string())
898            .trigger(WorkerTrigger::queue(&queue1))
899            .trigger(WorkerTrigger::queue(&queue2))
900            .trigger(WorkerTrigger::schedule("0 * * * *".to_string()))
901            .build();
902
903        assert_eq!(worker.triggers.len(), 3);
904
905        // Check first queue trigger
906        if let WorkerTrigger::Queue {
907            queue: queue_ref, ..
908        } = &worker.triggers[0]
909        {
910            assert_eq!(queue_ref.id, "queue-1");
911        } else {
912            panic!("Expected first trigger to be queue-1");
913        }
914
915        // Check second queue trigger
916        if let WorkerTrigger::Queue {
917            queue: queue_ref, ..
918        } = &worker.triggers[1]
919        {
920            assert_eq!(queue_ref.id, "queue-2");
921        } else {
922            panic!("Expected second trigger to be queue-2");
923        }
924
925        // Check schedule trigger
926        if let WorkerTrigger::Schedule { cron } = &worker.triggers[2] {
927            assert_eq!(cron, "0 * * * *");
928        } else {
929            panic!("Expected third trigger to be schedule");
930        }
931
932        // Check dependencies include both queues
933        let dependencies = worker.get_dependencies();
934        assert_eq!(dependencies.len(), 2); // Only queues, schedule has no dependency
935        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "queue-1")));
936        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "queue-2")));
937    }
938
939    #[test]
940    fn test_worker_with_commands_enabled() {
941        let worker = Worker::new("cmd-worker".to_string())
942            .code(WorkerCode::Image {
943                image: "test-image".to_string(),
944            })
945            .permissions("execution".to_string())
946            .commands_enabled(true)
947            .build();
948
949        assert_eq!(worker.id, "cmd-worker");
950        assert!(worker.public_endpoints.is_empty());
951        assert_eq!(worker.commands_enabled, true);
952    }
953
954    #[test]
955    fn test_worker_defaults() {
956        let worker = Worker::new("default-worker".to_string())
957            .code(WorkerCode::Image {
958                image: "test-image".to_string(),
959            })
960            .permissions("execution".to_string())
961            .build();
962
963        // Test that defaults are applied correctly
964        assert!(worker.public_endpoints.is_empty());
965        assert_eq!(worker.commands_enabled, false);
966        assert_eq!(worker.memory_mb, 512);
967        assert_eq!(worker.timeout_seconds, 180);
968    }
969
970    #[test]
971    fn worker_deserialization_rejects_timeout_outside_supported_range() {
972        let worker = Worker::new("timeout-worker".to_string())
973            .code(WorkerCode::Image {
974                image: "test-image".to_string(),
975            })
976            .permissions("execution".to_string())
977            .build();
978        let mut value = serde_json::to_value(worker).expect("serialize worker");
979
980        value["timeoutSeconds"] = serde_json::json!(0);
981        assert!(serde_json::from_value::<Worker>(value.clone()).is_err());
982
983        value["timeoutSeconds"] = serde_json::json!(MAX_WORKER_TIMEOUT_SECONDS + 1);
984        assert!(serde_json::from_value::<Worker>(value).is_err());
985    }
986
987    #[test]
988    fn worker_builder_rejects_zero_timeout() {
989        let Err(error) = Worker::new("timeout-worker".to_string()).timeout_seconds(0) else {
990            panic!("zero timeout must be rejected");
991        };
992
993        assert_eq!(error.code, "WORKER_TIMEOUT_INVALID");
994        assert_eq!(error.http_status_code, Some(400));
995    }
996
997    #[test]
998    fn worker_builder_rejects_timeout_above_maximum() {
999        let Err(error) = Worker::new("timeout-worker".to_string())
1000            .timeout_seconds(MAX_WORKER_TIMEOUT_SECONDS + 1)
1001        else {
1002            panic!("timeout above maximum must be rejected");
1003        };
1004
1005        assert_eq!(error.code, "WORKER_TIMEOUT_INVALID");
1006    }
1007
1008    #[test]
1009    fn worker_builder_accepts_minimum_timeout() {
1010        let worker = Worker::new("timeout-worker".to_string())
1011            .timeout_seconds(1)
1012            .expect("minimum timeout is valid")
1013            .code(WorkerCode::Image {
1014                image: "test-image".to_string(),
1015            })
1016            .permissions("execution".to_string())
1017            .build();
1018
1019        assert_eq!(worker.timeout_seconds, 1);
1020    }
1021
1022    #[test]
1023    fn worker_builder_accepts_maximum_timeout() {
1024        let worker = Worker::new("timeout-worker".to_string())
1025            .timeout_seconds(MAX_WORKER_TIMEOUT_SECONDS)
1026            .expect("maximum timeout is valid")
1027            .code(WorkerCode::Image {
1028                image: "test-image".to_string(),
1029            })
1030            .permissions("execution".to_string())
1031            .build();
1032
1033        assert_eq!(worker.timeout_seconds, MAX_WORKER_TIMEOUT_SECONDS);
1034    }
1035
1036    #[test]
1037    fn test_worker_public_ingress_with_commands() {
1038        let worker = Worker::new("public-cmd-worker".to_string())
1039            .code(WorkerCode::Image {
1040                image: "test-image".to_string(),
1041            })
1042            .permissions("execution".to_string())
1043            .public_endpoint(WorkerPublicEndpoint {
1044                name: "api".to_string(),
1045                host_label: None,
1046                wildcard_subdomains: false,
1047            })
1048            .commands_enabled(true)
1049            .build();
1050
1051        assert_eq!(worker.public_endpoints[0].name, "api");
1052        assert_eq!(worker.commands_enabled, true);
1053    }
1054
1055    #[test]
1056    fn worker_rejects_multiple_apex_public_endpoints() {
1057        let worker = Worker::new("apex-worker".to_string())
1058            .code(WorkerCode::Image {
1059                image: "test-image".to_string(),
1060            })
1061            .permissions("execution".to_string())
1062            .public_endpoint(WorkerPublicEndpoint {
1063                name: "api".to_string(),
1064                host_label: Some(APEX_HOST_LABEL.to_string()),
1065                wildcard_subdomains: false,
1066            })
1067            .public_endpoint(WorkerPublicEndpoint {
1068                name: "admin".to_string(),
1069                host_label: Some(APEX_HOST_LABEL.to_string()),
1070                wildcard_subdomains: false,
1071            })
1072            .build();
1073
1074        assert!(worker.validate_public_endpoints().is_err());
1075    }
1076}