Skip to main content

aft/
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
13use std::cell::RefCell;
14
15thread_local! {
16    /// Current session id for log tagging. `None` means "no session context".
17    static CURRENT_SESSION: RefCell<Option<String>> = const { RefCell::new(None) };
18}
19
20/// Set the current thread-local session id.
21///
22/// Call this at the start of a background thread that captured the session id
23/// from the parent request loop.
24pub fn set_session(session: Option<String>) {
25    CURRENT_SESSION.with(|s| {
26        *s.borrow_mut() = session;
27    });
28}
29
30struct SessionGuard(Option<String>);
31
32impl Drop for SessionGuard {
33    fn drop(&mut self) {
34        set_session(self.0.take());
35    }
36}
37
38/// Run `f` with the given session id set on the current thread, restoring the
39/// previous value afterwards (RAII-style and panic-safe).
40///
41/// This is the primary entry point for the main request loop: wrap the
42/// dispatch call in `with_session(req.session_id.clone(), || { ... })`.
43pub fn with_session<T>(session: Option<String>, f: impl FnOnce() -> T) -> T {
44    let prev = current_session();
45    set_session(session);
46    let _guard = SessionGuard(prev);
47    f()
48}
49
50/// Return the current session id (e.g. `"abcd1234"`), or `None` if no session is set.
51pub fn current_session() -> Option<String> {
52    CURRENT_SESSION.with(|s| s.borrow().clone())
53}
54
55/// Return the current session id prefix string, e.g. `"[ses_abcd1234] "`,
56/// or an empty string if no session is set.
57///
58/// The stored session id may already carry the `ses_` prefix (OpenCode's
59/// real session IDs do); detect that and avoid double-prefixing.
60pub fn session_prefix() -> String {
61    CURRENT_SESSION.with(|s| match s.borrow().as_deref() {
62        Some(sid) if sid.starts_with("ses_") => format!("[{}] ", sid),
63        Some(sid) => format!("[ses_{}] ", sid),
64        None => String::new(),
65    })
66}
67
68/// Log at INFO level with the `[aft]` prefix and optional `[ses_xxx]` session tag.
69///
70/// Use this instead of `log::info!("[aft] ...")` in per-request code paths.
71/// The macro automatically reads the thread-local session id and formats:
72///
73/// ```text
74/// With session:    [aft] [ses_abcd1234] semantic index: rebuilding from scratch
75/// Without session: [aft] semantic index: rebuilding from scratch
76/// ```
77#[macro_export]
78macro_rules! slog_info {
79    ($($arg:tt)*) => {
80        log::info!("[aft] {}{}", $crate::log_ctx::session_prefix(), format!($($arg)*))
81    };
82}
83
84/// Log at WARN level with the `[aft]` prefix and optional `[ses_xxx]` session tag.
85///
86/// See [`slog_info!`] for format details.
87#[macro_export]
88macro_rules! slog_warn {
89    ($($arg:tt)*) => {
90        log::warn!("[aft] {}{}", $crate::log_ctx::session_prefix(), format!($($arg)*))
91    };
92}
93
94/// Log at ERROR level with the `[aft]` prefix and optional `[ses_xxx]` session tag.
95///
96/// See [`slog_info!`] for format details.
97#[macro_export]
98macro_rules! slog_error {
99    ($($arg:tt)*) => {
100        log::error!("[aft] {}{}", $crate::log_ctx::session_prefix(), format!($($arg)*))
101    };
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    #[test]
109    fn with_session_sets_and_clears() {
110        // Initially no session
111        CURRENT_SESSION.with(|s| {
112            assert!(s.borrow().is_none());
113        });
114
115        // Set inside with_session
116        with_session(Some("test123".to_string()), || {
117            CURRENT_SESSION.with(|s| {
118                assert_eq!(s.borrow().as_deref(), Some("test123"));
119            });
120        });
121
122        // Cleared after with_session
123        CURRENT_SESSION.with(|s| {
124            assert!(s.borrow().is_none());
125        });
126    }
127
128    #[test]
129    fn with_session_none_is_noop() {
130        with_session(None, || {
131            CURRENT_SESSION.with(|s| {
132                assert!(s.borrow().is_none());
133            });
134        });
135    }
136
137    #[test]
138    fn session_prefix_format() {
139        with_session(Some("abcd1234".to_string()), || {
140            assert_eq!(session_prefix(), "[ses_abcd1234] ");
141        });
142
143        // Without session
144        assert_eq!(session_prefix(), "");
145    }
146
147    #[test]
148    fn session_prefix_does_not_double_prefix_real_ids() {
149        // Real OpenCode session IDs already start with "ses_" — the
150        // formatter must not turn that into "ses_ses_xxx".
151        with_session(Some("ses_313660571ffeZTsf4koSJwk50Q".to_string()), || {
152            assert_eq!(session_prefix(), "[ses_313660571ffeZTsf4koSJwk50Q] ");
153        });
154    }
155
156    #[test]
157    fn set_session_direct() {
158        set_session(Some("direct".to_string()));
159        CURRENT_SESSION.with(|s| {
160            assert_eq!(s.borrow().as_deref(), Some("direct"));
161        });
162        set_session(None);
163        CURRENT_SESSION.with(|s| {
164            assert!(s.borrow().is_none());
165        });
166    }
167}