structguru 1.6.0__tar.gz → 1.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {structguru-1.6.0 → structguru-1.7.0}/Cargo.lock +3 -2
- {structguru-1.6.0 → structguru-1.7.0}/Cargo.toml +1 -1
- {structguru-1.6.0 → structguru-1.7.0}/PKG-INFO +6 -6
- {structguru-1.6.0 → structguru-1.7.0}/README.md +5 -5
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/Cargo.toml +3 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/filter.rs +39 -4
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/render.rs +15 -1
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/value.rs +26 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/worker.rs +421 -66
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/conversion.rs +117 -11
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/dispatch.rs +215 -39
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/lib.rs +1 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/rendering.rs +27 -14
- structguru-1.7.0/crates/structguru-py/src/submission.rs +105 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/writer.rs +17 -8
- {structguru-1.6.0 → structguru-1.7.0}/pyproject.toml +1 -1
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/__init__.py +1 -1
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/_native_dispatch.py +9 -1
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/_runtime.py +153 -40
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/core.py +5 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/exceptions.py +6 -4
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/_util.py +1 -1
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/celery.py +100 -33
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/requests.py +9 -16
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/sentry.py +24 -6
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/stdlib.py +10 -2
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/settings.py +5 -2
- {structguru-1.6.0 → structguru-1.7.0}/LICENSE +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/clock.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-core/src/lib.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/Cargo.toml +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/exception.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/filter.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/local_repr.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/crates/structguru-py/src/template.rs +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/_contextvars.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/_levels.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/_native_env.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/config.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/__init__.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/_stdlib_env.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/asgi.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/django.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/flask.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/grpc.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/httpx.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/integrations/sqlalchemy.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/metrics.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/otel.py +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/py.typed +0 -0
- {structguru-1.6.0 → structguru-1.7.0}/src/structguru/redaction.py +0 -0
|
@@ -245,10 +245,11 @@ dependencies = [
|
|
|
245
245
|
|
|
246
246
|
[[package]]
|
|
247
247
|
name = "structguru-core"
|
|
248
|
-
version = "1.
|
|
248
|
+
version = "1.7.0"
|
|
249
249
|
dependencies = [
|
|
250
250
|
"fancy-regex",
|
|
251
251
|
"fastrand",
|
|
252
|
+
"libc",
|
|
252
253
|
"regex",
|
|
253
254
|
"serde",
|
|
254
255
|
"serde_json",
|
|
@@ -257,7 +258,7 @@ dependencies = [
|
|
|
257
258
|
|
|
258
259
|
[[package]]
|
|
259
260
|
name = "structguru-py"
|
|
260
|
-
version = "1.
|
|
261
|
+
version = "1.7.0"
|
|
261
262
|
dependencies = [
|
|
262
263
|
"pyo3",
|
|
263
264
|
"regex",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: structguru
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.7.0
|
|
4
4
|
Classifier: Development Status :: 5 - Production/Stable
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -55,7 +55,7 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
|
|
|
55
55
|
- **Structured JSON output** in production (rendered natively in Rust for speed)
|
|
56
56
|
- **Pretty colored console** output in development
|
|
57
57
|
- **Context management** — `bind()` for persistent context, `contextualize()` for request-scoped context
|
|
58
|
-
- **Sentry integration** — redacted breadcrumbs/events with raw
|
|
58
|
+
- **Sentry integration** — redacted breadcrumbs/events with raw exception capture available by opt-in
|
|
59
59
|
- **stdlib interop** — `logger.add()` sinks can also receive third-party `logging` records
|
|
60
60
|
- **RFC 5424 severity codes** included in every log record
|
|
61
61
|
- **Native Rust runtime** — rendering and output run through the bundled abi3 extension
|
|
@@ -143,7 +143,7 @@ options, not buffered records, counters, stdlib bridge state, or `logger.add()`
|
|
|
143
143
|
Those registered sinks survive reconfiguration. Streams and callbacks retain their identity.
|
|
144
144
|
|
|
145
145
|
Levels accept case-insensitive names (including `NOTSET`) or non-negative integer
|
|
146
|
-
thresholds
|
|
146
|
+
thresholds up to `2**63 - 1`. Unknown names, booleans and out-of-range integers raise `ValueError`.
|
|
147
147
|
|
|
148
148
|
### Environment configuration
|
|
149
149
|
|
|
@@ -259,7 +259,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
|
|
|
259
259
|
Removing an id that names no active sink raises `ValueError` (a non-integer raises
|
|
260
260
|
`TypeError`), as in loguru; `remove()` without an id removes the sinks added through
|
|
261
261
|
that logger and its `bind()`/`opt()` children. `level` accepts a name or a non-negative
|
|
262
|
-
integer and raises `ValueError` for anything else, like `configure(level=...)`.
|
|
262
|
+
integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
|
|
263
263
|
A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
|
|
264
264
|
wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
|
|
265
265
|
|
|
@@ -492,12 +492,12 @@ Behavior notes:
|
|
|
492
492
|
- **Sampling & rate limiting** (`sample_rate`, `rate_limit_max`, `rate_limit_period`) are applied as native pre-render filters — dropped records cost zero rendering. `sampled` and `rate_limited` counters are distinct from the transport `dropped` counter. `sample_max_level` restricts sampling to records at or below that level; more severe records always pass.
|
|
493
493
|
- **Metric hooks** (`metric_processor=...`) invoke a structlog-style processor (e.g. `MetricProcessor`) for every *kept* record on the caller's thread, with `(None, method, {"event": message, **fields})`; the message stays in `"event"` even when a field has that name. Dropped records (level/sampling/rate-limit) never reach it; hook errors are swallowed.
|
|
494
494
|
- **Fork/shutdown safe** — the writer is flushed on exit and respawned in forked children (gunicorn/celery prefork). The exit drain is registered when structguru is imported, so `atexit` handlers registered afterwards can still log. Rotating-file writers sharing a path coordinate through an owner-only `.lock` sidecar; distributed hosts should still prefer stdout and an external collector.
|
|
495
|
-
- **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which
|
|
495
|
+
- **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which scan a bounded rendering prefix of at most `exception_max_local_repr + 4096` characters before final truncation (depth and item limits also apply; patterns needing later context can miss visible text). Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
|
|
496
496
|
- **`stack_info` is supported natively**: the stack is captured in Python and rendered in the same position as `StackInfoRenderer` (`stack` between `service` and `message`). Unlike the standard path, the stack ends at the *user's* calling frame (frames of the `structguru` package are skipped, the way structlog skips its own).
|
|
497
497
|
- **Console mode** (`format="console"`): renders colored, human-readable lines instead of JSON — structguru's own stable dev format (`<timestamp> [<LEVEL>] <message> k=v`), with ANSI colors by default on a TTY. Override with `colors=True/False`. String values are double-quoted with `"` and `\` escaped, keys containing spaces, `=`, quotes, or backslashes are quoted, and control characters, U+2028/U+2029, and bidirectional controls are escaped everywhere, so a field key or value cannot forge another field or line. Floats use the JSON renderer's text (`1.0`, `1e+300`); the stack and a formatted `exception` follow as indented blocks.
|
|
498
498
|
- **File sinks** (`file_path=...`): write to a rotating file natively. Defaults mirror `RotatingFileHandler` (50 MB, 5 backups); configure via `file_max_bytes`/`file_backup_count`. Set `also_stdout=True` to mirror output to both file and stdout (e.g. container + persistent log).
|
|
499
499
|
- **Callable sinks** (`callable_sinks=[fn, ...]`): use a bounded queue (`callable_queue_maxsize=1024`). `overflow="block"` provides lossless backpressure; `overflow="drop"` reports `callable_dropped` metrics. One background thread at a time calls the sinks, in log order, also across reconfiguration; `logger.add()` never waits for the queue. Sink exceptions are counted in `callable_errors` with a rate-limited warning. Flush and lifecycle operations drain queued calls; a sink that makes no progress for 10 seconds is abandoned with a warning instead of blocking them.
|
|
500
|
-
- **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event
|
|
500
|
+
- **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
|
|
501
501
|
- **Scope**: the native renderer covers JSON and console rendering, file/stdout/callable sinks, redaction, sampling/rate limiting, metrics, exceptions, and stack information. `logger.add()` sinks receive native and stdlib records.
|
|
502
502
|
|
|
503
503
|
Shutdown and reconfiguration drain records already accepted by the native queue.
|
|
@@ -10,7 +10,7 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
|
|
|
10
10
|
- **Structured JSON output** in production (rendered natively in Rust for speed)
|
|
11
11
|
- **Pretty colored console** output in development
|
|
12
12
|
- **Context management** — `bind()` for persistent context, `contextualize()` for request-scoped context
|
|
13
|
-
- **Sentry integration** — redacted breadcrumbs/events with raw
|
|
13
|
+
- **Sentry integration** — redacted breadcrumbs/events with raw exception capture available by opt-in
|
|
14
14
|
- **stdlib interop** — `logger.add()` sinks can also receive third-party `logging` records
|
|
15
15
|
- **RFC 5424 severity codes** included in every log record
|
|
16
16
|
- **Native Rust runtime** — rendering and output run through the bundled abi3 extension
|
|
@@ -98,7 +98,7 @@ options, not buffered records, counters, stdlib bridge state, or `logger.add()`
|
|
|
98
98
|
Those registered sinks survive reconfiguration. Streams and callbacks retain their identity.
|
|
99
99
|
|
|
100
100
|
Levels accept case-insensitive names (including `NOTSET`) or non-negative integer
|
|
101
|
-
thresholds
|
|
101
|
+
thresholds up to `2**63 - 1`. Unknown names, booleans and out-of-range integers raise `ValueError`.
|
|
102
102
|
|
|
103
103
|
### Environment configuration
|
|
104
104
|
|
|
@@ -214,7 +214,7 @@ Handler ids are process-wide: any `Logger` can remove a sink that another one ad
|
|
|
214
214
|
Removing an id that names no active sink raises `ValueError` (a non-integer raises
|
|
215
215
|
`TypeError`), as in loguru; `remove()` without an id removes the sinks added through
|
|
216
216
|
that logger and its `bind()`/`opt()` children. `level` accepts a name or a non-negative
|
|
217
|
-
integer and raises `ValueError` for anything else, like `configure(level=...)`.
|
|
217
|
+
integer up to `2**63 - 1` and raises `ValueError` for anything else, like `configure(level=...)`.
|
|
218
218
|
A `logging.Handler` passed to `add()` keeps its own level and formatter: its formatter
|
|
219
219
|
wraps the rendered line, only `level` gates what it receives, and `remove()` closes it.
|
|
220
220
|
|
|
@@ -447,12 +447,12 @@ Behavior notes:
|
|
|
447
447
|
- **Sampling & rate limiting** (`sample_rate`, `rate_limit_max`, `rate_limit_period`) are applied as native pre-render filters — dropped records cost zero rendering. `sampled` and `rate_limited` counters are distinct from the transport `dropped` counter. `sample_max_level` restricts sampling to records at or below that level; more severe records always pass.
|
|
448
448
|
- **Metric hooks** (`metric_processor=...`) invoke a structlog-style processor (e.g. `MetricProcessor`) for every *kept* record on the caller's thread, with `(None, method, {"event": message, **fields})`; the message stays in `"event"` even when a field has that name. Dropped records (level/sampling/rate-limit) never reach it; hook errors are swallowed.
|
|
449
449
|
- **Fork/shutdown safe** — the writer is flushed on exit and respawned in forked children (gunicorn/celery prefork). The exit drain is registered when structguru is imported, so `atexit` handlers registered afterwards can still log. Rotating-file writers sharing a path coordinate through an owner-only `.lock` sidecar; distributed hosts should still prefer stdout and an external collector.
|
|
450
|
-
- **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which
|
|
450
|
+
- **Structured exceptions** (`structured_exceptions=True`) render `type`, `message`, `module`, and frames as a dictionary, with optional redacted/truncated locals controlled by the `exception_*` options. A local named like a sensitive key is redacted, and so is any value under a sensitive key inside a mapping, list, tuple, named tuple, set, dataclass with its generated `__repr__`, or `SimpleNamespace` (walked with bounded depth and size, cycle-safe); other objects' own `repr()` text is covered by `sensitive_patterns`, which scan a bounded rendering prefix of at most `exception_max_local_repr + 4096` characters before final truncation (depth and item limits also apply; patterns needing later context can miss visible text). Exception groups include nested members under `exceptions`, with the same frame limits and redaction. Traversal stops at ten nesting levels or 100 exception nodes; `exceptions_truncated` counts omitted direct children. Failed message conversions produce a marker instead of interrupting logging.
|
|
451
451
|
- **`stack_info` is supported natively**: the stack is captured in Python and rendered in the same position as `StackInfoRenderer` (`stack` between `service` and `message`). Unlike the standard path, the stack ends at the *user's* calling frame (frames of the `structguru` package are skipped, the way structlog skips its own).
|
|
452
452
|
- **Console mode** (`format="console"`): renders colored, human-readable lines instead of JSON — structguru's own stable dev format (`<timestamp> [<LEVEL>] <message> k=v`), with ANSI colors by default on a TTY. Override with `colors=True/False`. String values are double-quoted with `"` and `\` escaped, keys containing spaces, `=`, quotes, or backslashes are quoted, and control characters, U+2028/U+2029, and bidirectional controls are escaped everywhere, so a field key or value cannot forge another field or line. Floats use the JSON renderer's text (`1.0`, `1e+300`); the stack and a formatted `exception` follow as indented blocks.
|
|
453
453
|
- **File sinks** (`file_path=...`): write to a rotating file natively. Defaults mirror `RotatingFileHandler` (50 MB, 5 backups); configure via `file_max_bytes`/`file_backup_count`. Set `also_stdout=True` to mirror output to both file and stdout (e.g. container + persistent log).
|
|
454
454
|
- **Callable sinks** (`callable_sinks=[fn, ...]`): use a bounded queue (`callable_queue_maxsize=1024`). `overflow="block"` provides lossless backpressure; `overflow="drop"` reports `callable_dropped` metrics. One background thread at a time calls the sinks, in log order, also across reconfiguration; `logger.add()` never waits for the queue. Sink exceptions are counted in `callable_errors` with a rate-limited warning. Flush and lifecycle operations drain queued calls; a sink that makes no progress for 10 seconds is abandoned with a warning instead of blocking them.
|
|
455
|
-
- **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event
|
|
455
|
+
- **Sentry integration** (`sentry_processor=SentryProcessor(...)`): receives the already-redacted event; raw exception capture requires `capture_raw_exceptions=True`.
|
|
456
456
|
- **Scope**: the native renderer covers JSON and console rendering, file/stdout/callable sinks, redaction, sampling/rate limiting, metrics, exceptions, and stack information. `logger.add()` sinks receive native and stdlib records.
|
|
457
457
|
|
|
458
458
|
Shutdown and reconfiguration drain records already accepted by the native queue.
|
|
@@ -127,7 +127,10 @@ impl RateLimiter {
|
|
|
127
127
|
}
|
|
128
128
|
|
|
129
129
|
fn allow_key(&self, key: &str, now: Instant) -> Decision {
|
|
130
|
-
let mut state = self
|
|
130
|
+
let mut state = self
|
|
131
|
+
.buckets
|
|
132
|
+
.lock()
|
|
133
|
+
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
131
134
|
let cutoff = now.checked_sub(self.period);
|
|
132
135
|
|
|
133
136
|
// Prune the candidate bucket up to the window edge.
|
|
@@ -170,7 +173,7 @@ impl RateLimiter {
|
|
|
170
173
|
fn tracked_keys(&self) -> usize {
|
|
171
174
|
self.buckets
|
|
172
175
|
.lock()
|
|
173
|
-
.
|
|
176
|
+
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
174
177
|
.timestamps
|
|
175
178
|
.len()
|
|
176
179
|
}
|
|
@@ -272,7 +275,10 @@ impl Pipeline {
|
|
|
272
275
|
}
|
|
273
276
|
};
|
|
274
277
|
if decision == Decision::Drop {
|
|
275
|
-
let mut stats = self
|
|
278
|
+
let mut stats = self
|
|
279
|
+
.stats
|
|
280
|
+
.lock()
|
|
281
|
+
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
276
282
|
if sampled {
|
|
277
283
|
stats.sampled += 1;
|
|
278
284
|
}
|
|
@@ -292,7 +298,10 @@ impl Pipeline {
|
|
|
292
298
|
|
|
293
299
|
/// Snapshot of drop counters.
|
|
294
300
|
pub fn stats(&self) -> FilterStats {
|
|
295
|
-
*self
|
|
301
|
+
*self
|
|
302
|
+
.stats
|
|
303
|
+
.lock()
|
|
304
|
+
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
296
305
|
}
|
|
297
306
|
}
|
|
298
307
|
|
|
@@ -300,6 +309,32 @@ impl Pipeline {
|
|
|
300
309
|
mod tests {
|
|
301
310
|
use super::*;
|
|
302
311
|
|
|
312
|
+
#[test]
|
|
313
|
+
fn poisoned_rate_state_keeps_enforcing_the_existing_window() {
|
|
314
|
+
let limiter = RateLimiter::new(1, Duration::from_secs(60));
|
|
315
|
+
assert_eq!(limiter.allow("same", 20), Decision::Keep);
|
|
316
|
+
let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
|
317
|
+
let _guard = limiter.buckets.lock().unwrap();
|
|
318
|
+
panic!("injected rate state poison");
|
|
319
|
+
}));
|
|
320
|
+
assert!(poisoned.is_err());
|
|
321
|
+
assert_eq!(limiter.allow("same", 20), Decision::Drop);
|
|
322
|
+
assert_eq!(limiter.allow("other", 20), Decision::Keep);
|
|
323
|
+
assert_eq!(limiter.tracked_keys(), 2);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
#[test]
|
|
327
|
+
fn poisoned_filter_stats_remain_readable_and_incrementable() {
|
|
328
|
+
let pipeline = Pipeline::new(0.0, None, None, Duration::from_secs(1));
|
|
329
|
+
let poisoned = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
|
330
|
+
let _guard = pipeline.stats.lock().unwrap();
|
|
331
|
+
panic!("injected filter statistics poison");
|
|
332
|
+
}));
|
|
333
|
+
assert!(poisoned.is_err());
|
|
334
|
+
assert!(!pipeline.allow("record", 20));
|
|
335
|
+
assert_eq!(pipeline.stats().sampled, 1);
|
|
336
|
+
}
|
|
337
|
+
|
|
303
338
|
#[test]
|
|
304
339
|
fn sampler_rate_zero_drops_all() {
|
|
305
340
|
let s = Sampler::new(0.0, None);
|
|
@@ -164,6 +164,18 @@ fn is_sensitive(key: &str, keys: &[impl AsRef<str>]) -> bool {
|
|
|
164
164
|
/// `RedactingProcessor`: no value-pattern matching).
|
|
165
165
|
fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
|
|
166
166
|
match value {
|
|
167
|
+
Value::Keyed {
|
|
168
|
+
aliases,
|
|
169
|
+
value: child,
|
|
170
|
+
} => {
|
|
171
|
+
let redacted = if aliases.iter().any(|alias| is_sensitive(alias, keys)) {
|
|
172
|
+
Value::String(REDACTED.to_owned())
|
|
173
|
+
} else {
|
|
174
|
+
redact(child, keys);
|
|
175
|
+
std::mem::replace(child.as_mut(), Value::Null)
|
|
176
|
+
};
|
|
177
|
+
*value = redacted;
|
|
178
|
+
}
|
|
167
179
|
Value::Map(entries) => {
|
|
168
180
|
for (key, child) in entries.iter_mut() {
|
|
169
181
|
if is_sensitive(key, keys) {
|
|
@@ -204,6 +216,7 @@ fn redact(value: &mut Value, keys: &[impl AsRef<str>]) {
|
|
|
204
216
|
/// secret — `password=(\S+)` with `$1[REDACTED]` would re-emit the secret.
|
|
205
217
|
fn redact_patterns(value: &mut Value, patterns: &[RedactionPattern], replacement: &str) {
|
|
206
218
|
match value {
|
|
219
|
+
Value::Keyed { value, .. } => redact_patterns(value, patterns, replacement),
|
|
207
220
|
Value::Map(entries) => {
|
|
208
221
|
let mut renamed = false;
|
|
209
222
|
for (key, child) in entries.iter_mut() {
|
|
@@ -456,7 +469,7 @@ fn is_console_unsafe(ch: char) -> bool {
|
|
|
456
469
|
| '\u{200E}'
|
|
457
470
|
| '\u{200F}'
|
|
458
471
|
| '\u{202A}'..='\u{202E}'
|
|
459
|
-
| '\u{2066}'..='\u{
|
|
472
|
+
| '\u{2066}'..='\u{206F}'
|
|
460
473
|
)
|
|
461
474
|
}
|
|
462
475
|
|
|
@@ -583,6 +596,7 @@ fn display_value(value: &Value, buf: &mut String) {
|
|
|
583
596
|
buf.push('}');
|
|
584
597
|
}
|
|
585
598
|
Value::Raw(json) => buf.push_str(json), // already-serialized; emit verbatim
|
|
599
|
+
Value::Keyed { value, .. } => display_value(value, buf),
|
|
586
600
|
}
|
|
587
601
|
}
|
|
588
602
|
|
|
@@ -12,6 +12,12 @@ pub enum Value {
|
|
|
12
12
|
String(String),
|
|
13
13
|
List(Vec<Value>),
|
|
14
14
|
Map(Vec<(String, Value)>),
|
|
15
|
+
/// Original mapping-key names retained only for redaction. Serialization
|
|
16
|
+
/// and structural metrics expose the value, never this internal metadata.
|
|
17
|
+
Keyed {
|
|
18
|
+
aliases: Box<[String]>,
|
|
19
|
+
value: Box<Value>,
|
|
20
|
+
},
|
|
15
21
|
/// Pre-serialized, already-valid JSON emitted verbatim.
|
|
16
22
|
///
|
|
17
23
|
/// Used for integers outside the `i64` range: the boundary emits their
|
|
@@ -39,6 +45,10 @@ impl Value {
|
|
|
39
45
|
}
|
|
40
46
|
|
|
41
47
|
fn update_stats(&self, depth: usize, stats: &mut ValueStats) {
|
|
48
|
+
if let Value::Keyed { value, .. } = self {
|
|
49
|
+
value.update_stats(depth, stats);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
42
52
|
stats.nodes += 1;
|
|
43
53
|
stats.max_depth = stats.max_depth.max(depth);
|
|
44
54
|
|
|
@@ -58,6 +68,7 @@ impl Value {
|
|
|
58
68
|
| Value::Int(_)
|
|
59
69
|
| Value::Float(_)
|
|
60
70
|
| Value::String(_)
|
|
71
|
+
| Value::Keyed { .. }
|
|
61
72
|
| Value::Raw(_) => {}
|
|
62
73
|
}
|
|
63
74
|
}
|
|
@@ -122,6 +133,7 @@ impl Serialize for Value {
|
|
|
122
133
|
Value::Int(value) => serializer.serialize_i64(*value),
|
|
123
134
|
Value::Float(value) => serializer.serialize_f64(*value),
|
|
124
135
|
Value::String(value) => serializer.serialize_str(value),
|
|
136
|
+
Value::Keyed { value, .. } => value.serialize(serializer),
|
|
125
137
|
Value::List(items) => {
|
|
126
138
|
let mut seq = serializer.serialize_seq(Some(items.len()))?;
|
|
127
139
|
for item in items {
|
|
@@ -149,6 +161,20 @@ impl Serialize for Value {
|
|
|
149
161
|
mod tests {
|
|
150
162
|
use super::{Value, ValueStats, collapse_duplicate_keys};
|
|
151
163
|
|
|
164
|
+
#[test]
|
|
165
|
+
fn key_alias_metadata_is_not_serialized_or_counted() {
|
|
166
|
+
let inner = Value::List(vec![Value::Int(42)]);
|
|
167
|
+
let keyed = Value::Keyed {
|
|
168
|
+
aliases: vec!["password".to_owned()].into_boxed_slice(),
|
|
169
|
+
value: Box::new(inner.clone()),
|
|
170
|
+
};
|
|
171
|
+
assert_eq!(
|
|
172
|
+
keyed.to_json_string().unwrap(),
|
|
173
|
+
inner.to_json_string().unwrap()
|
|
174
|
+
);
|
|
175
|
+
assert_eq!(keyed.stats(), inner.stats());
|
|
176
|
+
}
|
|
177
|
+
|
|
152
178
|
#[test]
|
|
153
179
|
fn stats_count_nested_value_nodes() {
|
|
154
180
|
let value = Value::Map(vec![
|