praxis-proxy-filter 0.5.3

Filter pipeline engine and built-in filters for Praxis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// SPDX-License-Identifier: MIT
// Copyright (c) 2024 Praxis Contributors

//! Filter return types: continue, reject, or return a terminal response.

use std::fmt;

use async_trait::async_trait;
use bytes::Bytes;

use crate::FilterError;

// -----------------------------------------------------------------------------
// Streaming terminal response
// -----------------------------------------------------------------------------

/// Opaque, pull-based body for a terminal streaming response.
///
/// Implementations own any inner transport and response-filter continuation
/// state. The protocol layer pulls at most one chunk at a time and does not
/// read the next chunk until the previous downstream write completes.
#[async_trait]
pub trait StreamingResponseBody: Send + 'static {
    /// Pull the next filtered body chunk.
    ///
    /// `Ok(None)` means clean completion. Implementations must run their
    /// owned completion lifecycle exactly once before returning it.
    async fn next_chunk(&mut self) -> Result<Option<Bytes>, FilterError>;

    /// Suppress the unread body for HEAD, 204, or 304 delivery.
    ///
    /// Implementations cancel their underlying source while still running
    /// any owned clean-suppression lifecycle exactly once.
    async fn suppress(&mut self) -> Result<(), FilterError>;

    /// Abort the source and release all owned resources.
    ///
    /// This operation must be idempotent.
    async fn cancel(&mut self);
}

/// A terminal response whose body is delivered incrementally.
#[must_use]
pub struct StreamingTerminalResponse {
    /// HTTP status code.
    pub status: u16,

    /// Response headers available before downstream commitment.
    pub headers: http::HeaderMap,

    /// Opaque pull-based body and its owned continuation state.
    pub body: Box<dyn StreamingResponseBody>,
}

impl StreamingTerminalResponse {
    /// Create a streaming terminal response.
    ///
    /// # Panics
    ///
    /// Panics if `code` is outside 200..=599. Informational responses cannot
    /// terminate a request.
    pub fn new(code: u16, body: Box<dyn StreamingResponseBody>) -> Self {
        assert!(
            (200..=599).contains(&code),
            "streaming terminal status must be 200..=599, got {code}"
        );
        Self {
            status: code,
            headers: http::HeaderMap::new(),
            body,
        }
    }

    /// Set the response headers.
    pub fn with_headers(mut self, headers: http::HeaderMap) -> Self {
        self.headers = headers;
        self
    }
}

impl fmt::Debug for StreamingTerminalResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StreamingTerminalResponse")
            .field("status", &self.status)
            .field("headers", &self.headers)
            .field("body", &"<opaque streaming body>")
            .finish()
    }
}

// -----------------------------------------------------------------------------
// FilterAction
// -----------------------------------------------------------------------------

/// Result of a filter's request or response processing.
///
/// ```
/// use praxis_filter::{FilterAction, Rejection, TerminalResponse};
///
/// let action = FilterAction::Continue;
/// assert!(matches!(action, FilterAction::Continue));
///
/// let reject = FilterAction::Reject(Rejection::status(403));
/// assert!(matches!(reject, FilterAction::Reject(r) if r.status == 403));
///
/// let terminal = FilterAction::TerminalResponse(Box::new(TerminalResponse::new(200)));
/// assert!(matches!(terminal, FilterAction::TerminalResponse(r) if r.status == 200));
///
/// let release = FilterAction::Release;
/// assert!(matches!(release, FilterAction::Release));
///
/// let body_done = FilterAction::BodyDone;
/// assert!(matches!(body_done, FilterAction::BodyDone));
/// ```
#[derive(Debug)]
#[must_use]
pub enum FilterAction {
    /// Continue to the next filter in the pipeline.
    Continue,

    /// Stop processing and respond with the given rejection.
    Reject(Rejection),

    /// Return a complete response to the client, running
    /// response-phase filters for all filters that already
    /// executed during the request phase.
    ///
    /// Unlike [`Reject`], this preserves downstream keepalive
    /// and is intended for filters that produce a real response
    /// (e.g. the iterative request router returning an upstream
    /// response). Response-header and response-body filters
    /// execute before the response is sent, so preceding
    /// observability filters see the terminal response.
    ///
    /// Only valid in request-phase filters.
    ///
    /// [`Reject`]: FilterAction::Reject
    TerminalResponse(Box<TerminalResponse>),

    /// Return a streaming response to the client.
    ///
    /// Response-header filters run before commitment. After commitment, the
    /// protocol pulls one chunk, runs response-body filters, awaits the
    /// downstream write, and only then requests the next chunk. Source or
    /// filter failures after commitment terminate the downstream stream and
    /// cannot produce a replacement response.
    ///
    /// Only valid in request-phase filters.
    StreamingTerminalResponse(Box<StreamingTerminalResponse>),

    /// Signal that accumulated body data ([`StreamBuffer`] mode)
    /// should be forwarded to upstream. After release, remaining
    /// chunks flow through in stream mode.
    ///
    /// In non-StreamBuffer contexts (including the TCP pipeline),
    /// behaves as [`Continue`].
    ///
    /// [`StreamBuffer`]: crate::BodyMode::StreamBuffer
    /// [`Continue`]: FilterAction::Continue
    Release,

    /// Skip this filter for remaining body chunks.
    ///
    /// The filter has completed its body inspection and does
    /// not need to see further chunks. The pipeline continues
    /// calling other body filters; only this filter is skipped.
    ///
    /// In non-body contexts (request and response phases),
    /// behaves as [`Continue`].
    ///
    /// [`Continue`]: FilterAction::Continue
    BodyDone,
}

// -----------------------------------------------------------------------------
// Rejection
// -----------------------------------------------------------------------------

/// A filter rejection response.
///
/// ```
/// use praxis_filter::Rejection;
///
/// // Simple status-only rejection:
/// let r = Rejection::status(403);
/// assert_eq!(r.status, 403);
/// assert!(r.headers.is_empty());
/// assert!(r.body.is_none());
///
/// // Rich rejection with headers and body:
/// let r = Rejection::status(429)
///     .with_header("Retry-After", "60")
///     .with_body(b"rate limit exceeded".as_slice());
/// assert_eq!(r.status, 429);
/// assert_eq!(r.headers.len(), 1);
/// assert!(r.body.is_some());
/// ```
#[derive(Debug)]
#[must_use]
pub struct Rejection {
    /// Response body.
    pub body: Option<Bytes>,

    /// Response headers.
    pub headers: Vec<(String, String)>,

    /// Byte-preserving response headers.
    ///
    /// Used when proxying an existing response whose values may contain
    /// opaque bytes that are valid in HTTP but are not UTF-8.
    pub header_map: Option<Box<http::HeaderMap>>,

    /// Keep the downstream connection reusable after this response.
    ///
    /// Short-circuit rejections default to closing because the request body
    /// may be unread. Filters that have consumed the complete body and are
    /// returning a normal terminal response may opt into reuse.
    pub preserve_keepalive: bool,

    /// HTTP status code.
    pub status: u16,
}

impl Rejection {
    /// Create a rejection with the given status code.
    ///
    /// # Panics
    ///
    /// Panics if `code` is outside the valid HTTP status range
    /// (100..=599).
    pub fn status(code: u16) -> Self {
        assert!(
            (100..=599).contains(&code),
            "HTTP status code must be 100..=599, got {code}"
        );
        Self {
            status: code,
            headers: Vec::new(),
            header_map: None,
            body: None,
            preserve_keepalive: false,
        }
    }

    /// Set the body of the rejection response.
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Add a header to the rejection response.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Preserve downstream keepalive after sending this complete response.
    pub fn preserving_keepalive(mut self) -> Self {
        self.preserve_keepalive = true;
        self
    }
}

// -----------------------------------------------------------------------------
// TerminalResponse
// -----------------------------------------------------------------------------

/// A complete response produced by a request-phase filter.
///
/// Unlike [`Rejection`], a terminal response preserves downstream
/// keepalive and triggers the response-header and response-body
/// filter lifecycle for filters that already executed during the
/// request phase.
///
/// ```
/// use praxis_filter::TerminalResponse;
///
/// let r = TerminalResponse::new(200)
///     .with_headers(http::HeaderMap::new())
///     .with_body(b"ok".as_slice());
/// assert_eq!(r.status, 200);
/// assert!(r.body.is_some());
/// ```
#[derive(Debug)]
#[must_use]
pub struct TerminalResponse {
    /// HTTP status code.
    pub status: u16,

    /// Response headers.
    pub headers: http::HeaderMap,

    /// Buffered response body.
    pub body: Option<Bytes>,
}

impl TerminalResponse {
    /// Create a terminal response with the given status code.
    ///
    /// # Panics
    ///
    /// Panics if `code` is outside the valid terminal status range
    /// (200..=599). Informational (1xx) statuses cannot be terminal
    /// because they require a subsequent final response.
    pub fn new(code: u16) -> Self {
        assert!(
            (200..=599).contains(&code),
            "terminal status must be 200..=599 (1xx is informational, not final), got {code}"
        );
        Self {
            status: code,
            headers: http::HeaderMap::new(),
            body: None,
        }
    }

    /// Set the headers of the terminal response.
    pub fn with_headers(mut self, headers: http::HeaderMap) -> Self {
        self.headers = headers;
        self
    }

    /// Set the body of the terminal response.
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = Some(body.into());
        self
    }
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic,
    reason = "tests"
)]
mod tests {
    use super::*;

    #[test]
    fn rejection_status_defaults() {
        let r = Rejection::status(404);
        assert_eq!(r.status, 404, "status should match constructor arg");
        assert!(r.headers.is_empty(), "headers should default to empty");
        assert!(
            r.header_map.is_none(),
            "byte-preserving headers should default to empty"
        );
        assert!(r.body.is_none(), "body should default to None");
        assert!(!r.preserve_keepalive, "rejections should close by default");
    }

    #[test]
    fn rejection_status_boundary_100() {
        let r = Rejection::status(100);
        assert_eq!(r.status, 100, "100 is a valid HTTP status");
    }

    #[test]
    fn rejection_status_boundary_599() {
        let r = Rejection::status(599);
        assert_eq!(r.status, 599, "599 is a valid HTTP status");
    }

    #[test]
    #[should_panic(expected = "HTTP status code must be 100..=599")]
    fn rejection_status_zero_panics() {
        let _r = Rejection::status(0);
    }

    #[test]
    #[should_panic(expected = "HTTP status code must be 100..=599")]
    fn rejection_status_600_panics() {
        let _r = Rejection::status(600);
    }

    #[test]
    fn rejection_with_header_appends() {
        let r = Rejection::status(403)
            .with_header("X-Reason", "forbidden")
            .with_header("X-Request-Id", "abc");
        assert_eq!(r.headers.len(), 2, "should have two appended headers");
        assert_eq!(
            r.headers[0],
            ("X-Reason".into(), "forbidden".into()),
            "first header should match"
        );
        assert_eq!(
            r.headers[1],
            ("X-Request-Id".into(), "abc".into()),
            "second header should match"
        );
    }

    #[test]
    fn preserving_keepalive_is_explicit() {
        let rejection = Rejection::status(200).preserving_keepalive();
        assert!(rejection.preserve_keepalive);
    }

    #[test]
    fn rejection_with_body_sets_bytes() {
        let r = Rejection::status(400).with_body(b"bad request".as_slice());
        assert_eq!(
            r.body.unwrap(),
            Bytes::from_static(b"bad request"),
            "body should contain provided bytes"
        );
    }

    #[test]
    fn filter_action_continue_variant() {
        assert!(
            matches!(FilterAction::Continue, FilterAction::Continue),
            "Continue should match Continue"
        );
    }

    #[test]
    fn filter_action_reject_carries_rejection() {
        let action = FilterAction::Reject(Rejection::status(503));
        assert!(
            matches!(action, FilterAction::Reject(r) if r.status == 503),
            "Reject should carry rejection with status 503"
        );
    }

    #[test]
    fn terminal_response_200() {
        let r = TerminalResponse::new(200);
        assert_eq!(r.status, 200);
    }

    #[test]
    fn terminal_response_599() {
        let r = TerminalResponse::new(599);
        assert_eq!(r.status, 599);
    }

    #[test]
    #[should_panic(expected = "terminal status must be 200..=599")]
    fn terminal_response_1xx_panics() {
        let _r = TerminalResponse::new(100);
    }

    #[test]
    #[should_panic(expected = "terminal status must be 200..=599")]
    fn terminal_response_199_panics() {
        let _r = TerminalResponse::new(199);
    }

    #[test]
    fn filter_action_release_variant() {
        assert!(
            matches!(FilterAction::Release, FilterAction::Release),
            "Release should match Release"
        );
    }

    #[test]
    fn filter_action_body_done_variant() {
        assert!(
            matches!(FilterAction::BodyDone, FilterAction::BodyDone),
            "BodyDone should match BodyDone"
        );
    }

    // ---------------------------------------------------------------------------
    // Test Utilities for Streaming Types
    // ---------------------------------------------------------------------------

    struct NullStreamBody;

    #[async_trait]
    impl StreamingResponseBody for NullStreamBody {
        async fn next_chunk(&mut self) -> Result<Option<Bytes>, FilterError> {
            Ok(None)
        }

        async fn suppress(&mut self) -> Result<(), FilterError> {
            Ok(())
        }

        async fn cancel(&mut self) {}
    }

    struct SingleChunkStreamBody(Option<Bytes>);

    #[async_trait]
    impl StreamingResponseBody for SingleChunkStreamBody {
        async fn next_chunk(&mut self) -> Result<Option<Bytes>, FilterError> {
            Ok(self.0.take())
        }

        async fn suppress(&mut self) -> Result<(), FilterError> {
            self.0 = None;
            Ok(())
        }

        async fn cancel(&mut self) {
            self.0 = None;
        }
    }

    // ---------------------------------------------------------------------------
    // Streaming Terminal Response Tests
    // ---------------------------------------------------------------------------

    #[test]
    fn streaming_terminal_response_200() {
        let r = StreamingTerminalResponse::new(200, Box::new(NullStreamBody));
        assert_eq!(r.status, 200, "status should be 200");
    }

    #[test]
    fn streaming_terminal_response_599() {
        let r = StreamingTerminalResponse::new(599, Box::new(NullStreamBody));
        assert_eq!(r.status, 599, "599 is the upper boundary");
    }

    #[test]
    #[should_panic(expected = "streaming terminal status must be 200..=599")]
    fn streaming_terminal_response_1xx_panics() {
        let _r = StreamingTerminalResponse::new(100, Box::new(NullStreamBody));
    }

    #[test]
    #[should_panic(expected = "streaming terminal status must be 200..=599")]
    fn streaming_terminal_response_199_panics() {
        let _r = StreamingTerminalResponse::new(199, Box::new(NullStreamBody));
    }

    #[test]
    fn streaming_terminal_response_with_headers() {
        let mut headers = http::HeaderMap::new();
        headers.insert("x-custom", "value".parse().unwrap());
        let r = StreamingTerminalResponse::new(200, Box::new(NullStreamBody)).with_headers(headers);
        assert_eq!(
            r.headers.get("x-custom").unwrap(),
            "value",
            "custom header should be set"
        );
    }

    #[tokio::test]
    async fn null_stream_body_returns_none() {
        let mut body = NullStreamBody;
        let chunk = body.next_chunk().await.unwrap();
        assert!(chunk.is_none(), "NullStreamBody should return None");
    }

    #[tokio::test]
    async fn single_chunk_stream_body_yields_then_none() {
        let mut body = SingleChunkStreamBody(Some(Bytes::from_static(b"hello")));
        let first = body.next_chunk().await.unwrap();
        assert_eq!(
            first.unwrap(),
            Bytes::from_static(b"hello"),
            "first chunk should contain the payload"
        );
        let second = body.next_chunk().await.unwrap();
        assert!(second.is_none(), "second call should return None");
    }

    #[test]
    fn streaming_terminal_debug_format() {
        let r = StreamingTerminalResponse::new(200, Box::new(NullStreamBody));
        let debug = format!("{r:?}");
        assert!(
            debug.contains("StreamingTerminalResponse"),
            "debug should contain type name"
        );
        assert!(debug.contains("200"), "debug should contain status code");
        assert!(debug.contains("opaque"), "debug should indicate opaque body");
    }

    #[test]
    fn filter_action_streaming_terminal_variant() {
        let action = FilterAction::StreamingTerminalResponse(Box::new(StreamingTerminalResponse::new(
            200,
            Box::new(NullStreamBody),
        )));
        assert!(
            matches!(action, FilterAction::StreamingTerminalResponse(_)),
            "should match StreamingTerminalResponse variant"
        );
    }
}