Skip to main content

aft_base/
log_ctx.rs

1//! Thread-local session context for log lines.
2//!
3//! AFT runs a single-threaded request loop. Each incoming request carries a
4//! `session_id` that identifies the OpenCode/Pi session. By storing it in a
5//! thread-local we can automatically prepend `[ses_xxx]` to every `slog_*`
6//! log macro call without threading the session id through every function
7//! signature.
8//!
9//! Background threads spawned during request handling (search-index pre-warm,
10//! semantic-index build) **must** capture the session id before spawning and
11//! re-install it on the new thread via [`set_session`] or [`with_session`].
12//!
13//! A line logged outside any session scope carries no session tag. Threads
14//! such as the request loop, the subc frame loop and executor workers serve
15//! many sessions in turn, so "the last session this thread served" says
16//! nothing about who owns a later between-request line; tagging with it sent
17//! operators to the wrong session. Code that logs about a specific session
18//! from such a thread (a pending bind, a background task) must enter that
19//! session's scope with [`with_session`] first.
20
21use std::cell::RefCell;
22
23thread_local! {
24    /// Current session id for log tagging. `None` means "no session context".
25    static CURRENT_SESSION: RefCell<Option<String>> = const { RefCell::new(None) };
26}
27
28/// Set the current thread-local session id.
29///
30/// Call this at the start of a background thread that captured the session id
31/// from the parent request loop.
32pub fn set_session(session: Option<String>) {
33    CURRENT_SESSION.with(|s| {
34        *s.borrow_mut() = session;
35    });
36}
37
38struct SessionGuard(Option<String>);
39
40impl Drop for SessionGuard {
41    fn drop(&mut self) {
42        CURRENT_SESSION.with(|s| {
43            *s.borrow_mut() = self.0.take();
44        });
45    }
46}
47
48/// Run `f` with the given session id set on the current thread, restoring the
49/// previous value afterwards (RAII-style and panic-safe).
50///
51/// This is the primary entry point for the main request loop: wrap the
52/// dispatch call in `with_session(req.session_id.clone(), || { ... })`.
53pub fn with_session<T>(session: Option<String>, f: impl FnOnce() -> T) -> T {
54    let prev = current_session();
55    set_session(session);
56    let _guard = SessionGuard(prev);
57    f()
58}
59
60/// Return the current session id (e.g. `"abcd1234"`), or `None` if no session is set.
61pub fn current_session() -> Option<String> {
62    CURRENT_SESSION.with(|s| s.borrow().clone())
63}
64
65/// Return the current session id prefix string, e.g. `"[ses_abcd1234] "`,
66/// or an empty string when no session scope is active on this thread.
67///
68/// The stored session id may already carry the `ses_` prefix (OpenCode's
69/// real session IDs do); detect that and avoid double-prefixing.
70pub fn session_prefix() -> String {
71    match current_session().as_deref() {
72        Some(sid) if sid.starts_with("ses_") => format!("[{}] ", sid),
73        Some(sid) => format!("[ses_{}] ", sid),
74        None => String::new(),
75    }
76}
77
78#[doc(hidden)]
79pub fn format_session_message(message: std::fmt::Arguments<'_>) -> String {
80    let mut line = String::new();
81    write_session_message(&mut line, message).expect("writing to a String cannot fail");
82    line
83}
84
85fn write_session_message(
86    writer: &mut impl std::fmt::Write,
87    message: std::fmt::Arguments<'_>,
88) -> std::fmt::Result {
89    CURRENT_SESSION.with(|current| {
90        if let Some(sid) = current.borrow().as_deref() {
91            writer.write_str(if sid.starts_with("ses_") {
92                "["
93            } else {
94                "[ses_"
95            })?;
96            writer.write_str(sid)?;
97            writer.write_str("] ")?;
98        }
99        Ok(())
100    })?;
101    // Release the session borrow before user-provided Display implementations
102    // run; formatting a message may itself change the logging context.
103    writer.write_fmt(message)
104}
105
106/// Log at INFO level with the optional `[ses_xxx]` session tag.
107///
108/// Use this instead of `log::info!(...)` in per-request code paths.
109/// The macro automatically reads the thread-local session id and formats:
110///
111/// ```text
112/// With session:    <ts> [aft] INFO [ses_abcd1234] semantic index: rebuilding from scratch
113/// Without session: <ts> [aft] INFO semantic index: rebuilding from scratch
114/// ```
115///
116/// The timestamp, `[aft]` / `[aft-lsp]` outer prefix and level are added by
117/// the env_logger format in `logging.rs` based on the log record — do NOT
118/// inline them into the macro body, that produces a doubled
119/// `[aft-lsp] [aft]` prefix when LSP modules log.
120#[macro_export]
121macro_rules! slog_info {
122    ($($arg:tt)*) => {
123        if $crate::logging::slog_info_enabled(module_path!()) {
124            $crate::logging::emit_slog_info(
125                module_path!(),
126                $crate::log_ctx::format_session_message(format_args!($($arg)*)),
127            )
128        }
129    };
130}
131
132/// Log at WARN level with the optional `[ses_xxx]` session tag.
133///
134/// See [`slog_info!`] for format details.
135#[macro_export]
136macro_rules! slog_warn {
137    ($($arg:tt)*) => {
138        if $crate::logging::slog_warn_enabled(module_path!()) {
139            $crate::logging::emit_slog_warn(
140                module_path!(),
141                $crate::log_ctx::format_session_message(format_args!($($arg)*)),
142            )
143        }
144    };
145}
146
147/// Log at ERROR level with the optional `[ses_xxx]` session tag.
148///
149/// See [`slog_info!`] for format details.
150#[macro_export]
151macro_rules! slog_error {
152    ($($arg:tt)*) => {
153        if $crate::logging::slog_error_enabled(module_path!()) {
154            $crate::logging::emit_slog_error(
155                module_path!(),
156                $crate::log_ctx::format_session_message(format_args!($($arg)*)),
157            )
158        }
159    };
160}
161
162/// Log at DEBUG level with the optional `[ses_xxx]` session tag.
163///
164/// Use for verbose-but-useful diagnostics that should be silent by default and
165/// only surface when `RUST_LOG=aft=debug` (or similar) is set.
166///
167/// See [`slog_info!`] for format details.
168#[macro_export]
169macro_rules! slog_debug {
170    ($($arg:tt)*) => {
171        if $crate::logging::slog_debug_enabled(module_path!()) {
172            $crate::logging::emit_slog_debug(
173                module_path!(),
174                $crate::log_ctx::format_session_message(format_args!($($arg)*)),
175            )
176        }
177    };
178}
179
180#[cfg(test)]
181mod tests {
182    #[test]
183    fn session_message_streams_borrowed_session_and_message() {
184        use super::*;
185        struct Writer {
186            sid: *const u8,
187            saw_sid: bool,
188            saw_message: bool,
189        }
190        impl std::fmt::Write for Writer {
191            fn write_str(&mut self, value: &str) -> std::fmt::Result {
192                if value == "borrow-check" {
193                    assert_eq!(
194                        value.as_ptr(),
195                        self.sid,
196                        "session was cloned before formatting"
197                    );
198                    self.saw_sid = true;
199                }
200                if value == "message" {
201                    self.saw_message = true;
202                }
203                assert!(
204                    !value.contains("message") || value == "message",
205                    "message was preformatted"
206                );
207                Ok(())
208            }
209        }
210        with_session(Some("borrow-check".to_string()), || {
211            let sid = CURRENT_SESSION.with(|s| s.borrow().as_ref().unwrap().as_ptr());
212            let mut writer = Writer {
213                sid,
214                saw_sid: false,
215                saw_message: false,
216            };
217            write_session_message(&mut writer, format_args!("message")).unwrap();
218            assert!(writer.saw_sid && writer.saw_message);
219            assert_eq!(
220                format_session_message(format_args!("message")),
221                "[ses_borrow-check] message"
222            );
223        });
224    }
225
226    use super::*;
227    use std::cell::Cell;
228    use std::fmt;
229
230    struct LogMaxLevelGuard(log::LevelFilter);
231
232    impl LogMaxLevelGuard {
233        fn set(level: log::LevelFilter) -> Self {
234            let previous = log::max_level();
235            log::set_max_level(level);
236            Self(previous)
237        }
238    }
239
240    impl Drop for LogMaxLevelGuard {
241        fn drop(&mut self) {
242            log::set_max_level(self.0);
243        }
244    }
245
246    struct CountingDisplay<'a>(&'a Cell<usize>);
247
248    impl fmt::Display for CountingDisplay<'_> {
249        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
250            self.0.set(self.0.get() + 1);
251            formatter.write_str("counted")
252        }
253    }
254
255    /// Reset the thread-local so each test starts from a clean slate.
256    /// Rust runs tests on a thread pool, and a test that panics inside
257    /// `set_session` (rather than `with_session`) could otherwise leak its
258    /// session into the next test on the same thread.
259    fn reset_session_state() {
260        CURRENT_SESSION.with(|s| {
261            *s.borrow_mut() = None;
262        });
263    }
264
265    #[test]
266    fn with_session_sets_and_clears() {
267        reset_session_state();
268        // Initially no current session
269        CURRENT_SESSION.with(|s| {
270            assert!(s.borrow().is_none());
271        });
272
273        // Set inside with_session
274        with_session(Some("test123".to_string()), || {
275            CURRENT_SESSION.with(|s| {
276                assert_eq!(s.borrow().as_deref(), Some("test123"));
277            });
278        });
279
280        // CURRENT_SESSION cleared after with_session
281        CURRENT_SESSION.with(|s| {
282            assert!(s.borrow().is_none());
283        });
284    }
285
286    #[test]
287    fn with_session_none_is_noop() {
288        reset_session_state();
289        with_session(None, || {
290            CURRENT_SESSION.with(|s| {
291                assert!(s.borrow().is_none());
292            });
293        });
294    }
295
296    #[test]
297    fn session_prefix_format() {
298        reset_session_state();
299        with_session(Some("abcd1234".to_string()), || {
300            assert_eq!(session_prefix(), "[ses_abcd1234] ");
301        });
302
303        // Once the scope has ended there is no session context, so no prefix.
304        assert_eq!(session_prefix(), "");
305    }
306
307    #[test]
308    fn session_prefix_does_not_double_prefix_real_ids() {
309        reset_session_state();
310        // Real OpenCode session IDs already start with "ses_" — the
311        // formatter must not turn that into "ses_ses_xxx".
312        with_session(Some("ses_313660571ffeZTsf4koSJwk50Q".to_string()), || {
313            assert_eq!(session_prefix(), "[ses_313660571ffeZTsf4koSJwk50Q] ");
314        });
315    }
316
317    #[test]
318    fn set_session_direct() {
319        reset_session_state();
320        set_session(Some("direct".to_string()));
321        CURRENT_SESSION.with(|s| {
322            assert_eq!(s.borrow().as_deref(), Some("direct"));
323        });
324        assert_eq!(session_prefix(), "[ses_direct] ");
325        set_session(None);
326        CURRENT_SESSION.with(|s| {
327            assert!(s.borrow().is_none());
328        });
329        assert_eq!(session_prefix(), "");
330    }
331
332    /// A line logged after a session scope ends, on a thread that served that
333    /// session, carries no session tag. Threads like the request loop and the
334    /// subc frame loop serve many sessions in turn, so tagging an unscoped
335    /// line with the previous session (as an earlier fallback did) attributed
336    /// project-wide or other-session events to whichever session ran last.
337    #[test]
338    fn unscoped_line_after_scope_ends_carries_no_session() {
339        reset_session_state();
340
341        with_session(Some("ses_first".to_string()), || {
342            assert_eq!(
343                format_session_message(format_args!("inside")),
344                "[ses_first] inside"
345            );
346        });
347
348        assert!(current_session().is_none());
349        assert_eq!(
350            format_session_message(format_args!("invalidated 1 files")),
351            "invalidated 1 files"
352        );
353    }
354
355    /// A thread that served session A and then logs about session B inside
356    /// B's scope tags the line with B only.
357    #[test]
358    fn scoped_line_carries_its_own_session_not_the_previous_one() {
359        reset_session_state();
360
361        with_session(Some("ses_A".to_string()), || {});
362        let line = with_session(Some("ses_B".to_string()), || {
363            format_session_message(format_args!("pending bind"))
364        });
365        assert_eq!(line, "[ses_B] pending bind");
366    }
367
368    #[test]
369    fn disabled_debug_log_does_not_format_arguments() {
370        let _max_level = LogMaxLevelGuard::set(log::LevelFilter::Warn);
371        let formatted = Cell::new(0);
372
373        crate::slog_debug!("debug argument: {}", CountingDisplay(&formatted));
374
375        assert_eq!(
376            formatted.get(),
377            0,
378            "disabled debug arguments must stay lazy"
379        );
380    }
381
382    /// `with_session(None, ...)` (synthetic or system requests with no
383    /// session id) runs its closure with no session tag, even nested inside
384    /// a real session's scope, and restores that scope afterwards.
385    #[test]
386    fn with_session_none_runs_untagged_and_restores_outer_scope() {
387        reset_session_state();
388
389        with_session(Some("ses_real".to_string()), || {
390            with_session(None, || {
391                assert_eq!(session_prefix(), "");
392            });
393            assert_eq!(session_prefix(), "[ses_real] ");
394        });
395        assert_eq!(session_prefix(), "");
396    }
397}