hyperi-rustlib 2.7.0

Opinionated Rust framework for high-throughput data pipelines at PB scale. Auto-wiring config, logging, metrics, tracing, health, and graceful shutdown — built from many years of production infrastructure experience.
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
// Project:   hyperi-rustlib
// File:      tests/integration/logger_output.rs
// Purpose:   Integration tests for logger output capturing and masking
// Language:  Rust
//
// License:   FSL-1.1-ALv2
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Tests that verify actual log output content for both JSON and text formats,
//! including sensitive data masking via the `MaskingWriter`.

use std::collections::HashSet;
use std::io;
use std::sync::{Arc, Mutex};

use tracing_subscriber::EnvFilter;
use tracing_subscriber::fmt::time::UtcTime;
use tracing_subscriber::layer::SubscriberExt;

use hyperi_rustlib::logger::MaskingWriter;

// ---------------------------------------------------------------------------
// Test writer infrastructure
// ---------------------------------------------------------------------------

/// Shared buffer that survives writer drop (for capturing log output).
#[derive(Clone)]
struct TestBuf(Arc<Mutex<Vec<u8>>>);

impl TestBuf {
    fn new() -> Self {
        Self(Arc::new(Mutex::new(Vec::new())))
    }

    fn output(&self) -> String {
        let guard = self.0.lock().unwrap();
        String::from_utf8_lossy(&guard).to_string()
    }
}

/// Writer handle that writes to the shared buffer.
struct BufWriter(Arc<Mutex<Vec<u8>>>);

impl io::Write for BufWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// JSON format tests
// ---------------------------------------------------------------------------

#[test]
fn test_json_format_output() {
    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .json()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_target(true)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(user_id = 123, "User logged in");
    });

    let output = buf.output();
    assert!(output.contains("\"level\""), "should contain level field");
    assert!(output.contains("\"INFO\""), "level should be INFO");
    assert!(
        output.contains("User logged in"),
        "should contain the message"
    );
    assert!(
        output.contains("\"user_id\":123"),
        "should contain custom field"
    );
    assert!(
        output.contains("\"timestamp\""),
        "should contain timestamp field"
    );
}

#[test]
fn test_json_timestamp_is_rfc3339() {
    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .json()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!("timestamp check");
    });

    let output = buf.output();
    let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
    let ts = parsed["timestamp"].as_str().unwrap();

    // RFC 3339 timestamps end with Z or contain a +/- offset
    assert!(
        ts.ends_with('Z') || ts.contains('+') || ts.contains('-'),
        "timestamp should be RFC 3339: {ts}"
    );
    assert!(
        ts.contains('T'),
        "timestamp should contain T separator: {ts}"
    );
}

// ---------------------------------------------------------------------------
// Text format tests
// ---------------------------------------------------------------------------

#[test]
fn test_text_format_output() {
    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_target(true)
                .with_ansi(false)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(host = "db.example.com", "Connected to database");
    });

    let output = buf.output();
    assert!(output.contains("INFO"), "should contain level");
    assert!(
        output.contains("Connected to database"),
        "should contain message"
    );
    assert!(
        output.contains("db.example.com"),
        "should contain field value"
    );
}

// ---------------------------------------------------------------------------
// Level filtering tests
// ---------------------------------------------------------------------------

#[test]
fn test_log_level_filtering() {
    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("warn"))
        .with(
            tracing_subscriber::fmt::layer()
                .json()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_ansi(false)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!("should be filtered");
        tracing::warn!("should appear");
    });

    let output = buf.output();
    assert!(
        !output.contains("should be filtered"),
        "info should be filtered at warn level"
    );
    assert!(output.contains("should appear"), "warn should pass through");
}

// ---------------------------------------------------------------------------
// Masking integration tests (with MaskingWriter)
// ---------------------------------------------------------------------------

#[test]
fn test_json_masking_redacts_sensitive_fields() {
    let buf = TestBuf::new();
    let sensitive: HashSet<String> = ["password".to_string(), "token".to_string()]
        .into_iter()
        .collect();
    let fields = Arc::new(sensitive);
    let shared = buf.0.clone();

    let make_writer = move || {
        let inner = BufWriter(Arc::clone(&shared));
        MaskingWriter::new(inner, Arc::clone(&fields), true)
    };

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .json()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_writer(make_writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(
            password = "super_secret_123",
            token = "tok_abc",
            username = "john",
            "Login attempt"
        );
    });

    let output = buf.output();
    assert!(
        !output.contains("super_secret_123"),
        "password value should be redacted"
    );
    assert!(
        !output.contains("tok_abc"),
        "token value should be redacted"
    );
    assert!(
        output.contains("[REDACTED]"),
        "should contain redacted placeholder"
    );
    assert!(
        output.contains("john"),
        "non-sensitive field should be preserved"
    );
    assert!(
        output.contains("Login attempt"),
        "message should be preserved"
    );
}

#[test]
fn test_text_masking_redacts_sensitive_fields() {
    let buf = TestBuf::new();
    let sensitive: HashSet<String> = ["password".to_string()].into_iter().collect();
    let fields = Arc::new(sensitive);
    let shared = buf.0.clone();

    let make_writer = move || {
        let inner = BufWriter(Arc::clone(&shared));
        MaskingWriter::new(inner, Arc::clone(&fields), false)
    };

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_ansi(false)
                .with_writer(make_writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(password = "my_secret", host = "localhost", "DB connect");
    });

    let output = buf.output();
    assert!(
        !output.contains("my_secret"),
        "password value should be redacted"
    );
    assert!(
        output.contains("[REDACTED]"),
        "should contain redacted placeholder"
    );
    assert!(
        output.contains("localhost"),
        "non-sensitive field should be preserved"
    );
}

#[test]
fn test_masking_preserves_all_normal_fields() {
    let buf = TestBuf::new();
    let sensitive: HashSet<String> = ["password".to_string()].into_iter().collect();
    let fields = Arc::new(sensitive);
    let shared = buf.0.clone();

    let make_writer = move || {
        let inner = BufWriter(Arc::clone(&shared));
        MaskingWriter::new(inner, Arc::clone(&fields), true)
    };

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .json()
                .with_timer(UtcTime::rfc_3339())
                .with_file(false)
                .with_line_number(false)
                .with_writer(make_writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(
            host = "db.example.com",
            port = 5432,
            username = "admin",
            "Connection established"
        );
    });

    let output = buf.output();
    let parsed: serde_json::Value = serde_json::from_str(output.trim()).unwrap();
    assert_eq!(parsed["fields"]["host"], "db.example.com");
    assert_eq!(parsed["fields"]["port"], 5432);
    assert_eq!(parsed["fields"]["username"], "admin");
}

// ---------------------------------------------------------------------------
// Coloured formatter tests
// ---------------------------------------------------------------------------

#[test]
fn test_coloured_output_contains_ansi_escapes() {
    use hyperi_rustlib::logger::format::ColouredFormatter;

    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let formatter = ColouredFormatter::new(true)
        .with_file(false)
        .with_line_number(false);

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .with_ansi(true)
                .event_format(formatter)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!("coloured output test");
    });

    let output = buf.output();
    // ANSI escape sequences start with ESC (0x1B) followed by [
    assert!(
        output.contains('\x1b'),
        "output should contain ANSI escape codes when ansi=true: {output}"
    );
    assert!(
        output.contains("coloured output test"),
        "should contain message"
    );
    assert!(output.contains("INFO"), "should contain level");
}

#[test]
fn test_no_colour_output_is_clean() {
    use hyperi_rustlib::logger::format::ColouredFormatter;

    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let formatter = ColouredFormatter::new(false)
        .with_file(false)
        .with_line_number(false);

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .with_ansi(false)
                .event_format(formatter)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!("clean output test");
    });

    let output = buf.output();
    assert!(
        !output.contains('\x1b'),
        "output should NOT contain ANSI escape codes when ansi=false: {output}"
    );
    assert!(
        output.contains("clean output test"),
        "should contain message"
    );
    assert!(output.contains("INFO"), "should contain level");
}

#[test]
fn test_coloured_output_has_all_components() {
    use hyperi_rustlib::logger::format::ColouredFormatter;

    let buf = TestBuf::new();
    let shared = buf.0.clone();
    let writer = move || BufWriter(Arc::clone(&shared));

    let formatter = ColouredFormatter::new(false)
        .with_file(false)
        .with_line_number(false);

    let subscriber = tracing_subscriber::registry()
        .with(EnvFilter::new("info"))
        .with(
            tracing_subscriber::fmt::layer()
                .with_ansi(false)
                .event_format(formatter)
                .with_writer(writer),
        );

    tracing::subscriber::with_default(subscriber, || {
        tracing::info!(count = 42, host = "localhost", "Server started");
    });

    let output = buf.output();
    // Verify all components present
    assert!(output.contains("INFO"), "should contain level");
    assert!(output.contains("Server started"), "should contain message");
    assert!(output.contains("count"), "should contain field name");
    assert!(output.contains("42"), "should contain field value");
    assert!(output.contains("localhost"), "should contain string field");
    // Should contain a timestamp-like prefix
    assert!(output.contains('T'), "should contain RFC 3339 timestamp");
}