guardrail-proxy 0.6.0

HTTP reverse-proxy server for guardrail-rs
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
//! Prometheus metrics for `guardrail-rs`.
//!
//! Exposes a `/metrics` endpoint compatible with Prometheus scraping. All
//! metrics are registered in a process-global [`prometheus::Registry`] created
//! once at startup via [`Metrics::new`].

use prometheus::{
    Encoder, Gauge, Histogram, HistogramOpts, IntCounter, IntCounterVec, Opts, Registry,
    TextEncoder,
};

/// Container for all Prometheus metrics emitted by the proxy.
///
/// Cloning is cheap: all fields are `Arc`-backed internally by the
/// `prometheus` crate's collector types.
#[derive(Clone)]
pub struct Metrics {
    /// Total number of requests received, labeled by decision (`allow`,
    /// `redact`, `block`) and provider.
    pub requests_total: IntCounterVec,
    /// Total number of requests blocked, labeled by block code.
    pub blocked_total: IntCounterVec,
    /// Total number of requests with PII redacted on the **request** side.
    pub redacted_total: IntCounter,
    /// Total number of responses with PII redacted on the **response** side
    /// (see [`crate::response`]).
    pub response_redacted_total: IntCounter,
    /// Total number of responses that response redaction was on for but
    /// could not inspect, labeled by reason: `"unknown_encoding"` (refused
    /// with 502), `"unparseable_body"` or `"unknown_content_type"`
    /// (forwarded unredacted).
    pub response_redaction_skipped_total: IntCounterVec,
    /// End-to-end pipeline evaluation latency, in seconds.
    pub pipeline_duration_seconds: Histogram,
    /// Per-stage evaluation latency, in seconds, labeled by stage name.
    pub stage_duration_seconds: prometheus::HistogramVec,
    /// End-to-end request latency, in seconds, **including** time spent
    /// waiting on the upstream provider. Labeled by decision.
    pub request_duration_seconds: prometheus::HistogramVec,
    /// Total number of failed upstream requests, labeled by a coarse error
    /// class (`"timeout"`, `"connect"`, `"other"`).
    pub upstream_errors_total: IntCounterVec,
    /// Total number of pipeline stage errors, labeled by stage and by how the
    /// stage's `on_error` resolved them: `"allowed"` (fail-open: the request
    /// continued without that stage's check) or `"blocked"` (fail-closed).
    pub pipeline_errors_total: IntCounterVec,
    /// Total number of requests whose input was too long for a stage to
    /// check (ONNX `max_windows`), labeled by stage and by how
    /// `on_oversize` resolved it (`"blocked"` or `"allowed"`), and by why
    /// (`"over_limit"`, or `"unmeasured"` for input longer than the stage
    /// measures).
    pub stage_oversize_total: IntCounterVec,
    /// Total number of requests turned away with `503 overloaded`, labeled
    /// by the limit that was full (`"proxy"`: `server.max_concurrent_requests`).
    pub overload_rejections_total: IntCounterVec,
    /// Current number of in-flight HTTP connections being served.
    pub active_connections: Gauge,
    /// The registry these metrics are registered in.
    registry: Registry,
}

impl Metrics {
    /// Create a new metrics registry with all collectors registered.
    ///
    /// # Panics
    ///
    /// Panics if metric registration fails (only possible on duplicate
    /// registration, which cannot happen since this is called once at startup).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use guardrail_proxy::metrics::Metrics;
    ///
    /// let metrics = Metrics::new();
    /// metrics.requests_total.with_label_values(&["allow", "openai"]).inc();
    /// assert_eq!(metrics.requests_total.with_label_values(&["allow", "openai"]).get(), 1);
    /// ```
    pub fn new() -> Self {
        let registry = Registry::new();

        let requests_total = IntCounterVec::new(
            Opts::new(
                "guardrail_requests_total",
                "Total number of requests evaluated, labeled by decision and provider.",
            ),
            &["decision", "provider"],
        )
        .expect("valid metric definition");

        let blocked_total = IntCounterVec::new(
            Opts::new(
                "guardrail_blocked_total",
                "Total number of requests blocked, labeled by block code.",
            ),
            &["code"],
        )
        .expect("valid metric definition");

        let redacted_total = IntCounter::new(
            "guardrail_redacted_total",
            "Total number of requests that had PII redacted on the request side.",
        )
        .expect("valid metric definition");

        let response_redacted_total = IntCounter::new(
            "guardrail_response_redacted_total",
            "Total number of responses that had PII redacted on the response side.",
        )
        .expect("valid metric definition");

        let response_redaction_skipped_total = IntCounterVec::new(
            Opts::new(
                "guardrail_response_redaction_skipped_total",
                "Total number of responses that response redaction was on for but could not \
                 inspect, labeled by reason.",
            ),
            &["reason"],
        )
        .expect("valid metric definition");

        let pipeline_duration_seconds = Histogram::with_opts(
            HistogramOpts::new(
                "guardrail_pipeline_duration_seconds",
                "End-to-end pipeline evaluation latency in seconds.",
            )
            .buckets(vec![
                0.00005, 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1,
            ]),
        )
        .expect("valid metric definition");

        let stage_duration_seconds = prometheus::HistogramVec::new(
            HistogramOpts::new(
                "guardrail_stage_duration_seconds",
                "Per-stage evaluation latency in seconds, labeled by stage name.",
            )
            .buckets(vec![
                0.00001, 0.00005, 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05,
            ]),
            &["stage"],
        )
        .expect("valid metric definition");

        let request_duration_seconds = prometheus::HistogramVec::new(
            HistogramOpts::new(
                "guardrail_request_duration_seconds",
                "End-to-end request latency in seconds, including upstream time, labeled by decision.",
            )
            .buckets(vec![
                0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
            ]),
            &["decision"],
        )
        .expect("valid metric definition");

        let upstream_errors_total = IntCounterVec::new(
            Opts::new(
                "guardrail_upstream_errors_total",
                "Total number of failed upstream requests, labeled by error class.",
            ),
            &["error_class"],
        )
        .expect("valid metric definition");

        let pipeline_errors_total = IntCounterVec::new(
            Opts::new(
                "guardrail_pipeline_errors_total",
                "Total number of pipeline stage errors, labeled by stage and outcome \
                 (allowed = failed open, blocked = failed closed).",
            ),
            &["stage", "outcome"],
        )
        .expect("valid metric definition");

        let stage_oversize_total = IntCounterVec::new(
            Opts::new(
                "guardrail_stage_oversize_total",
                "Total number of requests whose input was too long for a stage to check, \
                 labeled by stage, outcome (blocked, or allowed unchecked) and reason \
                 (over_limit, or unmeasured: longer than the stage measures).",
            ),
            &["stage", "outcome", "reason"],
        )
        .expect("valid metric definition");

        let overload_rejections_total = IntCounterVec::new(
            Opts::new(
                "guardrail_overload_rejections_total",
                "Total number of requests answered 503 overloaded, labeled by the limit \
                 that was full.",
            ),
            &["limit"],
        )
        .expect("valid metric definition");

        let active_connections = Gauge::new(
            "guardrail_active_connections",
            "Current number of in-flight HTTP connections being served.",
        )
        .expect("valid metric definition");

        registry
            .register(Box::new(requests_total.clone()))
            .expect("register requests_total");
        registry
            .register(Box::new(blocked_total.clone()))
            .expect("register blocked_total");
        registry
            .register(Box::new(redacted_total.clone()))
            .expect("register redacted_total");
        registry
            .register(Box::new(response_redacted_total.clone()))
            .expect("register response_redacted_total");
        registry
            .register(Box::new(response_redaction_skipped_total.clone()))
            .expect("register response_redaction_skipped_total");
        registry
            .register(Box::new(pipeline_duration_seconds.clone()))
            .expect("register pipeline_duration_seconds");
        registry
            .register(Box::new(stage_duration_seconds.clone()))
            .expect("register stage_duration_seconds");
        registry
            .register(Box::new(request_duration_seconds.clone()))
            .expect("register request_duration_seconds");
        registry
            .register(Box::new(upstream_errors_total.clone()))
            .expect("register upstream_errors_total");
        registry
            .register(Box::new(pipeline_errors_total.clone()))
            .expect("register pipeline_errors_total");
        registry
            .register(Box::new(stage_oversize_total.clone()))
            .expect("register stage_oversize_total");
        registry
            .register(Box::new(overload_rejections_total.clone()))
            .expect("register overload_rejections_total");
        registry
            .register(Box::new(active_connections.clone()))
            .expect("register active_connections");

        Self {
            requests_total,
            blocked_total,
            redacted_total,
            response_redacted_total,
            response_redaction_skipped_total,
            pipeline_duration_seconds,
            stage_duration_seconds,
            request_duration_seconds,
            upstream_errors_total,
            pipeline_errors_total,
            stage_oversize_total,
            overload_rejections_total,
            active_connections,
            registry,
        }
    }

    /// Render all registered metrics in the Prometheus text exposition format.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding fails (extremely unlikely; only on
    /// internal `prometheus` crate invariant violations).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use guardrail_proxy::metrics::Metrics;
    ///
    /// let metrics = Metrics::new();
    /// metrics.requests_total.with_label_values(&["allow", "openai"]).inc();
    /// let output = metrics.render().unwrap();
    /// assert!(output.contains("guardrail_requests_total"));
    /// ```
    pub fn render(&self) -> Result<String, prometheus::Error> {
        let encoder = TextEncoder::new();
        let metric_families = self.registry.gather();
        let mut buf = Vec::new();
        encoder.encode(&metric_families, &mut buf)?;
        Ok(String::from_utf8(buf).expect("prometheus output is valid UTF-8"))
    }
}

impl Default for Metrics {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_metrics_render_contains_metric_names() {
        let metrics = Metrics::new();
        // Populate a few metrics so the encoder includes them in the output.
        metrics
            .requests_total
            .with_label_values(&["allow", "openai"])
            .inc();
        metrics.blocked_total.with_label_values(&["testcode"]).inc();
        metrics.redacted_total.inc();
        metrics.response_redacted_total.inc();
        metrics
            .response_redaction_skipped_total
            .with_label_values(&["unknown_encoding"])
            .inc();
        metrics.pipeline_duration_seconds.observe(0.001);
        metrics
            .stage_duration_seconds
            .with_label_values(&["regex_injection"])
            .observe(0.00003);
        metrics
            .request_duration_seconds
            .with_label_values(&["allow"])
            .observe(0.123);
        metrics
            .upstream_errors_total
            .with_label_values(&["timeout"])
            .inc();
        metrics.active_connections.inc();
        let output = metrics.render().unwrap();
        assert!(output.contains("guardrail_requests_total"));
        assert!(output.contains("guardrail_blocked_total"));
        assert!(output.contains("guardrail_redacted_total"));
        assert!(output.contains("guardrail_response_redacted_total"));
        assert!(output.contains(
            r#"guardrail_response_redaction_skipped_total{reason="unknown_encoding"} 1"#
        ));
        assert!(output.contains("guardrail_pipeline_duration_seconds"));
        assert!(output.contains("guardrail_stage_duration_seconds"));
        assert!(output.contains("guardrail_request_duration_seconds"));
        assert!(output.contains("guardrail_upstream_errors_total"));
        assert!(output.contains("guardrail_active_connections"));
    }

    #[test]
    fn test_counters_increment() {
        let metrics = Metrics::new();
        metrics
            .requests_total
            .with_label_values(&["allow", "openai"])
            .inc();
        metrics
            .requests_total
            .with_label_values(&["allow", "openai"])
            .inc();
        metrics.blocked_total.with_label_values(&["toxicity"]).inc();
        metrics.redacted_total.inc();
        metrics.response_redacted_total.inc();

        assert_eq!(
            metrics
                .requests_total
                .with_label_values(&["allow", "openai"])
                .get(),
            2
        );
        assert_eq!(
            metrics.blocked_total.with_label_values(&["toxicity"]).get(),
            1
        );
        assert_eq!(metrics.redacted_total.get(), 1);
        assert_eq!(metrics.response_redacted_total.get(), 1);
    }

    #[test]
    fn test_histogram_observe() {
        let metrics = Metrics::new();
        metrics.pipeline_duration_seconds.observe(0.0012);
        metrics
            .stage_duration_seconds
            .with_label_values(&["regex_injection"])
            .observe(0.00003);
        metrics
            .request_duration_seconds
            .with_label_values(&["allow"])
            .observe(0.123);

        let output = metrics.render().unwrap();
        assert!(output.contains("guardrail_pipeline_duration_seconds_bucket"));
        assert!(output.contains("stage=\"regex_injection\""));
        assert!(output.contains("guardrail_request_duration_seconds_bucket"));
        assert!(output.contains("decision=\"allow\""));
    }

    #[test]
    fn test_upstream_errors_and_active_connections() {
        let metrics = Metrics::new();
        metrics
            .upstream_errors_total
            .with_label_values(&["timeout"])
            .inc();
        metrics.active_connections.inc();
        metrics.active_connections.inc();
        metrics.active_connections.dec();

        assert_eq!(
            metrics
                .upstream_errors_total
                .with_label_values(&["timeout"])
                .get(),
            1
        );
        assert_eq!(metrics.active_connections.get(), 1.0);
    }
}