Skip to main content

alien_core/resources/
daemon.rs

1use crate::error::{ErrorData, Result};
2use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
3use crate::resources::{
4    ComputeCluster, ExposeProtocol, HealthCheck, PublicEndpoint, PublicEndpointOutput,
5    ResourceSpec, ToolchainConfig, WorkloadPriority, APEX_HOST_LABEL,
6};
7use alien_error::AlienError;
8use bon::Builder;
9use serde::{Deserialize, Serialize};
10use std::any::Any;
11use std::collections::HashMap;
12use std::fmt::Debug;
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
16#[serde(rename_all = "camelCase", tag = "type")]
17pub enum DaemonCode {
18    #[serde(rename_all = "camelCase")]
19    Image { image: String },
20    #[serde(rename_all = "camelCase")]
21    Source {
22        src: String,
23        toolchain: ToolchainConfig,
24    },
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
29#[serde(rename_all = "camelCase", deny_unknown_fields)]
30pub struct DaemonRuntimeMount {
31    /// Absolute host path to mount into the daemon container.
32    pub source: String,
33    /// Absolute container path where the source is mounted.
34    pub target: String,
35    /// Optional mount options understood by the backend runtime.
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub options: Option<String>,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
41#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
42#[serde(rename_all = "camelCase", deny_unknown_fields)]
43pub struct DaemonRuntime {
44    /// Run the daemon container with elevated host capabilities.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub privileged: Option<bool>,
47    /// Process namespace mode. Supported values are `host` and `private`.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub pid_namespace: Option<String>,
50    /// Network mode. Supported values are `host` and `appnet`.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub network_mode: Option<String>,
53    /// Host mounts exposed to the daemon container.
54    #[serde(default, skip_serializing_if = "Vec::is_empty")]
55    pub mounts: Vec<DaemonRuntimeMount>,
56    /// Runtime user, as a numeric uid or uid:gid string.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub user: Option<String>,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
62#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
63#[serde(rename_all = "camelCase", deny_unknown_fields)]
64#[builder(start_fn = new)]
65pub struct Daemon {
66    #[builder(start_fn)]
67    pub id: String,
68    #[builder(field)]
69    pub links: Vec<ResourceRef>,
70    /// Public endpoints exposed by the daemon.
71    #[builder(field)]
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub public_endpoints: Vec<PublicEndpoint>,
74    /// HTTP health check for public daemon endpoint load balancers.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub health_check: Option<HealthCheck>,
77    /// ComputeCluster resource ID that this daemon runs on for managed cloud
78    /// compute backends. Kubernetes and Local runtimes ignore this field.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub cluster: Option<String>,
81    /// Named workload permission profile. Absent means no workload cloud identity.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub permissions: Option<String>,
84    pub code: DaemonCode,
85    /// CPU resource requirements for each daemon instance.
86    #[builder(default = default_daemon_cpu())]
87    #[serde(default = "default_daemon_cpu")]
88    pub cpu: ResourceSpec,
89    /// Memory resource requirements for each daemon instance.
90    #[builder(default = default_daemon_memory())]
91    #[serde(default = "default_daemon_memory")]
92    pub memory: ResourceSpec,
93    /// Capacity group/pool to run on for backends that expose machine pools.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub pool: Option<String>,
96    /// Command to override the image default.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub command: Option<Vec<String>>,
99    /// Grace period in seconds for stopping daemon instances during updates, drains, and deletes.
100    ///
101    /// When omitted, the runtime backend applies its default. Valid values are
102    /// 1 second through 24 hours.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    #[cfg_attr(feature = "openapi", schema(minimum = 1, maximum = 86400))]
105    pub stop_grace_period_seconds: Option<u32>,
106    /// Relative scheduling importance. On Kubernetes the cluster administrator maps each
107    /// level to a PriorityClass at install time; unset leaves the pod without one. Other
108    /// platforms ignore it.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub priority: Option<WorkloadPriority>,
111    /// Optional backend runtime settings for trusted daemons.
112    ///
113    /// These settings are intended for daemon-style infrastructure that must
114    /// operate on the host. Backends that do not support a setting may reject
115    /// it during provisioning.
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub runtime: Option<DaemonRuntime>,
118    /// Pod Security profile. Absent means no pod security settings are
119    /// applied and the image runs as built; set `profile: restricted` to
120    /// apply the restricted profile.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub security: Option<crate::ContainerSecurity>,
123    #[builder(default)]
124    #[serde(default)]
125    pub environment: HashMap<String, String>,
126    /// Whether an app-owned command receiver can lease pending commands for
127    /// this Daemon and execute registered handlers.
128    #[builder(default = default_commands_enabled())]
129    #[serde(default = "default_commands_enabled")]
130    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
131    pub commands_enabled: bool,
132
133    /// Set by `alien build` when the daemon's command receiver reads its
134    /// credential from `ALIEN_COMMANDS_CAPABILITY_FILE`. Absent means the
135    /// receiver may be older, so a deployer that rotates credentials keeps
136    /// the long-lived `ALIEN_COMMANDS_TOKEN` for it. Build output replaces any
137    /// value written in the stack definition.
138    #[builder(default)]
139    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
140    pub commands_capability_file: bool,
141}
142
143impl Daemon {
144    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("daemon");
145
146    pub fn get_permissions(&self) -> Option<&str> {
147        self.permissions.as_deref()
148    }
149
150    fn validate_public_endpoints(&self) -> Result<()> {
151        let mut endpoint_names = std::collections::HashSet::new();
152        let mut backend_ports = std::collections::HashSet::new();
153        let mut apex_endpoint_name: Option<&str> = None;
154
155        for endpoint in &self.public_endpoints {
156            endpoint.validate_for_resource(&self.id)?;
157            if !endpoint_names.insert(endpoint.name.as_str()) {
158                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
159                    resource_id: self.id.clone(),
160                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
161                }));
162            }
163            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
164                if let Some(existing_name) = apex_endpoint_name {
165                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
166                        resource_id: self.id.clone(),
167                        reason: format!(
168                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
169                            existing_name
170                        ),
171                    }));
172                }
173                apex_endpoint_name = Some(endpoint.name.as_str());
174            }
175            backend_ports.insert(endpoint.port);
176            if endpoint.protocol != ExposeProtocol::Http {
177                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
178                    resource_id: self.id.clone(),
179                    reason: "daemon public endpoints currently support only HTTP".to_string(),
180                }));
181            }
182        }
183
184        if backend_ports.len() > 1 {
185            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
186                resource_id: self.id.clone(),
187                reason:
188                    "public endpoints on one daemon must currently route to the same backend port"
189                        .to_string(),
190            }));
191        }
192
193        Ok(())
194    }
195
196    fn validate_runtime(&self) -> Result<()> {
197        let Some(runtime) = &self.runtime else {
198            return Ok(());
199        };
200
201        if let Some(pid_namespace) = &runtime.pid_namespace {
202            if pid_namespace != "host" && pid_namespace != "private" {
203                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
204                    resource_id: self.id.clone(),
205                    reason: "runtime.pidNamespace must be 'host' or 'private'".to_string(),
206                }));
207            }
208        }
209
210        if let Some(network_mode) = &runtime.network_mode {
211            if network_mode != "host" && network_mode != "appnet" {
212                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
213                    resource_id: self.id.clone(),
214                    reason: "runtime.networkMode must be 'host' or 'appnet'".to_string(),
215                }));
216            }
217        }
218
219        if let Some(user) = &runtime.user {
220            let valid = match user.split_once(':') {
221                Some((uid, gid)) => {
222                    !uid.is_empty()
223                        && !gid.is_empty()
224                        && uid.chars().all(|c| c.is_ascii_digit())
225                        && gid.chars().all(|c| c.is_ascii_digit())
226                }
227                None => !user.is_empty() && user.chars().all(|c| c.is_ascii_digit()),
228            };
229            if !valid {
230                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
231                    resource_id: self.id.clone(),
232                    reason: "runtime.user must be a numeric uid or uid:gid".to_string(),
233                }));
234            }
235        }
236
237        for mount in &runtime.mounts {
238            if mount.source.is_empty() || mount.target.is_empty() {
239                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
240                    resource_id: self.id.clone(),
241                    reason: "runtime.mounts source and target must be non-empty".to_string(),
242                }));
243            }
244            if !mount.source.starts_with('/') || !mount.target.starts_with('/') {
245                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
246                    resource_id: self.id.clone(),
247                    reason: "runtime.mounts source and target must be absolute paths".to_string(),
248                }));
249            }
250        }
251
252        Ok(())
253    }
254}
255
256fn default_commands_enabled() -> bool {
257    false
258}
259
260/// CPU a daemon reserves when it does not say.
261pub fn default_daemon_cpu() -> ResourceSpec {
262    ResourceSpec {
263        min: "0.1".to_string(),
264        desired: "0.1".to_string(),
265    }
266}
267
268/// Memory a daemon reserves when it does not say.
269pub fn default_daemon_memory() -> ResourceSpec {
270    ResourceSpec {
271        min: "128Mi".to_string(),
272        desired: "128Mi".to_string(),
273    }
274}
275
276impl<S: daemon_builder::State> DaemonBuilder<S> {
277    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
278    where
279        for<'a> &'a R: Into<ResourceRef>,
280    {
281        let resource_ref: ResourceRef = resource.into();
282        self.links.push(resource_ref);
283        self
284    }
285
286    pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
287        self.public_endpoints.push(endpoint);
288        self
289    }
290}
291
292impl ResourceDefinition for Daemon {
293    fn get_resource_type(&self) -> ResourceType {
294        Self::RESOURCE_TYPE
295    }
296
297    fn id(&self) -> &str {
298        &self.id
299    }
300
301    fn replace_after_failed_create_is_safe(&self) -> bool {
302        // A create that timed out may already run replicas; deleting it stops them all, while
303        // creating it again updates the daemon in place.
304        false
305    }
306
307    fn get_dependencies(&self) -> Vec<ResourceRef> {
308        let mut dependencies = self.links.clone();
309        if let Some(cluster) = &self.cluster {
310            dependencies.push(ResourceRef::new(
311                ComputeCluster::RESOURCE_TYPE,
312                cluster.clone(),
313            ));
314        }
315        dependencies
316    }
317
318    fn get_permissions(&self) -> Option<&str> {
319        self.permissions.as_deref()
320    }
321
322    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
323        let new_daemon = new_config
324            .as_any()
325            .downcast_ref::<Daemon>()
326            .ok_or_else(|| {
327                AlienError::new(ErrorData::UnexpectedResourceType {
328                    resource_id: self.id.clone(),
329                    expected: Self::RESOURCE_TYPE,
330                    actual: new_config.get_resource_type(),
331                })
332            })?;
333
334        if self.id != new_daemon.id {
335            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
336                resource_id: self.id.clone(),
337                reason: "the 'id' field is immutable".to_string(),
338            }));
339        }
340
341        self.validate_public_endpoints()?;
342        new_daemon.validate_public_endpoints()?;
343        self.validate_runtime()?;
344        new_daemon.validate_runtime()?;
345
346        if self.public_endpoints != new_daemon.public_endpoints {
347            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
348                resource_id: self.id.clone(),
349                reason: "the 'publicEndpoints' field is immutable".to_string(),
350            }));
351        }
352
353        Ok(())
354    }
355
356    fn as_any(&self) -> &dyn Any {
357        self
358    }
359
360    fn as_any_mut(&mut self) -> &mut dyn Any {
361        self
362    }
363
364    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
365        Box::new(self.clone())
366    }
367
368    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
369        other.as_any().downcast_ref::<Daemon>() == Some(self)
370    }
371
372    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
373        serde_json::to_value(self)
374    }
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
378#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
379#[serde(rename_all = "camelCase")]
380pub struct DaemonOutputs {
381    pub daemon_name: String,
382    pub running: bool,
383    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
384    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
385}
386
387impl ResourceOutputsDefinition for DaemonOutputs {
388    fn get_resource_type(&self) -> ResourceType {
389        Daemon::RESOURCE_TYPE.clone()
390    }
391
392    fn as_any(&self) -> &dyn Any {
393        self
394    }
395
396    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
397        Box::new(self.clone())
398    }
399
400    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
401        other.as_any().downcast_ref::<DaemonOutputs>() == Some(self)
402    }
403
404    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
405        serde_json::to_value(self)
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn daemon_without_permissions_preserves_links_without_an_identity() {
415        let storage = crate::Storage::new("objects".to_string()).build();
416        let daemon = Daemon::new("observer".to_string())
417            .code(DaemonCode::Image {
418                image: "observer:latest".to_string(),
419            })
420            .link(&storage)
421            .build();
422        assert_eq!(daemon.get_permissions(), None);
423        assert_eq!(ResourceDefinition::get_permissions(&daemon), None);
424        assert_eq!(daemon.get_dependencies(), daemon.links);
425        assert_eq!(daemon.links[0].id(), "objects");
426        let json = serde_json::to_value(&daemon).unwrap();
427        assert!(json.get("permissions").is_none());
428        let decoded: Daemon = serde_json::from_value(json).unwrap();
429        assert_eq!(decoded, daemon);
430
431        let mut explicit = serde_json::to_value(&daemon).unwrap();
432        explicit["permissions"] = serde_json::json!("reader");
433        let decoded: Daemon = serde_json::from_value(explicit.clone()).unwrap();
434        assert_eq!(decoded.get_permissions(), Some("reader"));
435        assert_eq!(
436            ResourceDefinition::get_permissions(&decoded),
437            Some("reader")
438        );
439        assert_eq!(serde_json::to_value(decoded).unwrap(), explicit);
440    }
441
442    #[test]
443    fn daemon_serializes_with_resource_type() {
444        let daemon = Daemon::new("endpoint-agent".to_string())
445            .code(DaemonCode::Source {
446                src: "./agent".to_string(),
447                toolchain: ToolchainConfig::Rust {
448                    binary_name: "agent".to_string(),
449                },
450            })
451            .permissions("execution".to_string())
452            .commands_enabled(true)
453            .build();
454
455        let resource = crate::Resource::new(daemon);
456        let json = serde_json::to_value(&resource).expect("daemon should serialize");
457        assert_eq!(json["type"], "daemon");
458
459        let roundtrip: crate::Resource =
460            serde_json::from_value(json).expect("daemon should deserialize");
461        assert_eq!(roundtrip.resource_type().as_ref(), "daemon");
462    }
463
464    #[test]
465    fn daemon_accepts_one_public_http_endpoint() {
466        let daemon = Daemon::new("gateway".to_string())
467            .code(DaemonCode::Image {
468                image: "gateway:latest".to_string(),
469            })
470            .public_endpoint(PublicEndpoint {
471                name: "public".to_string(),
472                port: 8080,
473                protocol: ExposeProtocol::Http,
474                host_label: Some("public".to_string()),
475                wildcard_subdomains: true,
476            })
477            .permissions("gateway".to_string())
478            .build();
479
480        assert!(daemon.validate_public_endpoints().is_ok());
481        assert_eq!(daemon.public_endpoints.len(), 1);
482        assert_eq!(
483            daemon.public_endpoints[0].host_label.as_deref(),
484            Some("public")
485        );
486        assert!(daemon.public_endpoints[0].wildcard_subdomains);
487    }
488
489    #[test]
490    fn daemon_serializes_stop_grace_period_when_set() {
491        let daemon = Daemon::new("gateway".to_string())
492            .code(DaemonCode::Image {
493                image: "gateway:latest".to_string(),
494            })
495            .permissions("gateway".to_string())
496            .stop_grace_period_seconds(21_600)
497            .build();
498
499        let json = serde_json::to_value(&daemon).expect("daemon should serialize");
500        assert_eq!(json["stopGracePeriodSeconds"], 21_600);
501    }
502
503    #[test]
504    fn daemon_omits_stop_grace_period_when_absent() {
505        let daemon = Daemon::new("gateway".to_string())
506            .code(DaemonCode::Image {
507                image: "gateway:latest".to_string(),
508            })
509            .permissions("gateway".to_string())
510            .build();
511
512        let json = serde_json::to_value(&daemon).expect("daemon should serialize");
513        assert!(json.get("stopGracePeriodSeconds").is_none());
514    }
515
516    #[test]
517    fn daemon_rejects_multiple_backend_ports_or_non_http_public_endpoints() {
518        let multiple = Daemon::new("gateway".to_string())
519            .code(DaemonCode::Image {
520                image: "gateway:latest".to_string(),
521            })
522            .public_endpoint(PublicEndpoint {
523                name: "api".to_string(),
524                port: 8080,
525                protocol: ExposeProtocol::Http,
526                host_label: None,
527                wildcard_subdomains: false,
528            })
529            .public_endpoint(PublicEndpoint {
530                name: "admin".to_string(),
531                port: 9090,
532                protocol: ExposeProtocol::Http,
533                host_label: None,
534                wildcard_subdomains: false,
535            })
536            .permissions("gateway".to_string())
537            .build();
538        assert!(multiple.validate_public_endpoints().is_err());
539
540        let tcp = Daemon::new("gateway".to_string())
541            .code(DaemonCode::Image {
542                image: "gateway:latest".to_string(),
543            })
544            .public_endpoint(PublicEndpoint {
545                name: "api".to_string(),
546                port: 8080,
547                protocol: ExposeProtocol::Tcp,
548                host_label: None,
549                wildcard_subdomains: false,
550            })
551            .permissions("gateway".to_string())
552            .build();
553        assert!(tcp.validate_public_endpoints().is_err());
554    }
555
556    #[test]
557    fn daemon_rejects_multiple_apex_public_endpoints() {
558        let daemon = Daemon::new("gateway".to_string())
559            .code(DaemonCode::Image {
560                image: "gateway:latest".to_string(),
561            })
562            .public_endpoint(PublicEndpoint {
563                name: "api".to_string(),
564                port: 8080,
565                protocol: ExposeProtocol::Http,
566                host_label: Some(APEX_HOST_LABEL.to_string()),
567                wildcard_subdomains: false,
568            })
569            .public_endpoint(PublicEndpoint {
570                name: "admin".to_string(),
571                port: 8080,
572                protocol: ExposeProtocol::Http,
573                host_label: Some(APEX_HOST_LABEL.to_string()),
574                wildcard_subdomains: false,
575            })
576            .permissions("gateway".to_string())
577            .build();
578
579        assert!(daemon.validate_public_endpoints().is_err());
580    }
581}