rustrails-support 0.1.1

Core utilities (ActiveSupport equivalent)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::{
    collections::HashMap,
    sync::{Arc, Mutex, MutexGuard},
    thread::{self, ThreadId},
};

/// A tracing dispatch wrapper that prepends thread-local tags to log messages.
#[derive(Clone, Debug)]
pub struct TaggedLogging {
    subscriber: tracing::Dispatch,
    tag_stacks: Arc<Mutex<HashMap<ThreadId, Vec<String>>>>,
}

impl TaggedLogging {
    /// Wraps a tracing dispatch for tag-aware message formatting.
    #[must_use]
    pub fn new(subscriber: tracing::Dispatch) -> Self {
        Self {
            subscriber,
            tag_stacks: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Returns the wrapped tracing dispatch.
    #[must_use]
    pub fn subscriber(&self) -> &tracing::Dispatch {
        &self.subscriber
    }

    /// Pushes `tags` onto the current thread-local tag stack.
    pub fn push_tags<I, S>(&self, tags: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let tags = normalize_tags(tags);
        if tags.is_empty() {
            return;
        }

        self.with_current_stack(|stack| stack.extend(tags));
    }

    /// Pops the most recently pushed tag.
    pub fn pop_tags(&self) -> Option<String> {
        self.with_current_stack(Vec::pop)
    }

    /// Clears the current thread-local tag stack.
    pub fn clear_tags(&self) {
        self.tag_stacks().remove(&thread::current().id());
    }

    /// Applies `tags` for the duration of `f`, then restores the previous tag stack.
    pub fn tagged<F, R, I, S>(&self, tags: I, f: F) -> R
    where
        F: FnOnce() -> R,
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let tags = normalize_tags(tags);
        let thread_id = thread::current().id();
        let previous_len = self.with_current_stack(|stack| {
            let previous_len = stack.len();
            stack.extend(tags);
            previous_len
        });
        let _guard = TagScope {
            tag_stacks: Arc::clone(&self.tag_stacks),
            thread_id,
            previous_len,
        };
        f()
    }

    /// Formats `message` by prefixing the current tags.
    #[must_use]
    pub fn format_message(&self, message: &str) -> String {
        let prefix = self
            .tag_stacks()
            .get(&thread::current().id())
            .into_iter()
            .flat_map(|stack| stack.iter())
            .map(|tag| format!("[{tag}]"))
            .collect::<Vec<_>>()
            .join(" ");

        if prefix.is_empty() {
            message.to_owned()
        } else {
            format!("{prefix} {message}")
        }
    }

    fn with_current_stack<R>(&self, f: impl FnOnce(&mut Vec<String>) -> R) -> R {
        let thread_id = thread::current().id();
        let mut tag_stacks = self.tag_stacks();
        let result = {
            let stack = tag_stacks.entry(thread_id).or_default();
            f(stack)
        };

        if tag_stacks.get(&thread_id).is_some_and(Vec::is_empty) {
            tag_stacks.remove(&thread_id);
        }

        result
    }

    fn tag_stacks(&self) -> MutexGuard<'_, HashMap<ThreadId, Vec<String>>> {
        lock_tag_stacks(&self.tag_stacks)
    }
}

struct TagScope {
    tag_stacks: Arc<Mutex<HashMap<ThreadId, Vec<String>>>>,
    thread_id: ThreadId,
    previous_len: usize,
}

impl Drop for TagScope {
    fn drop(&mut self) {
        let mut tag_stacks = lock_tag_stacks(&self.tag_stacks);
        if let Some(stack) = tag_stacks.get_mut(&self.thread_id) {
            stack.truncate(self.previous_len);
            if stack.is_empty() {
                tag_stacks.remove(&self.thread_id);
            }
        }
    }
}

fn normalize_tags<I, S>(tags: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    tags.into_iter()
        .map(Into::into)
        .filter(|tag| !tag.trim().is_empty())
        .collect()
}

fn lock_tag_stacks(
    tag_stacks: &Mutex<HashMap<ThreadId, Vec<String>>>,
) -> MutexGuard<'_, HashMap<ThreadId, Vec<String>>> {
    tag_stacks
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

#[cfg(test)]
mod tests {
    use super::TaggedLogging;
    use std::thread;

    fn logger() -> TaggedLogging {
        TaggedLogging::new(tracing::Dispatch::none())
    }

    fn run_isolated<R>(test: impl FnOnce() -> R + Send + 'static) -> R
    where
        R: Send + 'static,
    {
        match thread::spawn(test).join() {
            Ok(result) => result,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    #[test]
    fn format_message_returns_plain_message_without_tags() {
        run_isolated(|| {
            let logger = logger();
            assert_eq!(logger.format_message("hello"), "hello");
        });
    }

    #[test]
    fn push_tags_prepends_tags_in_order() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Request", "User"]);

            assert_eq!(logger.format_message("hello"), "[Request] [User] hello");
        });
    }

    #[test]
    fn push_tags_ignores_empty_and_whitespace_tags() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Request", "", "  ", "User"]);

            assert_eq!(logger.format_message("hello"), "[Request] [User] hello");
            assert_eq!(logger.pop_tags(), Some(String::from("User")));
            assert_eq!(logger.pop_tags(), Some(String::from("Request")));
            assert_eq!(logger.pop_tags(), None);
        });
    }

    #[test]
    fn pop_tags_removes_the_last_tag() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Request", "User"]);

            assert_eq!(logger.pop_tags(), Some(String::from("User")));
            assert_eq!(logger.format_message("hello"), "[Request] hello");
        });
    }

    #[test]
    fn clear_tags_removes_all_tags() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Request", "User"]);
            logger.clear_tags();

            assert_eq!(logger.format_message("hello"), "hello");
        });
    }

    #[test]
    fn tagged_scopes_tags_temporarily() {
        run_isolated(|| {
            let logger = logger();

            let formatted = logger.tagged(["Request"], || logger.format_message("hello"));

            assert_eq!(formatted, "[Request] hello");
            assert_eq!(logger.format_message("after"), "after");
        });
    }

    #[test]
    fn tagged_ignores_empty_and_whitespace_tags() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Outer"]);

            logger.tagged(["", "  ", "Inner"], || {
                assert_eq!(logger.format_message("hello"), "[Outer] [Inner] hello");
            });

            assert_eq!(logger.format_message("after"), "[Outer] after");
        });
    }

    #[test]
    fn tagged_with_only_empty_tags_is_a_no_op() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Outer"]);

            logger.tagged(["", "   "], || {
                assert_eq!(logger.format_message("hello"), "[Outer] hello");
            });

            assert_eq!(logger.format_message("after"), "[Outer] after");
        });
    }

    #[test]
    fn tagged_restores_previous_tags_after_scope() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Outer"]);

            logger.tagged(["Inner"], || {
                assert_eq!(logger.format_message("hello"), "[Outer] [Inner] hello");
            });

            assert_eq!(logger.format_message("after"), "[Outer] after");
        });
    }

    #[test]
    fn tagged_can_be_nested() {
        run_isolated(|| {
            let logger = logger();

            logger.tagged(["Outer"], || {
                logger.tagged(["Inner"], || {
                    assert_eq!(logger.format_message("hello"), "[Outer] [Inner] hello");
                });
                assert_eq!(logger.format_message("middle"), "[Outer] middle");
            });

            assert_eq!(logger.format_message("after"), "after");
        });
    }

    #[test]
    fn tag_stack_is_isolated_per_thread() {
        let tagged_logger = logger();
        tagged_logger.push_tags(["Main"]);

        let child_message = run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Child"]);
            logger.format_message("hello")
        });

        assert_eq!(child_message, "[Child] hello");
        assert_eq!(tagged_logger.format_message("hello"), "[Main] hello");
    }

    #[test]
    fn same_logger_keeps_tags_isolated_per_thread() {
        let logger = logger();
        logger.push_tags(["Main"]);

        let child_message = {
            let logger = logger.clone();
            run_isolated(move || {
                assert_eq!(logger.format_message("before"), "before");
                logger.push_tags(["Child"]);
                let during = logger.format_message("hello");
                logger.clear_tags();
                let after = logger.format_message("after");
                (during, after)
            })
        };

        assert_eq!(
            child_message,
            (String::from("[Child] hello"), String::from("after"))
        );
        assert_eq!(logger.format_message("hello"), "[Main] hello");
    }

    #[test]
    fn tags_are_isolated_per_instance_on_the_same_thread() {
        run_isolated(|| {
            let first = logger();
            let second = logger();
            first.push_tags(["First"]);

            assert_eq!(first.format_message("hello"), "[First] hello");
            assert_eq!(second.format_message("hello"), "hello");
        });
    }

    #[test]
    fn clear_tags_only_affects_the_current_instance() {
        run_isolated(|| {
            let first = logger();
            let second = logger();
            first.push_tags(["First"]);
            second.push_tags(["Second"]);

            first.clear_tags();

            assert_eq!(first.format_message("hello"), "hello");
            assert_eq!(second.format_message("hello"), "[Second] hello");
        });
    }

    #[test]
    fn nested_tagged_scopes_restore_outer_tags_in_lifo_order() {
        run_isolated(|| {
            let logger = logger();

            logger.tagged(["Outer"], || {
                assert_eq!(logger.format_message("start"), "[Outer] start");

                logger.tagged(["Middle"], || {
                    assert_eq!(logger.format_message("middle"), "[Outer] [Middle] middle");

                    logger.tagged(["Inner"], || {
                        assert_eq!(
                            logger.format_message("inner"),
                            "[Outer] [Middle] [Inner] inner"
                        );
                    });

                    assert_eq!(
                        logger.format_message("after inner"),
                        "[Outer] [Middle] after inner"
                    );
                });

                assert_eq!(
                    logger.format_message("after middle"),
                    "[Outer] after middle"
                );
            });

            assert_eq!(logger.format_message("after all"), "after all");
        });
    }

    #[test]
    fn pop_tags_returns_none_when_stack_is_empty() {
        run_isolated(|| {
            let logger = logger();
            assert_eq!(logger.pop_tags(), None);
        });
    }

    #[test]
    fn tagged_restores_state_after_panic() {
        run_isolated(|| {
            let logger = logger();
            logger.push_tags(["Outer"]);

            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                logger.tagged(["Inner"], || panic!("boom"));
            }));

            assert!(result.is_err());
            assert_eq!(logger.format_message("hello"), "[Outer] hello");
        });
    }
}