Skip to main content

sys_lib/
instance.rs

1//! Instance info: facts fixed when this process **started**, answering
2//! "which running copy is this?" when several run at once. Put the instance id
3//! in every log line, audit record, and metric so events from two processes are
4//! never mixed up.
5//!
6//! ```
7//! use sys_lib::Instance;
8//!
9//! let me = Instance::start();
10//! println!("{me}");                                 // 01J9ZQ4M8T6Y2K5V3W1X7R0B9C web-01 pid 48213 up 0s
11//! eprintln!("instance={} event=boot", me.id());     // tag every log line
12//! assert!(std::ptr::eq(me, Instance::start()));    // one instance per process
13//! ```
14
15use core::{fmt, str::FromStr};
16use std::{
17    sync::OnceLock,
18    time::{Duration, SystemTime},
19};
20
21use clock_lib::{Monotonic, Wall};
22use id_forge::ulid::Ulid;
23
24use crate::{
25    Error, Result,
26    fmt::{json_str, kv},
27};
28
29static INSTANCE: OnceLock<Instance> = OnceLock::new();
30
31/// The running copy of this program. Created once per process by
32/// [`Instance::start`]; every caller sees the same value.
33pub struct Instance {
34    id: InstanceId,
35    started_at: SystemTime,
36    start: Monotonic,
37    host: String,
38    pid: u32,
39    user: String,
40}
41
42/// The instance created by [`Instance::start`], or `None` before the first call.
43///
44/// ```
45/// sys_lib::Instance::start();
46/// assert!(sys_lib::instance::current().is_some());
47/// ```
48#[must_use]
49pub fn current() -> Option<&'static Instance> {
50    INSTANCE.get()
51}
52
53impl Instance {
54    /// Creates the instance on the first call and returns it on every call.
55    /// Never fails: an unreadable host or user name becomes `"unknown"`. Safe to
56    /// call from many threads at once; exactly one instance is created (E-62).
57    ///
58    /// Cost: the first call creates a ULID and reads the host and user names
59    /// (5 to 20 µs [est.]); later calls about 1 ns.
60    pub fn start() -> &'static Instance {
61        INSTANCE.get_or_init(|| Instance {
62            id: InstanceId(*Ulid::new().as_bytes()),
63            started_at: SystemTime::now(),
64            start: Monotonic::now(),
65            host: crate::host::name()
66                .ok()
67                .filter(|h| !h.is_empty())
68                .unwrap_or_else(|| "unknown".to_owned()),
69            pid: std::process::id(),
70            user: crate::process::user()
71                .map(|u| u.name)
72                .ok()
73                .filter(|u| !u.is_empty())
74                .unwrap_or_else(|| "unknown".to_owned()),
75        })
76    }
77
78    /// The instance id, a ULID: sortable by start time, unique without coordination.
79    #[must_use]
80    pub fn id(&self) -> InstanceId {
81        self.id
82    }
83
84    /// When the process started (the wall clock at the first `start()`).
85    #[must_use]
86    pub fn started_at(&self) -> SystemTime {
87        self.started_at
88    }
89
90    /// How long ago it started, by the monotonic clock: wall-clock steps do not affect it.
91    #[must_use]
92    pub fn uptime(&self) -> Duration {
93        self.start.elapsed()
94    }
95
96    /// The host name at start, or `"unknown"`. An identifying value.
97    #[must_use]
98    pub fn host(&self) -> &str {
99        &self.host
100    }
101
102    /// The process id at start.
103    #[must_use]
104    pub fn pid(&self) -> u32 {
105        self.pid
106    }
107
108    /// The effective user at start, before any privilege drop, or `"unknown"`.
109    /// The current user is [`process::user()`](crate::process::user).
110    #[must_use]
111    pub fn user_at_start(&self) -> &str {
112        &self.user
113    }
114
115    /// False in a child created by `fork()` without `exec`, which inherits the
116    /// parent's instance: a forked worker must not log under the parent's id.
117    #[must_use]
118    pub fn is_current_process(&self) -> bool {
119        self.pid == std::process::id()
120    }
121
122    /// Writes `instance.id=... instance.started_at=... ...`, without allocating.
123    ///
124    /// ```
125    /// let mut line = String::new();
126    /// sys_lib::Instance::start().write_kv(&mut line)?;
127    /// assert!(line.starts_with("instance.id="));
128    /// # Ok::<(), std::fmt::Error>(())
129    /// ```
130    pub fn write_kv(&self, out: &mut impl fmt::Write) -> fmt::Result {
131        let mut id = crate::fmt::StackBuf::<32>::new();
132        fmt::Write::write_fmt(&mut id, format_args!("{}", self.id))?;
133        let mut started = crate::fmt::StackBuf::<48>::new();
134        fmt::Write::write_fmt(
135            &mut started,
136            format_args!("{:.0}", Wall::from(self.started_at)),
137        )?;
138        let mut pid = crate::fmt::StackBuf::<16>::new();
139        fmt::Write::write_fmt(&mut pid, format_args!("{}", self.pid))?;
140        kv(out, "instance.id", id.as_str())?;
141        out.write_char(' ')?;
142        kv(out, "instance.started_at", started.as_str())?;
143        out.write_char(' ')?;
144        kv(out, "instance.host", &self.host)?;
145        out.write_char(' ')?;
146        kv(out, "instance.pid", pid.as_str())?;
147        out.write_char(' ')?;
148        kv(out, "instance.user", &self.user)?;
149        write!(out, " instance.uptime_secs={}", self.uptime().as_secs())
150    }
151
152    /// Writes one JSON object, without allocating.
153    pub fn write_json(&self, out: &mut impl fmt::Write) -> fmt::Result {
154        write!(
155            out,
156            "{{\"id\":\"{}\",\"started_at\":\"{:.0}\",\"host\":",
157            self.id,
158            Wall::from(self.started_at)
159        )?;
160        json_str(out, &self.host)?;
161        write!(out, ",\"pid\":{},\"user\":", self.pid)?;
162        json_str(out, &self.user)?;
163        write!(out, ",\"uptime_secs\":{}}}", self.uptime().as_secs())
164    }
165}
166
167/// `01J9ZQ4M8T6Y2K5V3W1X7R0B9C web-01 pid 48213 up 3h12m04s`.
168impl fmt::Display for Instance {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        write!(f, "{} {} pid {} up ", self.id, self.host, self.pid)?;
171        write_uptime(f, self.uptime())
172    }
173}
174
175impl fmt::Debug for Instance {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        f.debug_struct("Instance")
178            .field("id", &self.id)
179            .field("started_at", &self.started_at)
180            .field("host", &self.host)
181            .field("pid", &self.pid)
182            .field("user", &self.user)
183            .finish()
184    }
185}
186
187/// `2d03h12m04s`, `3h12m04s`, `12m04s`, `4s`.
188fn write_uptime(f: &mut impl fmt::Write, d: Duration) -> fmt::Result {
189    let s = d.as_secs();
190    let (days, h, m, sec) = (s / 86_400, s / 3600 % 24, s / 60 % 60, s % 60);
191    if days > 0 {
192        write!(f, "{days}d{h:02}h{m:02}m{sec:02}s")
193    } else if h > 0 {
194        write!(f, "{h}h{m:02}m{sec:02}s")
195    } else if m > 0 {
196        write!(f, "{m}m{sec:02}s")
197    } else {
198        write!(f, "{sec}s")
199    }
200}
201
202/// An instance id: a 128-bit ULID, displayed as 26 Crockford base32 characters.
203///
204/// ```
205/// use sys_lib::InstanceId;
206///
207/// let id = sys_lib::Instance::start().id();
208/// let text = id.to_string();
209/// assert_eq!(text.len(), 26);
210/// assert_eq!(text.parse::<InstanceId>()?, id);
211/// # Ok::<(), sys_lib::Error>(())
212/// ```
213#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
214pub struct InstanceId([u8; 16]);
215
216impl InstanceId {
217    /// The 16 bytes, big-endian (the ULID's timestamp first).
218    #[must_use]
219    pub fn as_bytes(&self) -> &[u8; 16] {
220        &self.0
221    }
222
223    /// Parses the 26-character text form; anything else is `InvalidInput`.
224    ///
225    /// # Errors
226    ///
227    /// [`Error::InvalidInput`] unless `text` is exactly 26 valid characters.
228    pub fn parse(text: &str) -> Result<InstanceId> {
229        if text.len() != 26 {
230            return Err(invalid_id());
231        }
232        Ulid::parse_str(text)
233            .map(|u| InstanceId(*u.as_bytes()))
234            .map_err(|_| invalid_id())
235    }
236}
237
238fn invalid_id() -> Error {
239    Error::InvalidInput {
240        what: "instance id",
241        reason: "use exactly 26 Crockford base32 characters",
242    }
243}
244
245impl fmt::Display for InstanceId {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        fmt::Display::fmt(&Ulid::from_bytes(&self.0), f)
248    }
249}
250
251impl fmt::Debug for InstanceId {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        write!(f, "InstanceId({self})")
254    }
255}
256
257impl FromStr for InstanceId {
258    type Err = Error;
259
260    fn from_str(s: &str) -> Result<Self> {
261        Self::parse(s)
262    }
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn test_instance_start_once_from_64_threads() {
271        // E-62.
272        let ptrs: Vec<usize> = std::thread::scope(|s| {
273            let hs: Vec<_> = (0..64)
274                .map(|_| s.spawn(|| core::ptr::from_ref(Instance::start()) as usize))
275                .collect();
276            hs.into_iter().map(|h| h.join().unwrap_or(0)).collect()
277        });
278        assert!(ptrs.windows(2).all(|w| w[0] == w[1]));
279        let me = Instance::start();
280        assert!(me.is_current_process());
281        assert_eq!(me.pid(), std::process::id());
282        assert!(!me.host().is_empty() && !me.user_at_start().is_empty());
283        assert!(current().is_some());
284    }
285
286    #[test]
287    fn test_instance_id_round_trip_and_strict_parse() {
288        let id = Instance::start().id();
289        assert_eq!(InstanceId::parse(&id.to_string()).unwrap(), id);
290        assert_eq!(format!("{id:?}"), format!("InstanceId({id})"));
291        for bad in [
292            "",
293            "01J9ZQ4M8T6Y2K5V3W1X7R0B9",
294            "01J9ZQ4M8T6Y2K5V3W1X7R0B9CX",
295            "01J9ZQ4M8T6Y2K5V3W1X7R0B9!",
296            "\u{e9}".repeat(13).as_str(),
297        ] {
298            assert!(
299                matches!(InstanceId::parse(bad), Err(Error::InvalidInput { .. })),
300                "{bad:?}"
301            );
302        }
303    }
304
305    #[test]
306    fn test_instance_writers() {
307        let me = Instance::start();
308        let mut line = String::new();
309        me.write_kv(&mut line).unwrap();
310        assert!(line.starts_with(&format!("instance.id={} instance.started_at=", me.id())));
311        let mut json = String::new();
312        me.write_json(&mut json).unwrap();
313        assert!(json.starts_with(&format!("{{\"id\":\"{}\",\"started_at\":\"", me.id())));
314        assert!(json.ends_with('}'));
315        assert!(me.to_string().contains(&format!(" pid {} up ", me.pid())));
316    }
317
318    #[test]
319    fn test_instance_uptime_format() {
320        let fmt = |s| {
321            let mut out = String::new();
322            write_uptime(&mut out, Duration::from_secs(s)).unwrap();
323            out
324        };
325        assert_eq!(fmt(4), "4s");
326        assert_eq!(fmt(724), "12m04s");
327        assert_eq!(fmt(11_524), "3h12m04s");
328        assert_eq!(fmt(184_324), "2d03h12m04s");
329    }
330}