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    /// Memory allocated to the worker in megabytes (MB).
237    /// Default: 512
238    ///
239    /// Platform-specific constraints:
240    /// - **AWS Lambda**: 128–10240 MB in 1 MB increments
241    /// - **GCP Cloud Run**: 128–32768 MB
242    /// - **Azure Container Apps**: fixed CPU/memory pairs — 512, 1024, 1536, 2048, 2560,
243    ///   3072, 3584, 4096 MB. Values below 512 are automatically rounded up at deploy time.
244    #[builder(default = default_memory_mb())]
245    #[serde(default = "default_memory_mb")]
246    #[cfg_attr(feature = "openapi", schema(default = default_memory_mb))]
247    pub memory_mb: u32,
248
249    /// Maximum execution time for the worker in seconds.
250    /// Constraints: 1‑3600 seconds (platform-specific limits may apply)
251    /// Default: 180
252    #[builder(
253        default = default_timeout_seconds(),
254        with = |timeout_seconds: u32| -> crate::Result<_> {
255            validate_timeout_seconds(timeout_seconds)
256        }
257    )]
258    #[serde(
259        default = "default_timeout_seconds",
260        deserialize_with = "deserialize_timeout_seconds"
261    )]
262    #[cfg_attr(
263        feature = "openapi",
264        schema(default = default_timeout_seconds, minimum = 1, maximum = 3600)
265    )]
266    pub timeout_seconds: u32,
267
268    /// Key-value pairs to set as environment variables for the worker.
269    #[builder(default)]
270    #[serde(default)]
271    pub environment: HashMap<String, String>,
272
273    /// Whether the worker can receive remote commands via the Commands protocol.
274    /// When enabled, the platform pushes commands into the Worker runtime,
275    /// which executes registered handlers.
276    #[builder(default = default_commands_enabled())]
277    #[serde(default = "default_commands_enabled")]
278    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
279    pub commands_enabled: bool,
280
281    /// Maximum number of concurrent executions allowed for the worker.
282    /// None means platform default applies.
283    pub concurrency_limit: Option<u32>,
284
285    /// Optional readiness probe configuration.
286    /// Only applicable for workers with Public ingress.
287    /// When configured, the probe will be executed after provisioning/update to verify the worker is ready.
288    pub readiness_probe: Option<ReadinessProbe>,
289
290    /// Set by `alien build` when the Worker image was built on a runtime that
291    /// exchanges its cloud identity for telemetry credentials. Absent means the
292    /// image may be older and still reads `ALIEN_RUNTIME_SECRETS`, so a deployer
293    /// in identity mode keeps providing them. Build output replaces any value
294    /// written in the stack definition.
295    #[builder(default)]
296    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
297    pub runtime_identity_exchange: bool,
298}
299
300impl Worker {
301    /// The resource type identifier for Workers
302    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("worker");
303
304    /// Bindings needed by explicit links and queue delivery source routing.
305    pub fn runtime_binding_links(&self) -> Vec<ResourceRef> {
306        let mut links = self.links.clone();
307        for trigger in &self.triggers {
308            if let WorkerTrigger::Queue {
309                queue,
310                batch: Some(_),
311            } = trigger
312            {
313                if !links.contains(queue) {
314                    links.push(queue.clone());
315                }
316            }
317        }
318        links
319    }
320
321    /// Whether the worker explicitly opts into queue batching.
322    pub fn has_queue_batches(&self) -> bool {
323        self.triggers
324            .iter()
325            .any(|trigger| matches!(trigger, WorkerTrigger::Queue { batch: Some(_), .. }))
326    }
327
328    /// Batch routing is emitted only for workers that explicitly opt into batching.
329    pub fn queue_batch_environment(&self) -> Result<Option<String>> {
330        if !self.has_queue_batches() {
331            return Ok(None);
332        }
333        let mut batches = std::collections::BTreeMap::new();
334        for trigger in &self.triggers {
335            if let WorkerTrigger::Queue { queue, batch } = trigger {
336                if let Some(batch) = batch {
337                    batch.validate()?;
338                }
339                if batches.insert(&queue.id, batch).is_some() {
340                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
341                        resource_id: self.id.clone(),
342                        reason: "Duplicate queue trigger".into(),
343                    }));
344                }
345            }
346        }
347        if batches.is_empty() {
348            return Ok(None);
349        }
350        serde_json::to_string(&batches)
351            .map(Some)
352            .into_alien_error()
353            .context(ErrorData::GenericError {
354                message: "Failed to serialize queue batch configuration".into(),
355            })
356    }
357
358    /// Batch settings for a queue trigger, absent for legacy single-message delivery.
359    pub fn queue_batch_config(&self, queue_id: &str) -> Option<&QueueBatchConfig> {
360        self.triggers.iter().find_map(|trigger| match trigger {
361            WorkerTrigger::Queue { queue, batch } if queue.id == queue_id => batch.as_ref(),
362            _ => None,
363        })
364    }
365
366    /// Allocate SQS admission across queue mappings. Commands invoke Lambda directly.
367    /// AWS requires at least two per mapping. Below that threshold the function's
368    /// reserved concurrency remains the compute cap; it is not a distributed lock.
369    pub fn queue_source_maximum_concurrency(&self) -> Option<u32> {
370        if !self.has_queue_batches() {
371            return None;
372        }
373        let sources = self
374            .triggers
375            .iter()
376            .filter(|trigger| matches!(trigger, WorkerTrigger::Queue { .. }))
377            .count() as u32;
378        let capacity = self.concurrency_limit?.checked_div(sources)?;
379        (capacity >= 2).then_some(capacity.min(1000))
380    }
381
382    /// Returns the permission profile name for this worker.
383    pub fn get_permissions(&self) -> &str {
384        &self.permissions
385    }
386
387    /// The URL `urls` assigns to this worker's primary public endpoint, the first one
388    /// it declares. See [`crate::primary_public_endpoint_url`].
389    pub fn configured_primary_public_url(
390        &self,
391        urls: Option<&crate::PublicEndpointUrls>,
392    ) -> Option<String> {
393        let first_declared_endpoint = self
394            .public_endpoints
395            .first()
396            .map(|endpoint| endpoint.name.as_str());
397        crate::primary_public_endpoint_url(urls?.get(&self.id)?, first_declared_endpoint).cloned()
398    }
399
400    fn validate_public_endpoints(&self) -> Result<()> {
401        let mut endpoint_names = std::collections::HashSet::new();
402        let mut apex_endpoint_name: Option<&str> = None;
403        for endpoint in &self.public_endpoints {
404            endpoint.validate_for_resource(&self.id)?;
405            if !endpoint_names.insert(endpoint.name.as_str()) {
406                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
407                    resource_id: self.id.clone(),
408                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
409                }));
410            }
411            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
412                if let Some(existing_name) = apex_endpoint_name {
413                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
414                        resource_id: self.id.clone(),
415                        reason: format!(
416                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
417                            existing_name
418                        ),
419                    }));
420                }
421                apex_endpoint_name = Some(endpoint.name.as_str());
422            }
423        }
424
425        Ok(())
426    }
427}
428
429fn default_memory_mb() -> u32 {
430    512
431}
432
433fn default_timeout_seconds() -> u32 {
434    180
435}
436
437/// Longest Worker execution supported by every Commands delivery path.
438pub const MAX_WORKER_TIMEOUT_SECONDS: u32 = 3600;
439
440fn deserialize_timeout_seconds<'de, D>(deserializer: D) -> std::result::Result<u32, D::Error>
441where
442    D: serde::Deserializer<'de>,
443{
444    let value = u32::deserialize(deserializer)?;
445    validate_timeout_seconds(value).map_err(serde::de::Error::custom)
446}
447
448fn validate_timeout_seconds(timeout_seconds: u32) -> Result<u32> {
449    if (1..=MAX_WORKER_TIMEOUT_SECONDS).contains(&timeout_seconds) {
450        return Ok(timeout_seconds);
451    }
452
453    Err(AlienError::new(ErrorData::WorkerTimeoutInvalid {
454        timeout_seconds,
455        max_timeout_seconds: MAX_WORKER_TIMEOUT_SECONDS,
456    }))
457}
458
459fn default_commands_enabled() -> bool {
460    false
461}
462
463/// HTTP method for readiness probe requests.
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
466#[serde(rename_all = "UPPERCASE")]
467#[derive(Default)]
468pub enum HttpMethod {
469    #[default]
470    Get,
471    Post,
472    Put,
473    Delete,
474    Head,
475    Options,
476    Patch,
477}
478
479/// Configuration for HTTP-based readiness probe.
480/// This probe is executed after worker provisioning/update to verify the worker is ready to serve traffic.
481/// Only works with workers that have Public ingress.
482#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
483#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
484#[serde(rename_all = "camelCase")]
485pub struct ReadinessProbe {
486    /// HTTP method to use for the probe request.
487    /// Default: GET
488    #[serde(default)]
489    pub method: HttpMethod,
490
491    /// Path to request for the probe (e.g., "/health", "/ready").
492    /// Default: "/"
493    #[serde(default = "default_probe_path")]
494    pub path: String,
495}
496
497fn default_probe_path() -> String {
498    "/".to_string()
499}
500
501impl Default for ReadinessProbe {
502    fn default() -> Self {
503        Self {
504            method: HttpMethod::default(),
505            path: default_probe_path(),
506        }
507    }
508}
509
510use crate::resources::worker::worker_builder::State;
511
512impl<S: State> WorkerBuilder<S> {
513    /// Links the worker to another resource with specified permissions.
514    /// Accepts a reference to any type `R` where `&R` can be converted into `ResourceRef`.
515    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
516    where
517        for<'a> &'a R: Into<ResourceRef>, // Use Higher-Rank Trait Bound (HRTB)
518    {
519        // Perform the conversion from &R to ResourceRef using .into()
520        let resource_ref: ResourceRef = resource.into();
521        self.links.push(resource_ref);
522        self
523    }
524
525    /// Adds a trigger to the worker. Workers can have multiple triggers.
526    /// Each trigger will independently invoke the worker when its conditions are met.
527    ///
528    /// # Examples
529    /// ```rust
530    /// # use alien_core::{Worker, WorkerTrigger, WorkerCode, Queue};
531    /// # let queue1 = Queue::new("queue-1".to_string()).build();
532    /// # let queue2 = Queue::new("queue-2".to_string()).build();
533    /// let worker = Worker::new("my-worker".to_string())
534    ///     .code(WorkerCode::Image { image: "test:latest".to_string() })
535    ///     .permissions("execution".to_string())
536    ///     .trigger(WorkerTrigger::queue(&queue1))
537    ///     .trigger(WorkerTrigger::queue(&queue2))
538    ///     .build();
539    /// ```
540    pub fn trigger(mut self, trigger: WorkerTrigger) -> Self {
541        self.triggers.push(trigger);
542        self
543    }
544
545    /// Exposes a named public endpoint for the worker.
546    pub fn public_endpoint(mut self, endpoint: WorkerPublicEndpoint) -> Self {
547        self.public_endpoints.push(endpoint);
548        self
549    }
550}
551
552// Implementation of ResourceDefinition trait for Worker
553impl ResourceDefinition for Worker {
554    fn get_resource_type(&self) -> ResourceType {
555        Self::RESOURCE_TYPE
556    }
557
558    fn id(&self) -> &str {
559        &self.id
560    }
561
562    fn get_dependencies(&self) -> Vec<ResourceRef> {
563        let mut dependencies = self.links.clone();
564
565        // Add trigger dependencies
566        for trigger in &self.triggers {
567            match trigger {
568                WorkerTrigger::Queue { queue, .. } => {
569                    dependencies.push(queue.clone());
570                }
571                WorkerTrigger::Storage { storage, .. } => {
572                    dependencies.push(storage.clone());
573                }
574                WorkerTrigger::Schedule { .. } => {
575                    // Schedule triggers don't depend on other resources
576                }
577            }
578        }
579
580        dependencies
581    }
582
583    fn get_permissions(&self) -> Option<&str> {
584        Some(&self.permissions)
585    }
586
587    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
588        // Downcast to Worker type to use the existing validate_update method
589        let new_worker = new_config
590            .as_any()
591            .downcast_ref::<Worker>()
592            .ok_or_else(|| {
593                AlienError::new(ErrorData::UnexpectedResourceType {
594                    resource_id: self.id.clone(),
595                    expected: Self::RESOURCE_TYPE,
596                    actual: new_config.get_resource_type(),
597                })
598            })?;
599
600        if self.id != new_worker.id {
601            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
602                resource_id: self.id.clone(),
603                reason: "the 'id' field is immutable".to_string(),
604            }));
605        }
606        self.validate_public_endpoints()?;
607        new_worker.validate_public_endpoints()?;
608        if self.public_endpoints != new_worker.public_endpoints {
609            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
610                resource_id: self.id.clone(),
611                reason: "the 'publicEndpoints' field is immutable".to_string(),
612            }));
613        }
614        Ok(())
615    }
616
617    fn as_any(&self) -> &dyn Any {
618        self
619    }
620
621    fn as_any_mut(&mut self) -> &mut dyn Any {
622        self
623    }
624
625    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
626        Box::new(self.clone())
627    }
628
629    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
630        other.as_any().downcast_ref::<Worker>() == Some(self)
631    }
632
633    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
634        serde_json::to_value(self)
635    }
636}
637
638/// Outputs generated by a successfully provisioned Worker.
639#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
640#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
641#[serde(rename_all = "camelCase")]
642pub struct WorkerOutputs {
643    /// The platform-specific worker name.
644    pub worker_name: String,
645    /// Public endpoints resolved for this worker.
646    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
647    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
648    /// The ARN or platform-specific identifier.
649    #[serde(skip_serializing_if = "Option::is_none")]
650    pub identifier: Option<String>,
651    /// Push target for commands delivery. Platform-specific:
652    /// - AWS: Lambda function name or ARN
653    /// - GCP: Full Pub/Sub topic path (projects/{project}/topics/{topic})
654    /// - Azure: Service Bus "{namespace}/{queue}"
655    #[serde(default, skip_serializing_if = "Option::is_none")]
656    pub commands_push_target: Option<String>,
657}
658
659impl ResourceOutputsDefinition for WorkerOutputs {
660    fn get_resource_type(&self) -> ResourceType {
661        Worker::RESOURCE_TYPE.clone()
662    }
663
664    fn as_any(&self) -> &dyn Any {
665        self
666    }
667
668    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
669        Box::new(self.clone())
670    }
671
672    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
673        other.as_any().downcast_ref::<WorkerOutputs>() == Some(self)
674    }
675
676    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
677        serde_json::to_value(self)
678    }
679}
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684    use crate::Storage;
685
686    #[test]
687    fn test_worker_builder_direct_refs() {
688        let dummy_storage = Storage::new("test-storage".to_string()).build();
689        let dummy_storage_2 = Storage::new("test-storage-2".to_string()).build();
690
691        let worker = Worker::new("my-worker".to_string())
692            .code(WorkerCode::Image {
693                image: "test-image".to_string(),
694            })
695            .permissions("execution".to_string())
696            .link(&dummy_storage) // Pass reference directly
697            .link(&dummy_storage_2) // Add a second link
698            .build();
699
700        assert_eq!(worker.id, "my-worker");
701        assert_eq!(
702            worker.code,
703            WorkerCode::Image {
704                image: "test-image".to_string()
705            }
706        );
707
708        // Verify permissions was set correctly
709        assert_eq!(worker.permissions, "execution");
710
711        // Verify links were added correctly
712        assert!(worker
713            .links
714            .contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage")));
715        assert!(worker
716            .links
717            .contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage-2")));
718        assert_eq!(worker.links.len(), 2); // Expect 2 links now
719    }
720
721    #[test]
722    fn test_worker_with_readiness_probe() {
723        let probe = ReadinessProbe {
724            method: HttpMethod::Post,
725            path: "/health".to_string(),
726        };
727
728        let worker = Worker::new("my-worker".to_string())
729            .code(WorkerCode::Image {
730                image: "test-image".to_string(),
731            })
732            .permissions("execution".to_string())
733            .public_endpoint(WorkerPublicEndpoint {
734                name: "api".to_string(),
735                host_label: None,
736                wildcard_subdomains: false,
737            })
738            .readiness_probe(probe.clone())
739            .build();
740
741        assert_eq!(worker.id, "my-worker");
742        assert_eq!(worker.public_endpoints[0].name, "api");
743        assert_eq!(worker.readiness_probe, Some(probe));
744    }
745
746    #[test]
747    fn test_readiness_probe_defaults() {
748        let probe = ReadinessProbe::default();
749        assert_eq!(probe.method, HttpMethod::Get);
750        assert_eq!(probe.path, "/");
751    }
752
753    #[test]
754    fn test_worker_with_rust_toolchain() {
755        let worker = Worker::new("my-rust-worker".to_string())
756            .code(WorkerCode::Source {
757                src: "./".to_string(),
758                toolchain: ToolchainConfig::Rust {
759                    binary_name: "my-app".to_string(),
760                },
761            })
762            .permissions("execution".to_string())
763            .build();
764
765        assert_eq!(worker.id, "my-rust-worker");
766
767        match &worker.code {
768            WorkerCode::Source { src, toolchain } => {
769                assert_eq!(src, "./");
770                assert_eq!(
771                    toolchain,
772                    &ToolchainConfig::Rust {
773                        binary_name: "my-app".to_string(),
774                    }
775                );
776            }
777            _ => panic!("Expected Source code"),
778        }
779    }
780
781    #[test]
782    fn test_worker_with_typescript_toolchain() {
783        let worker = Worker::new("my-ts-worker".to_string())
784            .code(WorkerCode::Source {
785                src: "./".to_string(),
786                toolchain: ToolchainConfig::TypeScript {
787                    binary_name: Some("my-ts-worker".to_string()),
788                },
789            })
790            .permissions("execution".to_string())
791            .build();
792
793        assert_eq!(worker.id, "my-ts-worker");
794
795        match &worker.code {
796            WorkerCode::Source { src, toolchain } => {
797                assert_eq!(src, "./");
798                assert_eq!(
799                    toolchain,
800                    &ToolchainConfig::TypeScript {
801                        binary_name: Some("my-ts-worker".to_string())
802                    }
803                );
804            }
805            _ => panic!("Expected Source code"),
806        }
807    }
808
809    #[test]
810    fn test_worker_with_queue_trigger() {
811        use crate::Queue;
812
813        let queue = Queue::new("test-queue".to_string()).build();
814
815        let worker = Worker::new("triggered-worker".to_string())
816            .code(WorkerCode::Image {
817                image: "test-image".to_string(),
818            })
819            .permissions("execution".to_string())
820            .trigger(WorkerTrigger::queue(&queue))
821            .build();
822
823        assert_eq!(worker.triggers.len(), 1);
824        if let WorkerTrigger::Queue {
825            queue: queue_ref, ..
826        } = &worker.triggers[0]
827        {
828            assert_eq!(queue_ref.resource_type, Queue::RESOURCE_TYPE);
829            assert_eq!(queue_ref.id, "test-queue");
830        } else {
831            panic!("Expected queue trigger");
832        }
833    }
834
835    #[test]
836    fn test_worker_trigger_dependencies() {
837        use crate::Queue;
838
839        let queue = Queue::new("test-queue".to_string()).build();
840        let storage = Storage::new("test-storage".to_string()).build();
841
842        let worker = Worker::new("triggered-worker".to_string())
843            .code(WorkerCode::Image {
844                image: "test-image".to_string(),
845            })
846            .permissions("execution".to_string())
847            .link(&storage) // regular link dependency
848            .trigger(WorkerTrigger::queue(&queue)) // trigger dependency
849            .build();
850
851        let dependencies = worker.get_dependencies();
852
853        // Should have both link and trigger dependencies
854        assert_eq!(dependencies.len(), 2);
855        assert!(dependencies.contains(&ResourceRef::new(Storage::RESOURCE_TYPE, "test-storage")));
856        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "test-queue")));
857    }
858
859    #[test]
860    fn test_worker_trigger_helper_methods() {
861        use crate::Queue;
862
863        let queue = Queue::new("my-queue".to_string()).build();
864
865        // Test the helper method
866        let trigger = WorkerTrigger::queue(&queue);
867
868        if let WorkerTrigger::Queue {
869            queue: queue_ref, ..
870        } = trigger
871        {
872            assert_eq!(queue_ref.resource_type, Queue::RESOURCE_TYPE);
873            assert_eq!(queue_ref.id, "my-queue");
874        } else {
875            panic!("Expected queue trigger");
876        }
877    }
878
879    #[test]
880    fn test_worker_with_multiple_triggers() {
881        use crate::Queue;
882
883        let queue1 = Queue::new("queue-1".to_string()).build();
884        let queue2 = Queue::new("queue-2".to_string()).build();
885
886        let worker = Worker::new("multi-triggered-worker".to_string())
887            .code(WorkerCode::Image {
888                image: "test-image".to_string(),
889            })
890            .permissions("execution".to_string())
891            .trigger(WorkerTrigger::queue(&queue1))
892            .trigger(WorkerTrigger::queue(&queue2))
893            .trigger(WorkerTrigger::schedule("0 * * * *".to_string()))
894            .build();
895
896        assert_eq!(worker.triggers.len(), 3);
897
898        // Check first queue trigger
899        if let WorkerTrigger::Queue {
900            queue: queue_ref, ..
901        } = &worker.triggers[0]
902        {
903            assert_eq!(queue_ref.id, "queue-1");
904        } else {
905            panic!("Expected first trigger to be queue-1");
906        }
907
908        // Check second queue trigger
909        if let WorkerTrigger::Queue {
910            queue: queue_ref, ..
911        } = &worker.triggers[1]
912        {
913            assert_eq!(queue_ref.id, "queue-2");
914        } else {
915            panic!("Expected second trigger to be queue-2");
916        }
917
918        // Check schedule trigger
919        if let WorkerTrigger::Schedule { cron } = &worker.triggers[2] {
920            assert_eq!(cron, "0 * * * *");
921        } else {
922            panic!("Expected third trigger to be schedule");
923        }
924
925        // Check dependencies include both queues
926        let dependencies = worker.get_dependencies();
927        assert_eq!(dependencies.len(), 2); // Only queues, schedule has no dependency
928        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "queue-1")));
929        assert!(dependencies.contains(&ResourceRef::new(Queue::RESOURCE_TYPE, "queue-2")));
930    }
931
932    #[test]
933    fn test_worker_with_commands_enabled() {
934        let worker = Worker::new("cmd-worker".to_string())
935            .code(WorkerCode::Image {
936                image: "test-image".to_string(),
937            })
938            .permissions("execution".to_string())
939            .commands_enabled(true)
940            .build();
941
942        assert_eq!(worker.id, "cmd-worker");
943        assert!(worker.public_endpoints.is_empty());
944        assert_eq!(worker.commands_enabled, true);
945    }
946
947    #[test]
948    fn test_worker_defaults() {
949        let worker = Worker::new("default-worker".to_string())
950            .code(WorkerCode::Image {
951                image: "test-image".to_string(),
952            })
953            .permissions("execution".to_string())
954            .build();
955
956        // Test that defaults are applied correctly
957        assert!(worker.public_endpoints.is_empty());
958        assert_eq!(worker.commands_enabled, false);
959        assert_eq!(worker.memory_mb, 512);
960        assert_eq!(worker.timeout_seconds, 180);
961    }
962
963    #[test]
964    fn worker_deserialization_rejects_timeout_outside_supported_range() {
965        let worker = Worker::new("timeout-worker".to_string())
966            .code(WorkerCode::Image {
967                image: "test-image".to_string(),
968            })
969            .permissions("execution".to_string())
970            .build();
971        let mut value = serde_json::to_value(worker).expect("serialize worker");
972
973        value["timeoutSeconds"] = serde_json::json!(0);
974        assert!(serde_json::from_value::<Worker>(value.clone()).is_err());
975
976        value["timeoutSeconds"] = serde_json::json!(MAX_WORKER_TIMEOUT_SECONDS + 1);
977        assert!(serde_json::from_value::<Worker>(value).is_err());
978    }
979
980    #[test]
981    fn worker_builder_rejects_zero_timeout() {
982        let Err(error) = Worker::new("timeout-worker".to_string()).timeout_seconds(0) else {
983            panic!("zero timeout must be rejected");
984        };
985
986        assert_eq!(error.code, "WORKER_TIMEOUT_INVALID");
987        assert_eq!(error.http_status_code, Some(400));
988    }
989
990    #[test]
991    fn worker_builder_rejects_timeout_above_maximum() {
992        let Err(error) = Worker::new("timeout-worker".to_string())
993            .timeout_seconds(MAX_WORKER_TIMEOUT_SECONDS + 1)
994        else {
995            panic!("timeout above maximum must be rejected");
996        };
997
998        assert_eq!(error.code, "WORKER_TIMEOUT_INVALID");
999    }
1000
1001    #[test]
1002    fn worker_builder_accepts_minimum_timeout() {
1003        let worker = Worker::new("timeout-worker".to_string())
1004            .timeout_seconds(1)
1005            .expect("minimum timeout is valid")
1006            .code(WorkerCode::Image {
1007                image: "test-image".to_string(),
1008            })
1009            .permissions("execution".to_string())
1010            .build();
1011
1012        assert_eq!(worker.timeout_seconds, 1);
1013    }
1014
1015    #[test]
1016    fn worker_builder_accepts_maximum_timeout() {
1017        let worker = Worker::new("timeout-worker".to_string())
1018            .timeout_seconds(MAX_WORKER_TIMEOUT_SECONDS)
1019            .expect("maximum timeout is valid")
1020            .code(WorkerCode::Image {
1021                image: "test-image".to_string(),
1022            })
1023            .permissions("execution".to_string())
1024            .build();
1025
1026        assert_eq!(worker.timeout_seconds, MAX_WORKER_TIMEOUT_SECONDS);
1027    }
1028
1029    #[test]
1030    fn test_worker_public_ingress_with_commands() {
1031        let worker = Worker::new("public-cmd-worker".to_string())
1032            .code(WorkerCode::Image {
1033                image: "test-image".to_string(),
1034            })
1035            .permissions("execution".to_string())
1036            .public_endpoint(WorkerPublicEndpoint {
1037                name: "api".to_string(),
1038                host_label: None,
1039                wildcard_subdomains: false,
1040            })
1041            .commands_enabled(true)
1042            .build();
1043
1044        assert_eq!(worker.public_endpoints[0].name, "api");
1045        assert_eq!(worker.commands_enabled, true);
1046    }
1047
1048    #[test]
1049    fn worker_rejects_multiple_apex_public_endpoints() {
1050        let worker = Worker::new("apex-worker".to_string())
1051            .code(WorkerCode::Image {
1052                image: "test-image".to_string(),
1053            })
1054            .permissions("execution".to_string())
1055            .public_endpoint(WorkerPublicEndpoint {
1056                name: "api".to_string(),
1057                host_label: Some(APEX_HOST_LABEL.to_string()),
1058                wildcard_subdomains: false,
1059            })
1060            .public_endpoint(WorkerPublicEndpoint {
1061                name: "admin".to_string(),
1062                host_label: Some(APEX_HOST_LABEL.to_string()),
1063                wildcard_subdomains: false,
1064            })
1065            .build();
1066
1067        assert!(worker.validate_public_endpoints().is_err());
1068    }
1069}