structguru 1.7.2__tar.gz → 1.8.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.7.2 → structguru-1.8.0}/Cargo.lock +2 -2
- {structguru-1.7.2 → structguru-1.8.0}/Cargo.toml +1 -1
- {structguru-1.7.2 → structguru-1.8.0}/PKG-INFO +33 -6
- {structguru-1.7.2 → structguru-1.8.0}/README.md +32 -5
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/filter.rs +42 -8
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/render.rs +106 -2
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/worker.rs +83 -5
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/dispatch.rs +20 -6
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/writer.rs +14 -1
- {structguru-1.7.2 → structguru-1.8.0}/pyproject.toml +4 -4
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/__init__.py +1 -1
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/_native_env.py +31 -20
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/_runtime.py +92 -48
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/core.py +52 -8
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/asgi.py +6 -3
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/celery.py +26 -9
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/flask.py +8 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/sentry.py +15 -10
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/stdlib.py +5 -2
- {structguru-1.7.2 → structguru-1.8.0}/LICENSE +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/Cargo.toml +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/clock.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/lib.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-core/src/value.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/Cargo.toml +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/conversion.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/exception.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/filter.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/lib.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/local_repr.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/pipeline.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/rendering.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/submission.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/crates/structguru-py/src/template.rs +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/_contextvars.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/_levels.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/_native_dispatch.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/config.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/exceptions.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/__init__.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/_stdlib_env.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/_util.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/django.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/grpc.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/httpx.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/requests.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/integrations/sqlalchemy.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/metrics.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/otel.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/py.typed +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/redaction.py +0 -0
- {structguru-1.7.2 → structguru-1.8.0}/src/structguru/settings.py +0 -0
|
@@ -245,7 +245,7 @@ dependencies = [
|
|
|
245
245
|
|
|
246
246
|
[[package]]
|
|
247
247
|
name = "structguru-core"
|
|
248
|
-
version = "1.
|
|
248
|
+
version = "1.8.0"
|
|
249
249
|
dependencies = [
|
|
250
250
|
"fancy-regex",
|
|
251
251
|
"fastrand",
|
|
@@ -258,7 +258,7 @@ dependencies = [
|
|
|
258
258
|
|
|
259
259
|
[[package]]
|
|
260
260
|
name = "structguru-py"
|
|
261
|
-
version = "1.
|
|
261
|
+
version = "1.8.0"
|
|
262
262
|
dependencies = [
|
|
263
263
|
"pyo3",
|
|
264
264
|
"regex",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: structguru
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Classifier: Development Status :: 5 - Production/Stable
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -79,6 +79,8 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
|
|
|
79
79
|
- **SQLAlchemy** — slow query detection and logging
|
|
80
80
|
- **gRPC** — server interceptor with per-RPC context binding
|
|
81
81
|
- **Sentry** — forward log events as breadcrumbs/events with configurable severity
|
|
82
|
+
- **httpx** — outbound request logging hooks
|
|
83
|
+
- **requests** — a `Session` subclass that logs outbound requests
|
|
82
84
|
|
|
83
85
|
## Installation
|
|
84
86
|
|
|
@@ -190,7 +192,7 @@ logger.fatal("Alias for critical")
|
|
|
190
192
|
|
|
191
193
|
### Brace formatting
|
|
192
194
|
|
|
193
|
-
Arguments used in `str.format` placeholders are consumed by formatting (
|
|
195
|
+
Arguments used in `str.format` placeholders are consumed by formatting, so they appear in the message and not again as fields (loguru keeps them in its `extra`). Extra kwargs that are **not** in any placeholder are forwarded as structured fields:
|
|
194
196
|
|
|
195
197
|
```python
|
|
196
198
|
from structguru import logger
|
|
@@ -206,7 +208,9 @@ The message is formatted whenever positional or keyword arguments are passed, as
|
|
|
206
208
|
do not count, so `logger.exception("{{x}}")` logs `{{x}}` like `logger.error`. Fields
|
|
207
209
|
named in a nested format spec (`"{x:{width}}"`) are consumed too. A placeholder that
|
|
208
210
|
names a sensitive key — as the root (`{token}`) or an attribute or index
|
|
209
|
-
(`{creds[password]}`) — is interpolated as `[REDACTED]`. A
|
|
211
|
+
(`{creds[password]}`) — is interpolated as `[REDACTED]`. A positional argument has no
|
|
212
|
+
key: `logger.info("password={}", password)` is covered by `sensitive_patterns` only, so
|
|
213
|
+
pass a secret by name. A mapping, sequence, set,
|
|
210
214
|
dataclass, or namespace interpolated whole (`{creds}`) renders with the values under
|
|
211
215
|
sensitive keys redacted; other objects' own `str()` text is covered by
|
|
212
216
|
`sensitive_patterns` only. The message is positional-only,
|
|
@@ -286,7 +290,9 @@ sink never sees the same record twice.
|
|
|
286
290
|
|
|
287
291
|
Logs emitted inside a sink callback, whether it received a native record or a
|
|
288
292
|
raw stdlib one, reach the native writer but skip callable and `logger.add()`
|
|
289
|
-
sinks, preventing recursive delivery and worker deadlocks.
|
|
293
|
+
sinks, preventing recursive delivery and worker deadlocks. The same holds for a
|
|
294
|
+
record logged inside a `metric_processor`, `sentry_processor`, or `stream_sink`
|
|
295
|
+
hook: it skips the hooks. Outside callbacks,
|
|
290
296
|
`logger.remove()` waits for producers that already selected the removed sink
|
|
291
297
|
and for raw stdlib deliveries in progress. Lifecycle calls inside a callback,
|
|
292
298
|
including a stdlib handler's `emit()` on the raw path, cannot wait for the
|
|
@@ -344,6 +350,25 @@ and to integers by their decimal digits (a matching integer is emitted as the
|
|
|
344
350
|
redacted string). If redaction makes two keys of one map equal, the record
|
|
345
351
|
keeps one key with the last value.
|
|
346
352
|
|
|
353
|
+
`sensitive_keys` replaces the built-in keys rather than adding to them, and an
|
|
354
|
+
empty sequence turns key redaction off. To add your own, spread the defaults.
|
|
355
|
+
Keys match as whole names, case-insensitively: `client_secret` is redacted
|
|
356
|
+
because it is in the default set, `password_hash` is not. Add the compound
|
|
357
|
+
names your code logs.
|
|
358
|
+
|
|
359
|
+
```python
|
|
360
|
+
from structguru import DEFAULT_SENSITIVE_KEYS, update
|
|
361
|
+
|
|
362
|
+
update(sensitive_keys=[*DEFAULT_SENSITIVE_KEYS, "internal_ref"])
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Patterns use the syntax of Rust's `regex` crate. It differs from Python's `re`
|
|
366
|
+
in one place that matters when porting a pattern: `$` matches only at the very
|
|
367
|
+
end of the text, not before a trailing newline, so `password=\S+$` leaves a
|
|
368
|
+
value that ends in `\n` unredacted. Drop the anchor, or make the optional
|
|
369
|
+
newline part of the pattern (`password=\S+\n?$`) when consuming it in the
|
|
370
|
+
replacement is acceptable.
|
|
371
|
+
|
|
347
372
|
Patterns run on Rust's linear-time regex engine (no ReDoS), which rejects
|
|
348
373
|
look-around and backreferences at `update()` time. Most look-behinds rewrite
|
|
349
374
|
as capture groups — `(?<=password=)\S+` becomes `(password=)\S+` with
|
|
@@ -452,7 +477,9 @@ traceback still ship:
|
|
|
452
477
|
- `<cycle: dict>` for a container that refers back to itself.
|
|
453
478
|
- `<max depth exceeded>` beyond 64 levels of nesting.
|
|
454
479
|
|
|
455
|
-
Integers outside the 64-bit range are written as JSON numbers,
|
|
480
|
+
Integers outside the 64-bit range are written as JSON numbers, up to
|
|
481
|
+
`sys.get_int_max_str_digits()` digits (4300 by default); a longer one becomes
|
|
482
|
+
`<unsupported: int>`. `int` and
|
|
456
483
|
`float` subclasses (such as `numpy.float64`) are written by value, non-string
|
|
457
484
|
mapping keys are rendered as strings (`{200: 3}` becomes `{"200": 3}`), and
|
|
458
485
|
each unpaired surrogate in text becomes one U+FFFD while a split surrogate pair
|
|
@@ -688,7 +715,7 @@ bridge = install_stdlib_bridge_from_env()
|
|
|
688
715
|
|
|
689
716
|
## Documentation & Examples
|
|
690
717
|
|
|
691
|
-
The [documentation](docs/index.md) follows
|
|
718
|
+
The [documentation](docs/index.md) follows Diátaxis:
|
|
692
719
|
|
|
693
720
|
- **[Tutorials](docs/tutorials/index.md)** — Learn structguru step by step, from the first log line to a logged web service.
|
|
694
721
|
- **[How-to guides](docs/how-to/index.md)** — Configure, route, redact, and integrate with frameworks (FastAPI, Granian, Flask, Django, Celery, gRPC, SQLAlchemy, HTTPX, Requests).
|
|
@@ -34,6 +34,8 @@ Combines a loguru-style API — brace formatting, `bind`, `contextualize`, `opt`
|
|
|
34
34
|
- **SQLAlchemy** — slow query detection and logging
|
|
35
35
|
- **gRPC** — server interceptor with per-RPC context binding
|
|
36
36
|
- **Sentry** — forward log events as breadcrumbs/events with configurable severity
|
|
37
|
+
- **httpx** — outbound request logging hooks
|
|
38
|
+
- **requests** — a `Session` subclass that logs outbound requests
|
|
37
39
|
|
|
38
40
|
## Installation
|
|
39
41
|
|
|
@@ -145,7 +147,7 @@ logger.fatal("Alias for critical")
|
|
|
145
147
|
|
|
146
148
|
### Brace formatting
|
|
147
149
|
|
|
148
|
-
Arguments used in `str.format` placeholders are consumed by formatting (
|
|
150
|
+
Arguments used in `str.format` placeholders are consumed by formatting, so they appear in the message and not again as fields (loguru keeps them in its `extra`). Extra kwargs that are **not** in any placeholder are forwarded as structured fields:
|
|
149
151
|
|
|
150
152
|
```python
|
|
151
153
|
from structguru import logger
|
|
@@ -161,7 +163,9 @@ The message is formatted whenever positional or keyword arguments are passed, as
|
|
|
161
163
|
do not count, so `logger.exception("{{x}}")` logs `{{x}}` like `logger.error`. Fields
|
|
162
164
|
named in a nested format spec (`"{x:{width}}"`) are consumed too. A placeholder that
|
|
163
165
|
names a sensitive key — as the root (`{token}`) or an attribute or index
|
|
164
|
-
(`{creds[password]}`) — is interpolated as `[REDACTED]`. A
|
|
166
|
+
(`{creds[password]}`) — is interpolated as `[REDACTED]`. A positional argument has no
|
|
167
|
+
key: `logger.info("password={}", password)` is covered by `sensitive_patterns` only, so
|
|
168
|
+
pass a secret by name. A mapping, sequence, set,
|
|
165
169
|
dataclass, or namespace interpolated whole (`{creds}`) renders with the values under
|
|
166
170
|
sensitive keys redacted; other objects' own `str()` text is covered by
|
|
167
171
|
`sensitive_patterns` only. The message is positional-only,
|
|
@@ -241,7 +245,9 @@ sink never sees the same record twice.
|
|
|
241
245
|
|
|
242
246
|
Logs emitted inside a sink callback, whether it received a native record or a
|
|
243
247
|
raw stdlib one, reach the native writer but skip callable and `logger.add()`
|
|
244
|
-
sinks, preventing recursive delivery and worker deadlocks.
|
|
248
|
+
sinks, preventing recursive delivery and worker deadlocks. The same holds for a
|
|
249
|
+
record logged inside a `metric_processor`, `sentry_processor`, or `stream_sink`
|
|
250
|
+
hook: it skips the hooks. Outside callbacks,
|
|
245
251
|
`logger.remove()` waits for producers that already selected the removed sink
|
|
246
252
|
and for raw stdlib deliveries in progress. Lifecycle calls inside a callback,
|
|
247
253
|
including a stdlib handler's `emit()` on the raw path, cannot wait for the
|
|
@@ -299,6 +305,25 @@ and to integers by their decimal digits (a matching integer is emitted as the
|
|
|
299
305
|
redacted string). If redaction makes two keys of one map equal, the record
|
|
300
306
|
keeps one key with the last value.
|
|
301
307
|
|
|
308
|
+
`sensitive_keys` replaces the built-in keys rather than adding to them, and an
|
|
309
|
+
empty sequence turns key redaction off. To add your own, spread the defaults.
|
|
310
|
+
Keys match as whole names, case-insensitively: `client_secret` is redacted
|
|
311
|
+
because it is in the default set, `password_hash` is not. Add the compound
|
|
312
|
+
names your code logs.
|
|
313
|
+
|
|
314
|
+
```python
|
|
315
|
+
from structguru import DEFAULT_SENSITIVE_KEYS, update
|
|
316
|
+
|
|
317
|
+
update(sensitive_keys=[*DEFAULT_SENSITIVE_KEYS, "internal_ref"])
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Patterns use the syntax of Rust's `regex` crate. It differs from Python's `re`
|
|
321
|
+
in one place that matters when porting a pattern: `$` matches only at the very
|
|
322
|
+
end of the text, not before a trailing newline, so `password=\S+$` leaves a
|
|
323
|
+
value that ends in `\n` unredacted. Drop the anchor, or make the optional
|
|
324
|
+
newline part of the pattern (`password=\S+\n?$`) when consuming it in the
|
|
325
|
+
replacement is acceptable.
|
|
326
|
+
|
|
302
327
|
Patterns run on Rust's linear-time regex engine (no ReDoS), which rejects
|
|
303
328
|
look-around and backreferences at `update()` time. Most look-behinds rewrite
|
|
304
329
|
as capture groups — `(?<=password=)\S+` becomes `(password=)\S+` with
|
|
@@ -407,7 +432,9 @@ traceback still ship:
|
|
|
407
432
|
- `<cycle: dict>` for a container that refers back to itself.
|
|
408
433
|
- `<max depth exceeded>` beyond 64 levels of nesting.
|
|
409
434
|
|
|
410
|
-
Integers outside the 64-bit range are written as JSON numbers,
|
|
435
|
+
Integers outside the 64-bit range are written as JSON numbers, up to
|
|
436
|
+
`sys.get_int_max_str_digits()` digits (4300 by default); a longer one becomes
|
|
437
|
+
`<unsupported: int>`. `int` and
|
|
411
438
|
`float` subclasses (such as `numpy.float64`) are written by value, non-string
|
|
412
439
|
mapping keys are rendered as strings (`{200: 3}` becomes `{"200": 3}`), and
|
|
413
440
|
each unpaired surrogate in text becomes one U+FFFD while a split surrogate pair
|
|
@@ -643,7 +670,7 @@ bridge = install_stdlib_bridge_from_env()
|
|
|
643
670
|
|
|
644
671
|
## Documentation & Examples
|
|
645
672
|
|
|
646
|
-
The [documentation](docs/index.md) follows
|
|
673
|
+
The [documentation](docs/index.md) follows Diátaxis:
|
|
647
674
|
|
|
648
675
|
- **[Tutorials](docs/tutorials/index.md)** — Learn structguru step by step, from the first log line to a logged web service.
|
|
649
676
|
- **[How-to guides](docs/how-to/index.md)** — Configure, route, redact, and integrate with frameworks (FastAPI, Granian, Flask, Django, Celery, gRPC, SQLAlchemy, HTTPX, Requests).
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
//! rate-limited), separate from the writer's transport-level `dropped` counter.
|
|
6
6
|
|
|
7
7
|
use std::collections::{HashMap, VecDeque};
|
|
8
|
+
use std::hash::{DefaultHasher, Hash, Hasher};
|
|
8
9
|
use std::sync::Mutex;
|
|
9
10
|
use std::time::{Duration, Instant};
|
|
10
11
|
|
|
@@ -76,13 +77,32 @@ impl RecordFilter for Sampler {
|
|
|
76
77
|
/// evicted so a stream of unique messages cannot grow memory for a period.
|
|
77
78
|
pub const RATE_LIMIT_MAX_KEYS: usize = 8192;
|
|
78
79
|
|
|
80
|
+
/// Fixed-size identity of one rate-limit key (the formatted message).
|
|
81
|
+
///
|
|
82
|
+
/// The table holds at most `max_keys` entries, but a message of any length
|
|
83
|
+
/// used to be its own key, so a stream of large unique messages grew memory
|
|
84
|
+
/// with their size and eviction copied every one of them. A 128-bit digest
|
|
85
|
+
/// keeps both independent of the message; two messages sharing a digest is a
|
|
86
|
+
/// 2^-128 coincidence that could only group them under one limit.
|
|
87
|
+
fn key_id(key: &str) -> u128 {
|
|
88
|
+
let mut low = DefaultHasher::new();
|
|
89
|
+
key.hash(&mut low);
|
|
90
|
+
// A salted second pass: the halves share no prefix.
|
|
91
|
+
let mut high = DefaultHasher::new();
|
|
92
|
+
high.write_u64(0x5374_7275_6374_6775);
|
|
93
|
+
key.hash(&mut high);
|
|
94
|
+
u128::from(low.finish()) | (u128::from(high.finish()) << 64)
|
|
95
|
+
}
|
|
96
|
+
|
|
79
97
|
/// Sliding-window rate limiter keyed by the formatted message.
|
|
80
98
|
///
|
|
81
99
|
/// Allows at most `max_count` records per key within `period`. Stale buckets are
|
|
82
100
|
/// pruned lazily on access and periodically garbage-collected, mirroring the
|
|
83
101
|
/// Python `RateLimitingProcessor` semantics. The key table is capped at
|
|
84
102
|
/// `max_keys` entries; when a new key would exceed it, stale buckets are swept
|
|
85
|
-
/// and then the least recently seen tenth of the table is evicted.
|
|
103
|
+
/// and then the least recently seen tenth of the table is evicted. Each entry
|
|
104
|
+
/// stores a [`key_id`] digest, never the message, so the table's memory does
|
|
105
|
+
/// not depend on how long the messages are.
|
|
86
106
|
pub struct RateLimiter {
|
|
87
107
|
max_count: usize,
|
|
88
108
|
period: Duration,
|
|
@@ -99,8 +119,8 @@ struct Bucket {
|
|
|
99
119
|
}
|
|
100
120
|
|
|
101
121
|
struct RateLimiterState {
|
|
102
|
-
/// Per-key sliding-window timestamps.
|
|
103
|
-
timestamps: HashMap<
|
|
122
|
+
/// Per-key sliding-window timestamps, by message digest.
|
|
123
|
+
timestamps: HashMap<u128, Bucket>,
|
|
104
124
|
/// Bounded GC frequency so sweeping does not dominate the hot path.
|
|
105
125
|
cleanup_counter: u64,
|
|
106
126
|
cleanup_interval: u64,
|
|
@@ -127,6 +147,7 @@ impl RateLimiter {
|
|
|
127
147
|
}
|
|
128
148
|
|
|
129
149
|
fn allow_key(&self, key: &str, now: Instant) -> Decision {
|
|
150
|
+
let id = key_id(key);
|
|
130
151
|
let mut state = self
|
|
131
152
|
.buckets
|
|
132
153
|
.lock()
|
|
@@ -135,14 +156,14 @@ impl RateLimiter {
|
|
|
135
156
|
|
|
136
157
|
// Prune the candidate bucket up to the window edge.
|
|
137
158
|
if let Some(cutoff) = cutoff
|
|
138
|
-
&& let Some(bucket) = state.timestamps.get_mut(
|
|
159
|
+
&& let Some(bucket) = state.timestamps.get_mut(&id)
|
|
139
160
|
{
|
|
140
161
|
while bucket.hits.front().is_some_and(|&t| t <= cutoff) {
|
|
141
162
|
bucket.hits.pop_front();
|
|
142
163
|
}
|
|
143
164
|
}
|
|
144
165
|
|
|
145
|
-
if !state.timestamps.contains_key(
|
|
166
|
+
if !state.timestamps.contains_key(&id) && state.timestamps.len() >= self.max_keys {
|
|
146
167
|
if let Some(cutoff) = cutoff {
|
|
147
168
|
sweep_stale(&mut state, cutoff);
|
|
148
169
|
}
|
|
@@ -150,7 +171,7 @@ impl RateLimiter {
|
|
|
150
171
|
evict_least_recent(&mut state, self.max_keys - self.max_keys / 10);
|
|
151
172
|
}
|
|
152
173
|
}
|
|
153
|
-
let bucket = state.timestamps.entry(
|
|
174
|
+
let bucket = state.timestamps.entry(id).or_default();
|
|
154
175
|
bucket.last_seen = Some(now);
|
|
155
176
|
if bucket.hits.len() >= self.max_count {
|
|
156
177
|
return Decision::Drop;
|
|
@@ -190,15 +211,17 @@ fn sweep_stale(state: &mut RateLimiterState, cutoff: Instant) {
|
|
|
190
211
|
}
|
|
191
212
|
|
|
192
213
|
/// Shrink the key table to `keep` entries, dropping those seen least recently.
|
|
214
|
+
/// Keys are digests, so selecting them allocates one small vector and copies
|
|
215
|
+
/// no message text.
|
|
193
216
|
fn evict_least_recent(state: &mut RateLimiterState, keep: usize) {
|
|
194
217
|
let excess = state.timestamps.len().saturating_sub(keep);
|
|
195
218
|
if excess == 0 {
|
|
196
219
|
return;
|
|
197
220
|
}
|
|
198
|
-
let mut by_age: Vec<(Option<Instant>,
|
|
221
|
+
let mut by_age: Vec<(Option<Instant>, u128)> = state
|
|
199
222
|
.timestamps
|
|
200
223
|
.iter()
|
|
201
|
-
.map(|(key, bucket)| (bucket.last_seen, key
|
|
224
|
+
.map(|(key, bucket)| (bucket.last_seen, *key))
|
|
202
225
|
.collect();
|
|
203
226
|
by_age.sort_unstable_by_key(|(last, _)| *last);
|
|
204
227
|
for (_, key) in by_age.into_iter().take(excess) {
|
|
@@ -432,6 +455,17 @@ mod tests {
|
|
|
432
455
|
assert_eq!(r.allow_key("beta", now), Decision::Drop);
|
|
433
456
|
}
|
|
434
457
|
|
|
458
|
+
#[test]
|
|
459
|
+
fn rate_limiter_digests_group_identical_messages_only() {
|
|
460
|
+
let id = key_id("request id=1");
|
|
461
|
+
assert_eq!(id, key_id("request id=1"));
|
|
462
|
+
assert_ne!(id, key_id("request id=2"));
|
|
463
|
+
assert_ne!(id, key_id("request id=1 "));
|
|
464
|
+
assert_ne!(key_id("a"), key_id("b"));
|
|
465
|
+
// The table key is a fixed-size digest, never the message text.
|
|
466
|
+
assert_eq!(std::mem::size_of_val(&id), 16);
|
|
467
|
+
}
|
|
468
|
+
|
|
435
469
|
#[test]
|
|
436
470
|
fn rate_limiter_key_table_is_capped_and_keeps_hot_keys() {
|
|
437
471
|
let limiter = RateLimiter::with_max_keys(2, Duration::from_secs(60), 100);
|
|
@@ -129,18 +129,35 @@ pub const REDACTED_MARKER_KEY: &str = "_structguru_redacted";
|
|
|
129
129
|
|
|
130
130
|
/// Default sensitive keys. This constant is the single source of truth:
|
|
131
131
|
/// `structguru.redaction.DEFAULT_SENSITIVE_KEYS` is built from it at import.
|
|
132
|
+
///
|
|
133
|
+
/// Whole names only (`is_sensitive`): compounds such as `password_hash` or
|
|
134
|
+
/// `x-usertoken` do not match, so each common spelling is listed by itself.
|
|
132
135
|
pub const DEFAULT_SENSITIVE_KEYS: &[&str] = &[
|
|
133
136
|
"password",
|
|
134
137
|
"passwd",
|
|
138
|
+
"passphrase",
|
|
139
|
+
"pwd",
|
|
135
140
|
"secret",
|
|
141
|
+
"secret_key",
|
|
142
|
+
"client_secret",
|
|
143
|
+
"secret_access_key",
|
|
136
144
|
"token",
|
|
137
145
|
"api_key",
|
|
138
146
|
"apikey",
|
|
147
|
+
"api-key",
|
|
148
|
+
"x-api-key",
|
|
139
149
|
"access_token",
|
|
140
150
|
"refresh_token",
|
|
151
|
+
"auth_token",
|
|
152
|
+
"id_token",
|
|
153
|
+
"jwt",
|
|
141
154
|
"authorization",
|
|
142
155
|
"cookie",
|
|
156
|
+
"set-cookie",
|
|
143
157
|
"session_id",
|
|
158
|
+
"session_key",
|
|
159
|
+
"credential",
|
|
160
|
+
"credentials",
|
|
144
161
|
"credit_card",
|
|
145
162
|
"ssn",
|
|
146
163
|
"private_key",
|
|
@@ -458,21 +475,43 @@ const ANSI_RESET: &str = "\x1b[0m";
|
|
|
458
475
|
/// (manipulating the operator's terminal), a Unicode line or paragraph
|
|
459
476
|
/// separator (a line break for `str.splitlines()` and many viewers), or a
|
|
460
477
|
/// bidirectional formatting control (reordering how the rest of the line
|
|
461
|
-
/// displays). Covers C0/C1 controls, U+2028, U+2029, and
|
|
478
|
+
/// displays). Covers C0/C1 controls, U+2028, U+2029, and every format (`Cf`)
|
|
479
|
+
/// character except the ones natural text uses for meaning: the joiners
|
|
480
|
+
/// U+200B–U+200D (emoji sequences, Arabic and Indic scripts) and the soft
|
|
481
|
+
/// hyphen. The rest are invisible in any font, so a value could hide payload
|
|
482
|
+
/// in them that a reader never sees.
|
|
462
483
|
fn is_console_unsafe(ch: char) -> bool {
|
|
463
484
|
ch.is_control()
|
|
464
485
|
|| matches!(
|
|
465
486
|
ch,
|
|
466
487
|
'\u{2028}'
|
|
467
488
|
| '\u{2029}'
|
|
489
|
+
| '\u{0600}'..='\u{0605}'
|
|
468
490
|
| '\u{061C}'
|
|
491
|
+
| '\u{06DD}'
|
|
492
|
+
| '\u{070F}'
|
|
493
|
+
| '\u{0890}'..='\u{0891}'
|
|
494
|
+
| '\u{08E2}'
|
|
495
|
+
| '\u{180E}'
|
|
469
496
|
| '\u{200E}'
|
|
470
497
|
| '\u{200F}'
|
|
471
498
|
| '\u{202A}'..='\u{202E}'
|
|
499
|
+
| '\u{2060}'..='\u{2064}'
|
|
472
500
|
| '\u{2066}'..='\u{206F}'
|
|
501
|
+
| '\u{FEFF}'
|
|
502
|
+
| '\u{FFF9}'..='\u{FFFB}'
|
|
503
|
+
| '\u{110BD}'
|
|
504
|
+
| '\u{110CD}'
|
|
505
|
+
| '\u{13430}'..='\u{1343F}'
|
|
506
|
+
| '\u{1BCA0}'..='\u{1BCA3}'
|
|
507
|
+
| '\u{1D173}'..='\u{1D17A}'
|
|
508
|
+
| '\u{E0001}'
|
|
509
|
+
| '\u{E0020}'..='\u{E007F}'
|
|
473
510
|
)
|
|
474
511
|
}
|
|
475
512
|
|
|
513
|
+
/// `repr`-style text for one character, as Python spells it: `\xNN` up to
|
|
514
|
+
/// U+00FF, `\uNNNN` up to U+FFFF, and `\UNNNNNNNN` beyond.
|
|
476
515
|
fn push_char_escape(buf: &mut String, ch: char) {
|
|
477
516
|
use std::fmt::Write;
|
|
478
517
|
match ch {
|
|
@@ -482,9 +521,12 @@ fn push_char_escape(buf: &mut String, ch: char) {
|
|
|
482
521
|
c if u32::from(c) <= 0xFF => {
|
|
483
522
|
let _ = write!(buf, "\\x{:02x}", u32::from(c));
|
|
484
523
|
}
|
|
485
|
-
c => {
|
|
524
|
+
c if u32::from(c) <= 0xFFFF => {
|
|
486
525
|
let _ = write!(buf, "\\u{:04x}", u32::from(c));
|
|
487
526
|
}
|
|
527
|
+
c => {
|
|
528
|
+
let _ = write!(buf, "\\U{:08x}", u32::from(c));
|
|
529
|
+
}
|
|
488
530
|
}
|
|
489
531
|
}
|
|
490
532
|
|
|
@@ -1446,6 +1488,68 @@ mod tests {
|
|
|
1446
1488
|
);
|
|
1447
1489
|
}
|
|
1448
1490
|
|
|
1491
|
+
#[test]
|
|
1492
|
+
fn console_escapes_invisible_format_characters() {
|
|
1493
|
+
for ch in [
|
|
1494
|
+
'\u{0600}',
|
|
1495
|
+
'\u{0605}',
|
|
1496
|
+
'\u{06DD}',
|
|
1497
|
+
'\u{070F}',
|
|
1498
|
+
'\u{0890}',
|
|
1499
|
+
'\u{08E2}',
|
|
1500
|
+
'\u{180E}',
|
|
1501
|
+
'\u{2060}',
|
|
1502
|
+
'\u{2064}',
|
|
1503
|
+
'\u{FEFF}',
|
|
1504
|
+
'\u{FFF9}',
|
|
1505
|
+
'\u{FFFB}',
|
|
1506
|
+
'\u{110BD}',
|
|
1507
|
+
'\u{1343F}',
|
|
1508
|
+
'\u{1BCA0}',
|
|
1509
|
+
'\u{1D17A}',
|
|
1510
|
+
'\u{E0001}',
|
|
1511
|
+
'\u{E0020}',
|
|
1512
|
+
'\u{E0041}',
|
|
1513
|
+
'\u{E007F}',
|
|
1514
|
+
] {
|
|
1515
|
+
assert!(is_console_unsafe(ch), "U+{:04X}", u32::from(ch));
|
|
1516
|
+
}
|
|
1517
|
+
// The joiners and the soft hyphen carry meaning in natural text.
|
|
1518
|
+
for ch in [
|
|
1519
|
+
'\u{00AD}',
|
|
1520
|
+
'\u{200B}',
|
|
1521
|
+
'\u{200C}',
|
|
1522
|
+
'\u{200D}',
|
|
1523
|
+
'a',
|
|
1524
|
+
'é',
|
|
1525
|
+
'\u{1F600}',
|
|
1526
|
+
] {
|
|
1527
|
+
assert!(!is_console_unsafe(ch), "U+{:04X}", u32::from(ch));
|
|
1528
|
+
}
|
|
1529
|
+
let fields = vec![(
|
|
1530
|
+
"k".to_owned(),
|
|
1531
|
+
Value::String("a\u{2060}b\u{FEFF}[S]\u{E0041}hidden\u{1D173}".to_owned()),
|
|
1532
|
+
)];
|
|
1533
|
+
let line = render_line_console(
|
|
1534
|
+
fields,
|
|
1535
|
+
"l",
|
|
1536
|
+
"info",
|
|
1537
|
+
"svc",
|
|
1538
|
+
"m\u{E0001}\u{1F64D}",
|
|
1539
|
+
false,
|
|
1540
|
+
"TS",
|
|
1541
|
+
None,
|
|
1542
|
+
None,
|
|
1543
|
+
None,
|
|
1544
|
+
None,
|
|
1545
|
+
);
|
|
1546
|
+
assert_eq!(
|
|
1547
|
+
line,
|
|
1548
|
+
"TS [INFO ] m\\U000e0001\u{1F64D} \
|
|
1549
|
+
k=\"a\\u2060b\\ufeff[S]\\U000e0041hidden\\U0001d173\""
|
|
1550
|
+
);
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1449
1553
|
#[test]
|
|
1450
1554
|
fn console_floats_match_json_number_text() {
|
|
1451
1555
|
let fields = vec![
|
|
@@ -170,14 +170,53 @@ impl StringSink for StdoutSink {
|
|
|
170
170
|
|
|
171
171
|
#[cfg(unix)]
|
|
172
172
|
fn write_stdout(bytes: &[u8]) -> std::io::Result<()> {
|
|
173
|
-
use std::mem::ManuallyDrop;
|
|
174
173
|
use std::os::fd::FromRawFd;
|
|
175
174
|
|
|
176
175
|
// SAFETY: the handle borrows fd 1 for this one write and `ManuallyDrop`
|
|
177
176
|
// keeps it from ever being closed. This is how the standard library's own
|
|
178
177
|
// raw stdout writes; a closed fd 1 only makes `write` fail with EBADF.
|
|
179
178
|
let mut stdout = ManuallyDrop::new(unsafe { File::from_raw_fd(1) });
|
|
180
|
-
|
|
179
|
+
let mut pending = bytes;
|
|
180
|
+
while !pending.is_empty() {
|
|
181
|
+
match stdout.write(pending) {
|
|
182
|
+
// A non-blocking fd 1 whose pipe is full reports `WouldBlock`, as
|
|
183
|
+
// when a parent or a pipe transport left the flag on. Wait for
|
|
184
|
+
// room and resume with the unwritten bytes: block mode loses
|
|
185
|
+
// nothing to a slow sink, and the line is never left torn. A
|
|
186
|
+
// stalled pipe is bounded by the flush() and close() abandonment.
|
|
187
|
+
Err(err) if err.kind() == ErrorKind::WouldBlock => wait_writable()?,
|
|
188
|
+
Err(err) if err.kind() == ErrorKind::Interrupted => continue,
|
|
189
|
+
Ok(0) => {
|
|
190
|
+
return Err(std::io::Error::new(
|
|
191
|
+
ErrorKind::WriteZero,
|
|
192
|
+
"stdout write wrote nothing",
|
|
193
|
+
));
|
|
194
|
+
}
|
|
195
|
+
Ok(written) => pending = &pending[written..],
|
|
196
|
+
Err(err) => return Err(err),
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
Ok(())
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/// Block until fd 1 can accept a write; a signal only restarts the wait.
|
|
203
|
+
#[cfg(unix)]
|
|
204
|
+
fn wait_writable() -> std::io::Result<()> {
|
|
205
|
+
loop {
|
|
206
|
+
let mut descriptor = libc::pollfd {
|
|
207
|
+
fd: 1,
|
|
208
|
+
events: libc::POLLOUT,
|
|
209
|
+
revents: 0,
|
|
210
|
+
};
|
|
211
|
+
// SAFETY: `poll` reads the one `pollfd` and writes only its `revents`.
|
|
212
|
+
if unsafe { libc::poll(&mut descriptor, 1, -1) } >= 0 {
|
|
213
|
+
return Ok(());
|
|
214
|
+
}
|
|
215
|
+
let error = std::io::Error::last_os_error();
|
|
216
|
+
if error.kind() != ErrorKind::Interrupted {
|
|
217
|
+
return Err(error);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
181
220
|
}
|
|
182
221
|
|
|
183
222
|
#[cfg(not(unix))]
|
|
@@ -320,12 +359,25 @@ fn file_identity(meta: &fs::Metadata) -> Option<(u64, u64)> {
|
|
|
320
359
|
}
|
|
321
360
|
|
|
322
361
|
impl RotatingFileSink {
|
|
323
|
-
///
|
|
324
|
-
/// created if they do not exist (a small convenience over CPython).
|
|
362
|
+
/// Like [`Self::with_lock_timeout`] with the documented stall bound (10 s).
|
|
325
363
|
pub fn new(
|
|
326
364
|
path: impl Into<PathBuf>,
|
|
327
365
|
max_bytes: usize,
|
|
328
366
|
backup_count: usize,
|
|
367
|
+
) -> Result<Self, SinkError> {
|
|
368
|
+
Self::with_lock_timeout(path, max_bytes, backup_count, Duration::from_secs(10))
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/// Open `path` for append (created if missing), waiting at most
|
|
372
|
+
/// `lock_timeout` for the sidecar lock. Parent directories are created if
|
|
373
|
+
/// they do not exist (a small convenience over CPython). A holder that
|
|
374
|
+
/// never releases it, such as a sibling worker stopped inside its write
|
|
375
|
+
/// section, is an error instead of a wait without end.
|
|
376
|
+
pub fn with_lock_timeout(
|
|
377
|
+
path: impl Into<PathBuf>,
|
|
378
|
+
max_bytes: usize,
|
|
379
|
+
backup_count: usize,
|
|
380
|
+
lock_timeout: Duration,
|
|
329
381
|
) -> Result<Self, SinkError> {
|
|
330
382
|
let path =
|
|
331
383
|
std::path::absolute(path.into()).map_err(|err| SinkError::new(err.to_string()))?;
|
|
@@ -335,7 +387,7 @@ impl RotatingFileSink {
|
|
|
335
387
|
fs::create_dir_all(parent).map_err(|err| SinkError::new(err.to_string()))?;
|
|
336
388
|
}
|
|
337
389
|
let lock_file = open_lock(&path)?;
|
|
338
|
-
|
|
390
|
+
lock_exclusive_within(&lock_file, lock_timeout)?;
|
|
339
391
|
let opened = open_append(&path);
|
|
340
392
|
let unlock_result = File::unlock(&lock_file);
|
|
341
393
|
let file = opened?;
|
|
@@ -512,6 +564,32 @@ fn lock_exclusive(lock_file: &File) -> Result<(), SinkError> {
|
|
|
512
564
|
}
|
|
513
565
|
}
|
|
514
566
|
|
|
567
|
+
/// How often a waiting opener re-tests the sidecar lock.
|
|
568
|
+
const LOCK_POLL_INTERVAL: Duration = Duration::from_millis(10);
|
|
569
|
+
|
|
570
|
+
/// Take the sidecar lock, giving up after `timeout` instead of waiting
|
|
571
|
+
/// forever behind a holder that is stopped.
|
|
572
|
+
fn lock_exclusive_within(lock_file: &File, timeout: Duration) -> Result<(), SinkError> {
|
|
573
|
+
use std::fs::TryLockError;
|
|
574
|
+
|
|
575
|
+
let deadline = Instant::now() + timeout;
|
|
576
|
+
loop {
|
|
577
|
+
match lock_file.try_lock() {
|
|
578
|
+
Err(TryLockError::WouldBlock) => {
|
|
579
|
+
if Instant::now() >= deadline {
|
|
580
|
+
return Err(SinkError::new(
|
|
581
|
+
"timed out waiting for another process to release the log file lock",
|
|
582
|
+
));
|
|
583
|
+
}
|
|
584
|
+
thread::sleep(LOCK_POLL_INTERVAL);
|
|
585
|
+
}
|
|
586
|
+
// A signal interrupted the attempt, which made no decision.
|
|
587
|
+
Err(TryLockError::Error(ref err)) if err.kind() == ErrorKind::Interrupted => {}
|
|
588
|
+
result => return result.map_err(|err| SinkError::new(err.to_string())),
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
515
593
|
/// `write_all` that also reports how many bytes reached the file before an error.
|
|
516
594
|
fn write_counted(file: &mut File, bytes: &[u8]) -> (usize, std::io::Result<()>) {
|
|
517
595
|
let mut written = 0;
|
|
@@ -16,25 +16,35 @@
|
|
|
16
16
|
|
|
17
17
|
use std::cell::Cell;
|
|
18
18
|
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
|
19
|
-
use std::ffi::CString;
|
|
20
19
|
use std::ops::{Deref, DerefMut};
|
|
21
20
|
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU8, AtomicU64, AtomicUsize, Ordering};
|
|
22
21
|
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak};
|
|
23
22
|
use std::thread::JoinHandle;
|
|
24
23
|
use std::time::{Duration, Instant};
|
|
25
24
|
|
|
26
|
-
use pyo3::exceptions::
|
|
25
|
+
use pyo3::exceptions::PyRuntimeError;
|
|
27
26
|
use pyo3::prelude::*;
|
|
27
|
+
use pyo3::sync::PyOnceLock;
|
|
28
28
|
use pyo3::types::{PyDict, PyString};
|
|
29
29
|
|
|
30
|
-
/// Issue a `UserWarning` that can
|
|
30
|
+
/// Issue a `UserWarning` that can neither interrupt nor stall the caller.
|
|
31
31
|
///
|
|
32
32
|
/// A diagnostic about logging must not make logging fail: when a warnings
|
|
33
33
|
/// filter turns it into an exception (`-W error`), the exception goes to
|
|
34
|
-
/// `sys.unraisablehook`, as CPython reports errors it cannot raise.
|
|
34
|
+
/// `sys.unraisablehook`, as CPython reports errors it cannot raise. The Python
|
|
35
|
+
/// diagnostic path records the warning and writes it with a bound, so this
|
|
36
|
+
/// thread never waits on stderr: that would stop it delivering to every other
|
|
37
|
+
/// sink, and it would hold the warnings lock that `shutdown()` later needs.
|
|
35
38
|
fn warn(py: Python<'_>, message: &str, stacklevel: i32) {
|
|
36
|
-
|
|
37
|
-
|
|
39
|
+
static WARN: PyOnceLock<Py<PyAny>> = PyOnceLock::new();
|
|
40
|
+
let issued = WARN
|
|
41
|
+
.get_or_try_init(py, || {
|
|
42
|
+
py.import("structguru._runtime")?
|
|
43
|
+
.getattr("_warn_from_native")
|
|
44
|
+
.map(Bound::unbind)
|
|
45
|
+
})
|
|
46
|
+
.and_then(|warn| warn.bind(py).call1((message, stacklevel)).map(|_| ()));
|
|
47
|
+
if let Err(error) = issued {
|
|
38
48
|
error.write_unraisable(py, None);
|
|
39
49
|
}
|
|
40
50
|
}
|
|
@@ -1581,6 +1591,10 @@ impl CallableDispatcher {
|
|
|
1581
1591
|
result.set_item("callable_errors", self.inner.errors.load(Ordering::Acquire))?;
|
|
1582
1592
|
result.set_item("callable_depth", depth)?;
|
|
1583
1593
|
result.set_item("callable_maxsize", registry.maxsize)?;
|
|
1594
|
+
result.set_item(
|
|
1595
|
+
"callable_sinks",
|
|
1596
|
+
registry.configured.len() + registry.runtime.len(),
|
|
1597
|
+
)?;
|
|
1584
1598
|
Ok(result)
|
|
1585
1599
|
}
|
|
1586
1600
|
|