Skip to main content

byteflow/
log.rs

1//! Host-side scheduler diagnostics on stderr, gated by `BYTEFLOW_LOG`.
2//!
3//! # Why this is separate from the `print` native
4//!
5//! Actor-visible logging (`CallNative print`) writes to **stdout** and is part
6//! of the program's observable behaviour — samples and demos use it to show
7//! envelopes crossing the mailbox. Scheduler diagnostics (spawn / send /
8//! park / finish) are an **operator** concern: they must not pollute stdout
9//! when an embedder pipes Flow output, and they must stay off by default
10//! so a production run is silent unless asked.
11//!
12//! ```text
13//! BYTEFLOW_LOG unset / 0 / off / false  → silent
14//! BYTEFLOW_LOG=1 / info / true          → spawn, send, receive, finish
15//! BYTEFLOW_LOG=debug / 2                → also park, deliver queued/handoff
16//! ```
17//!
18//! # Lazy init
19//!
20//! The level is read from the environment once (first call) and cached in
21//! atomics. That avoids re-parsing `std::env` on every send in a hot worker
22//! loop. Tests can override via [`set_level_for_tests`].
23
24use std::sync::atomic::{AtomicU8, Ordering};
25use std::time::{SystemTime, UNIX_EPOCH};
26
27const OFF: u8 = 0;
28const INFO: u8 = 1;
29const DEBUG: u8 = 2;
30
31static LEVEL: AtomicU8 = AtomicU8::new(OFF);
32static INIT: AtomicU8 = AtomicU8::new(0);
33
34fn level() -> u8 {
35    if INIT.load(Ordering::Acquire) == 0 {
36        let parsed = match std::env::var("BYTEFLOW_LOG") {
37            Ok(v) => {
38                let v = v.trim().to_ascii_lowercase();
39                match v.as_str() {
40                    "" | "0" | "off" | "false" | "no" => OFF,
41                    "debug" | "trace" | "2" => DEBUG,
42                    // "1", "info", "true", "yes", or any other non-empty token
43                    _ => INFO,
44                }
45            }
46            Err(_) => OFF,
47        };
48        LEVEL.store(parsed, Ordering::Release);
49        INIT.store(1, Ordering::Release);
50    }
51    LEVEL.load(Ordering::Acquire)
52}
53
54fn stamp_ms() -> u64 {
55    // Logging must never panic: a broken clock just prints epoch-ish 0.
56    match SystemTime::now().duration_since(UNIX_EPOCH) {
57        Ok(d) => d.as_millis() as u64,
58        Err(_) => 0,
59    }
60}
61
62/// Override the cached level (tests only). `0` off, `1` info, `2` debug.
63pub fn set_level_for_tests(level: u8) {
64    LEVEL.store(level.min(DEBUG), Ordering::Release);
65    INIT.store(1, Ordering::Release);
66}
67
68/// INFO-level line when [`BYTEFLOW_LOG`](crate::log) is at least `info`.
69#[inline]
70pub fn info(msg: impl std::fmt::Display) {
71    if level() >= INFO {
72        eprintln!("[{}] byteflow INFO  {}", stamp_ms(), msg);
73    }
74}
75
76/// DEBUG-level line when [`BYTEFLOW_LOG`](crate::log) is `debug`.
77#[inline]
78pub fn debug(msg: impl std::fmt::Display) {
79    if level() >= DEBUG {
80        eprintln!("[{}] byteflow DEBUG {}", stamp_ms(), msg);
81    }
82}
83
84/// A collector refused or dropped one diagnostic line.
85///
86/// The runtime ignores this. The flow keeps its original outcome.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct LogRecordError;
89
90impl std::fmt::Display for LogRecordError {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        f.write_str("log sink rejected the line")
93    }
94}
95
96impl std::error::Error for LogRecordError {}
97
98/// Receives the diagnostic line that would be written to stderr.
99///
100/// `try_record` runs on the worker that emitted the event. It must return
101/// promptly and must not panic. [`Err`] is ignored: a collector failure does
102/// not fail the flow. There is no queue inside the runtime.
103pub trait LogSink: Send + Sync + std::fmt::Debug + 'static {
104    fn try_record(&self, line: &str) -> Result<(), LogRecordError>;
105}
106
107pub(crate) fn info_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
108    forward(sink, INFO, "INFO ", msg);
109}
110
111pub(crate) fn debug_sink(sink: Option<&std::sync::Arc<dyn LogSink>>, msg: impl std::fmt::Display) {
112    forward(sink, DEBUG, "DEBUG", msg);
113}
114
115fn forward(
116    sink: Option<&std::sync::Arc<dyn LogSink>>,
117    min: u8,
118    label: &str,
119    msg: impl std::fmt::Display,
120) {
121    let show = level() >= min;
122    if !show && sink.is_none() {
123        return;
124    }
125    let line = format!("[{}] byteflow {label} {msg}", stamp_ms());
126    if show {
127        eprintln!("{line}");
128    }
129    if let Some(sink) = sink {
130        let _ = sink.try_record(&line);
131    }
132}