1use 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
31pub struct Instance {
34 id: InstanceId,
35 started_at: SystemTime,
36 start: Monotonic,
37 host: String,
38 pid: u32,
39 user: String,
40}
41
42#[must_use]
49pub fn current() -> Option<&'static Instance> {
50 INSTANCE.get()
51}
52
53impl Instance {
54 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 #[must_use]
80 pub fn id(&self) -> InstanceId {
81 self.id
82 }
83
84 #[must_use]
86 pub fn started_at(&self) -> SystemTime {
87 self.started_at
88 }
89
90 #[must_use]
92 pub fn uptime(&self) -> Duration {
93 self.start.elapsed()
94 }
95
96 #[must_use]
98 pub fn host(&self) -> &str {
99 &self.host
100 }
101
102 #[must_use]
104 pub fn pid(&self) -> u32 {
105 self.pid
106 }
107
108 #[must_use]
111 pub fn user_at_start(&self) -> &str {
112 &self.user
113 }
114
115 #[must_use]
118 pub fn is_current_process(&self) -> bool {
119 self.pid == std::process::id()
120 }
121
122 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 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
167impl 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
187fn 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#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
214pub struct InstanceId([u8; 16]);
215
216impl InstanceId {
217 #[must_use]
219 pub fn as_bytes(&self) -> &[u8; 16] {
220 &self.0
221 }
222
223 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 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}