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    #[builder(default)]
119    #[serde(default)]
120    pub environment: HashMap<String, String>,
121    /// Whether an app-owned command receiver can lease pending commands for
122    /// this Daemon and execute registered handlers.
123    #[builder(default = default_commands_enabled())]
124    #[serde(default = "default_commands_enabled")]
125    #[cfg_attr(feature = "openapi", schema(default = default_commands_enabled))]
126    pub commands_enabled: bool,
127
128    /// Set by `alien build` when the daemon's command receiver reads its
129    /// credential from `ALIEN_COMMANDS_CAPABILITY_FILE`. Absent means the
130    /// receiver may be older, so a deployer that rotates credentials keeps
131    /// the long-lived `ALIEN_COMMANDS_TOKEN` for it. Build output replaces any
132    /// value written in the stack definition.
133    #[builder(default)]
134    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
135    pub commands_capability_file: bool,
136}
137
138impl Daemon {
139    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("daemon");
140
141    pub fn get_permissions(&self) -> Option<&str> {
142        self.permissions.as_deref()
143    }
144
145    fn validate_public_endpoints(&self) -> Result<()> {
146        let mut endpoint_names = std::collections::HashSet::new();
147        let mut backend_ports = std::collections::HashSet::new();
148        let mut apex_endpoint_name: Option<&str> = None;
149
150        for endpoint in &self.public_endpoints {
151            endpoint.validate_for_resource(&self.id)?;
152            if !endpoint_names.insert(endpoint.name.as_str()) {
153                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
154                    resource_id: self.id.clone(),
155                    reason: format!("duplicate public endpoint name '{}'", endpoint.name),
156                }));
157            }
158            if endpoint.host_label.as_deref() == Some(APEX_HOST_LABEL) {
159                if let Some(existing_name) = apex_endpoint_name {
160                    return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
161                        resource_id: self.id.clone(),
162                        reason: format!(
163                            "only one apex public endpoint is allowed per resource; '{}' already uses hostLabel '@'",
164                            existing_name
165                        ),
166                    }));
167                }
168                apex_endpoint_name = Some(endpoint.name.as_str());
169            }
170            backend_ports.insert(endpoint.port);
171            if endpoint.protocol != ExposeProtocol::Http {
172                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
173                    resource_id: self.id.clone(),
174                    reason: "daemon public endpoints currently support only HTTP".to_string(),
175                }));
176            }
177        }
178
179        if backend_ports.len() > 1 {
180            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
181                resource_id: self.id.clone(),
182                reason:
183                    "public endpoints on one daemon must currently route to the same backend port"
184                        .to_string(),
185            }));
186        }
187
188        Ok(())
189    }
190
191    fn validate_runtime(&self) -> Result<()> {
192        let Some(runtime) = &self.runtime else {
193            return Ok(());
194        };
195
196        if let Some(pid_namespace) = &runtime.pid_namespace {
197            if pid_namespace != "host" && pid_namespace != "private" {
198                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
199                    resource_id: self.id.clone(),
200                    reason: "runtime.pidNamespace must be 'host' or 'private'".to_string(),
201                }));
202            }
203        }
204
205        if let Some(network_mode) = &runtime.network_mode {
206            if network_mode != "host" && network_mode != "appnet" {
207                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
208                    resource_id: self.id.clone(),
209                    reason: "runtime.networkMode must be 'host' or 'appnet'".to_string(),
210                }));
211            }
212        }
213
214        if let Some(user) = &runtime.user {
215            let valid = match user.split_once(':') {
216                Some((uid, gid)) => {
217                    !uid.is_empty()
218                        && !gid.is_empty()
219                        && uid.chars().all(|c| c.is_ascii_digit())
220                        && gid.chars().all(|c| c.is_ascii_digit())
221                }
222                None => !user.is_empty() && user.chars().all(|c| c.is_ascii_digit()),
223            };
224            if !valid {
225                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
226                    resource_id: self.id.clone(),
227                    reason: "runtime.user must be a numeric uid or uid:gid".to_string(),
228                }));
229            }
230        }
231
232        for mount in &runtime.mounts {
233            if mount.source.is_empty() || mount.target.is_empty() {
234                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
235                    resource_id: self.id.clone(),
236                    reason: "runtime.mounts source and target must be non-empty".to_string(),
237                }));
238            }
239            if !mount.source.starts_with('/') || !mount.target.starts_with('/') {
240                return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
241                    resource_id: self.id.clone(),
242                    reason: "runtime.mounts source and target must be absolute paths".to_string(),
243                }));
244            }
245        }
246
247        Ok(())
248    }
249}
250
251fn default_commands_enabled() -> bool {
252    false
253}
254
255/// CPU a daemon reserves when it does not say.
256pub fn default_daemon_cpu() -> ResourceSpec {
257    ResourceSpec {
258        min: "0.1".to_string(),
259        desired: "0.1".to_string(),
260    }
261}
262
263/// Memory a daemon reserves when it does not say.
264pub fn default_daemon_memory() -> ResourceSpec {
265    ResourceSpec {
266        min: "128Mi".to_string(),
267        desired: "128Mi".to_string(),
268    }
269}
270
271impl<S: daemon_builder::State> DaemonBuilder<S> {
272    pub fn link<R: ?Sized>(mut self, resource: &R) -> Self
273    where
274        for<'a> &'a R: Into<ResourceRef>,
275    {
276        let resource_ref: ResourceRef = resource.into();
277        self.links.push(resource_ref);
278        self
279    }
280
281    pub fn public_endpoint(mut self, endpoint: PublicEndpoint) -> Self {
282        self.public_endpoints.push(endpoint);
283        self
284    }
285}
286
287impl ResourceDefinition for Daemon {
288    fn get_resource_type(&self) -> ResourceType {
289        Self::RESOURCE_TYPE
290    }
291
292    fn id(&self) -> &str {
293        &self.id
294    }
295
296    fn replace_after_failed_create_is_safe(&self) -> bool {
297        // A create that timed out may already run replicas; deleting it stops them all, while
298        // creating it again updates the daemon in place.
299        false
300    }
301
302    fn get_dependencies(&self) -> Vec<ResourceRef> {
303        let mut dependencies = self.links.clone();
304        if let Some(cluster) = &self.cluster {
305            dependencies.push(ResourceRef::new(
306                ComputeCluster::RESOURCE_TYPE,
307                cluster.clone(),
308            ));
309        }
310        dependencies
311    }
312
313    fn get_permissions(&self) -> Option<&str> {
314        self.permissions.as_deref()
315    }
316
317    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
318        let new_daemon = new_config
319            .as_any()
320            .downcast_ref::<Daemon>()
321            .ok_or_else(|| {
322                AlienError::new(ErrorData::UnexpectedResourceType {
323                    resource_id: self.id.clone(),
324                    expected: Self::RESOURCE_TYPE,
325                    actual: new_config.get_resource_type(),
326                })
327            })?;
328
329        if self.id != new_daemon.id {
330            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
331                resource_id: self.id.clone(),
332                reason: "the 'id' field is immutable".to_string(),
333            }));
334        }
335
336        self.validate_public_endpoints()?;
337        new_daemon.validate_public_endpoints()?;
338        self.validate_runtime()?;
339        new_daemon.validate_runtime()?;
340
341        if self.public_endpoints != new_daemon.public_endpoints {
342            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
343                resource_id: self.id.clone(),
344                reason: "the 'publicEndpoints' field is immutable".to_string(),
345            }));
346        }
347
348        Ok(())
349    }
350
351    fn as_any(&self) -> &dyn Any {
352        self
353    }
354
355    fn as_any_mut(&mut self) -> &mut dyn Any {
356        self
357    }
358
359    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
360        Box::new(self.clone())
361    }
362
363    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
364        other.as_any().downcast_ref::<Daemon>() == Some(self)
365    }
366
367    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
368        serde_json::to_value(self)
369    }
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
374#[serde(rename_all = "camelCase")]
375pub struct DaemonOutputs {
376    pub daemon_name: String,
377    pub running: bool,
378    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
379    pub public_endpoints: HashMap<String, PublicEndpointOutput>,
380}
381
382impl ResourceOutputsDefinition for DaemonOutputs {
383    fn get_resource_type(&self) -> ResourceType {
384        Daemon::RESOURCE_TYPE.clone()
385    }
386
387    fn as_any(&self) -> &dyn Any {
388        self
389    }
390
391    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
392        Box::new(self.clone())
393    }
394
395    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
396        other.as_any().downcast_ref::<DaemonOutputs>() == Some(self)
397    }
398
399    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
400        serde_json::to_value(self)
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    #[test]
409    fn daemon_without_permissions_preserves_links_without_an_identity() {
410        let storage = crate::Storage::new("objects".to_string()).build();
411        let daemon = Daemon::new("observer".to_string())
412            .code(DaemonCode::Image {
413                image: "observer:latest".to_string(),
414            })
415            .link(&storage)
416            .build();
417        assert_eq!(daemon.get_permissions(), None);
418        assert_eq!(ResourceDefinition::get_permissions(&daemon), None);
419        assert_eq!(daemon.get_dependencies(), daemon.links);
420        assert_eq!(daemon.links[0].id(), "objects");
421        let json = serde_json::to_value(&daemon).unwrap();
422        assert!(json.get("permissions").is_none());
423        let decoded: Daemon = serde_json::from_value(json).unwrap();
424        assert_eq!(decoded, daemon);
425
426        let mut explicit = serde_json::to_value(&daemon).unwrap();
427        explicit["permissions"] = serde_json::json!("reader");
428        let decoded: Daemon = serde_json::from_value(explicit.clone()).unwrap();
429        assert_eq!(decoded.get_permissions(), Some("reader"));
430        assert_eq!(
431            ResourceDefinition::get_permissions(&decoded),
432            Some("reader")
433        );
434        assert_eq!(serde_json::to_value(decoded).unwrap(), explicit);
435    }
436
437    #[test]
438    fn daemon_serializes_with_resource_type() {
439        let daemon = Daemon::new("endpoint-agent".to_string())
440            .code(DaemonCode::Source {
441                src: "./agent".to_string(),
442                toolchain: ToolchainConfig::Rust {
443                    binary_name: "agent".to_string(),
444                },
445            })
446            .permissions("execution".to_string())
447            .commands_enabled(true)
448            .build();
449
450        let resource = crate::Resource::new(daemon);
451        let json = serde_json::to_value(&resource).expect("daemon should serialize");
452        assert_eq!(json["type"], "daemon");
453
454        let roundtrip: crate::Resource =
455            serde_json::from_value(json).expect("daemon should deserialize");
456        assert_eq!(roundtrip.resource_type().as_ref(), "daemon");
457    }
458
459    #[test]
460    fn daemon_accepts_one_public_http_endpoint() {
461        let daemon = Daemon::new("gateway".to_string())
462            .code(DaemonCode::Image {
463                image: "gateway:latest".to_string(),
464            })
465            .public_endpoint(PublicEndpoint {
466                name: "public".to_string(),
467                port: 8080,
468                protocol: ExposeProtocol::Http,
469                host_label: Some("public".to_string()),
470                wildcard_subdomains: true,
471            })
472            .permissions("gateway".to_string())
473            .build();
474
475        assert!(daemon.validate_public_endpoints().is_ok());
476        assert_eq!(daemon.public_endpoints.len(), 1);
477        assert_eq!(
478            daemon.public_endpoints[0].host_label.as_deref(),
479            Some("public")
480        );
481        assert!(daemon.public_endpoints[0].wildcard_subdomains);
482    }
483
484    #[test]
485    fn daemon_serializes_stop_grace_period_when_set() {
486        let daemon = Daemon::new("gateway".to_string())
487            .code(DaemonCode::Image {
488                image: "gateway:latest".to_string(),
489            })
490            .permissions("gateway".to_string())
491            .stop_grace_period_seconds(21_600)
492            .build();
493
494        let json = serde_json::to_value(&daemon).expect("daemon should serialize");
495        assert_eq!(json["stopGracePeriodSeconds"], 21_600);
496    }
497
498    #[test]
499    fn daemon_omits_stop_grace_period_when_absent() {
500        let daemon = Daemon::new("gateway".to_string())
501            .code(DaemonCode::Image {
502                image: "gateway:latest".to_string(),
503            })
504            .permissions("gateway".to_string())
505            .build();
506
507        let json = serde_json::to_value(&daemon).expect("daemon should serialize");
508        assert!(json.get("stopGracePeriodSeconds").is_none());
509    }
510
511    #[test]
512    fn daemon_rejects_multiple_backend_ports_or_non_http_public_endpoints() {
513        let multiple = Daemon::new("gateway".to_string())
514            .code(DaemonCode::Image {
515                image: "gateway:latest".to_string(),
516            })
517            .public_endpoint(PublicEndpoint {
518                name: "api".to_string(),
519                port: 8080,
520                protocol: ExposeProtocol::Http,
521                host_label: None,
522                wildcard_subdomains: false,
523            })
524            .public_endpoint(PublicEndpoint {
525                name: "admin".to_string(),
526                port: 9090,
527                protocol: ExposeProtocol::Http,
528                host_label: None,
529                wildcard_subdomains: false,
530            })
531            .permissions("gateway".to_string())
532            .build();
533        assert!(multiple.validate_public_endpoints().is_err());
534
535        let tcp = Daemon::new("gateway".to_string())
536            .code(DaemonCode::Image {
537                image: "gateway:latest".to_string(),
538            })
539            .public_endpoint(PublicEndpoint {
540                name: "api".to_string(),
541                port: 8080,
542                protocol: ExposeProtocol::Tcp,
543                host_label: None,
544                wildcard_subdomains: false,
545            })
546            .permissions("gateway".to_string())
547            .build();
548        assert!(tcp.validate_public_endpoints().is_err());
549    }
550
551    #[test]
552    fn daemon_rejects_multiple_apex_public_endpoints() {
553        let daemon = Daemon::new("gateway".to_string())
554            .code(DaemonCode::Image {
555                image: "gateway:latest".to_string(),
556            })
557            .public_endpoint(PublicEndpoint {
558                name: "api".to_string(),
559                port: 8080,
560                protocol: ExposeProtocol::Http,
561                host_label: Some(APEX_HOST_LABEL.to_string()),
562                wildcard_subdomains: false,
563            })
564            .public_endpoint(PublicEndpoint {
565                name: "admin".to_string(),
566                port: 8080,
567                protocol: ExposeProtocol::Http,
568                host_label: Some(APEX_HOST_LABEL.to_string()),
569                wildcard_subdomains: false,
570            })
571            .permissions("gateway".to_string())
572            .build();
573
574        assert!(daemon.validate_public_endpoints().is_err());
575    }
576}