daemon_detect/identity.rs
1//! The service identity a daemon detects itself under.
2
3use crate::markers::DaemonMarkers;
4use crate::state::DaemonState;
5use crate::values::{
6 BinaryName,
7 LaunchdLabelPrefix,
8 ServiceInstance,
9};
10
11/// How this process is named as an OS service.
12///
13/// Combines the binary name (used by systemd and Windows), a
14/// reverse-DNS label prefix (used by launchd), and an instance
15/// discriminator (a port, an identity key, …) so one binary can run
16/// multiple service instances.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ServiceIdentity {
19 binary_name: BinaryName,
20 launchd_prefix: LaunchdLabelPrefix,
21 instance: ServiceInstance,
22}
23
24impl ServiceIdentity {
25 /// Describe a service instance from already-validated values.
26 ///
27 /// - `binary_name` — the installed binary, e.g. `my-daemon`;
28 /// - `launchd_prefix` — the reverse-DNS launchd prefix, e.g.
29 /// `com.example.my-daemon`;
30 /// - `instance` — the per-instance suffix, e.g. an HTTP port or a node
31 /// identity key. A `u16` port converts directly.
32 #[must_use]
33 pub fn new(
34 binary_name: BinaryName,
35 launchd_prefix: LaunchdLabelPrefix,
36 instance: impl Into<ServiceInstance>,
37 ) -> Self {
38 Self {
39 binary_name,
40 launchd_prefix,
41 instance: instance.into(),
42 }
43 }
44
45 /// The macOS launchd label: `{launchd_prefix}.{instance}`.
46 #[must_use]
47 pub fn launchd_label(&self) -> String {
48 format!("{}.{}", self.launchd_prefix, self.instance)
49 }
50
51 /// The Linux systemd template-unit name:
52 /// `{binary_name}@{instance}.service`.
53 #[must_use]
54 pub fn systemd_unit_name(&self) -> String {
55 format!("{}@{}.service", self.binary_name, self.instance)
56 }
57
58 /// The Windows service name: `{binary_name}-{instance}`.
59 #[must_use]
60 pub fn windows_service_name(&self) -> String {
61 format!("{}-{}", self.binary_name, self.instance)
62 }
63
64 /// The service label for the platform this process runs on.
65 #[must_use]
66 pub fn service_label(&self) -> String {
67 if cfg!(target_os = "macos") {
68 self.launchd_label()
69 } else if cfg!(windows) {
70 self.windows_service_name()
71 } else {
72 self.systemd_unit_name()
73 }
74 }
75
76 /// Full daemon detection for this identity: whether the process
77 /// is a daemon and, when it is, the derived service label and
78 /// system-versus-user mode.
79 #[must_use]
80 pub fn detect(&self, markers: &DaemonMarkers) -> DaemonState {
81 crate::platform::detect_impl(self, markers)
82 }
83}