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