praxis-proxy-filter 0.5.6

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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Filter pipeline engine: the runtime representation of a listener's
//! filter processing.
//!
//! ## Module Layout
//!
//! | Module | Responsibility |
//! |---|---|
//! | [`build`] | `FilterPipeline` construction from config entries |
//! | [`build_branch`] | Recursive branch chain resolution |
//! | [`http`] | Request, response, and body execution loops |
//! | [`tcp`] | Connect/disconnect execution |
//! | [`evaluate`] | Branch condition checking and dispatch |
//! | [`branch`] | Runtime branch types ([`ResolvedBranch`], [`BranchOutcome`]) |
//! | [`filter`] | [`PipelineFilter`], the per-filter wrapper |
//! | [`body`] | Body chunk processing utilities |
//! | [`checks`] | Ordering validation (router before LB, etc.) |
//! | [`clusters`] | Cluster reference collection |
//! | [`extension`] | [`PipelineExtension`] trait for injecting per-request resources |
//!
//! At runtime, chains do not exist. All listener chains are
//! concatenated into a flat `Vec<PipelineFilter>`. Branch chains are
//! stored as nested `Vec<PipelineFilter>` inside each filter's
//! [`branches`] field.
//!
//! [`ResolvedBranch`]: branch::ResolvedBranch
//! [`BranchOutcome`]: branch::BranchOutcome
//! [`PipelineFilter`]: filter::PipelineFilter
//! [`branches`]: filter::PipelineFilter::branches

pub(crate) mod body;
pub(crate) mod branch;
mod build;
pub(crate) mod build_branch;
mod checks;
mod clusters;
pub(crate) mod evaluate;
mod extension;
pub(crate) mod filter;
mod http;
mod http_utils;
/// Public pipeline introspection snapshots for admin surfaces.
pub(crate) mod introspection;
/// Sub-request execution for iterative request routing.
pub(crate) mod subrequest;
mod tcp;
#[cfg(test)]
mod test_filters;

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic,
    clippy::field_reassign_with_default,
    clippy::type_complexity,
    clippy::too_many_lines,
    clippy::redundant_closure_for_method_calls,
    clippy::significant_drop_tightening,
    clippy::doc_markdown,
    reason = "tests"
)]
mod tests;

use std::sync::Arc;

pub use extension::PipelineExtension;
use praxis_core::{
    config::{ABSOLUTE_MAX_BODY_BYTES, FailureMode, InsecureOptions},
    health::HealthRegistry,
    id::IdGenerator,
    kv::KvStoreRegistry,
    time::TimeSource,
};
use tracing::{error, warn};

use self::filter::PipelineFilter;
use crate::{
    FilterError,
    body::{BodyCapabilities, BodyMode},
    builtins::http::payload_processing::compression_config::CompressionConfig,
    extensions::RequestExtensions,
};

// -----------------------------------------------------------------------------
// FilterPipeline
// -----------------------------------------------------------------------------

/// An ordered list of filters executed on every request.
///
/// ```
/// use praxis_filter::{FilterPipeline, FilterRegistry};
///
/// let registry = FilterRegistry::with_builtins();
/// let pipeline = FilterPipeline::build(&mut [], &registry).unwrap();
/// assert!(pipeline.is_empty());
/// ```
#[expect(
    clippy::struct_excessive_bools,
    reason = "independent server-injected runtime toggles, not a state machine"
)]
pub struct FilterPipeline {
    /// Pre-computed body processing capabilities for this pipeline.
    body_capabilities: BodyCapabilities,

    /// Compression configuration, if a compression filter is present.
    compression: Option<CompressionConfig>,

    /// Ordered list of filters with their conditions and branches.
    pub(crate) filters: Vec<PipelineFilter>,

    /// Whether per-filter duration metrics are recorded.
    record_filter_duration_metrics: bool,

    /// Compiled path templates for the `route` metric label.
    route_templates: Arc<praxis_core::config::RouteTemplates>,

    /// Shared health registry for endpoint health lookups.
    health_registry: Option<HealthRegistry>,

    /// Shared ID generator for request correlation IDs.
    id_generator: Arc<IdGenerator>,

    /// Named key-value stores for runtime mappings.
    kv_stores: Option<KvStoreRegistry>,

    /// Per-cluster session stores for sticky session affinity, preserved across reloads.
    session_stores: Option<Arc<crate::SessionStoreRegistry>>,

    /// Shared sub-request client for iterative sub-requests.
    subrequest_client: Option<praxis_core::subrequest::SubRequestClient>,

    /// Whether any filter, including branch filters, may select a streaming
    /// sub-request response.
    may_select_streaming_subrequest_response: bool,

    /// External pipeline extensions injected after construction.
    pipeline_extensions: Vec<Box<dyn PipelineExtension>>,

    /// Wall-clock time source for filters that need timestamps.
    time_source: Arc<dyn TimeSource>,

    /// Global request body ceiling, enforced by counting in Stream mode.
    request_body_ceiling: Option<usize>,

    /// Global response body ceiling, enforced by counting in Stream mode.
    response_body_ceiling: Option<usize>,

    /// Indices into `filters` of filters declaring request-body access.
    request_body_filter_indices: Vec<usize>,

    /// Indices into `filters` of filters declaring response-body access.
    response_body_filter_indices: Vec<usize>,

    /// Indices into `filters` of filters declaring selected-upstream
    /// request-body access.
    selected_upstream_request_body_filter_indices: Vec<usize>,

    /// Whether upstream hostnames may resolve to private or reserved IPs.
    ///
    /// Mirrors `insecure_options.allow_private_upstreams`; consumed by the
    /// upstream peer builders when they resolve a hostname.
    allow_private_upstreams: bool,
}

#[expect(
    clippy::multiple_inherent_impl,
    reason = "pipeline concerns are split across modules"
)]
impl FilterPipeline {
    /// Apply global body size ceilings.
    ///
    /// When no filter requires body access (mode is [`Stream`]),
    /// uses [`SizeLimit`] to enforce the ceiling without
    /// buffering. When a filter already requested
    /// [`StreamBuffer`], the ceiling tightens the existing limit.
    ///
    /// # Errors
    ///
    /// Returns [`FilterError`] if a [`StreamBuffer`] has no byte limit
    /// and `allow_unbounded` is `false`.
    ///
    /// [`Stream`]: BodyMode::Stream
    /// [`SizeLimit`]: BodyMode::SizeLimit
    /// [`StreamBuffer`]: BodyMode::StreamBuffer
    pub fn apply_body_limits(
        &mut self,
        max_request: Option<usize>,
        max_response: Option<usize>,
        allow_unbounded: bool,
    ) -> Result<(), FilterError> {
        self.apply_nested_body_limits(max_request, max_response, allow_unbounded)?;

        if let Some(ceiling) = max_request {
            self.body_capabilities.request_body_mode = clamp_body_mode(
                self.body_capabilities.request_body_mode,
                ceiling,
                self.body_capabilities.needs_request_body,
            );
            self.body_capabilities.needs_request_body = true;
        }

        if let Some(ceiling) = max_response {
            self.body_capabilities.response_body_mode = clamp_body_mode(
                self.body_capabilities.response_body_mode,
                ceiling,
                self.body_capabilities.needs_response_body,
            );
            self.body_capabilities.needs_response_body = true;
        }

        check_unbounded_stream_buffer(
            "request",
            &mut self.body_capabilities.request_body_mode,
            allow_unbounded,
        )?;
        check_unbounded_stream_buffer(
            "response",
            &mut self.body_capabilities.response_body_mode,
            allow_unbounded,
        )?;

        self.request_body_ceiling = max_request;
        self.response_body_ceiling = max_response;

        Ok(())
    }

    /// Apply the listener ceilings recursively to nested pipelines.
    fn apply_nested_body_limits(
        &mut self,
        max_request: Option<usize>,
        max_response: Option<usize>,
        allow_unbounded: bool,
    ) -> Result<(), FilterError> {
        let mut nested_error = None;
        self.visit_nested_pipelines(&mut |pipeline| {
            if nested_error.is_none()
                && let Err(error) = pipeline.apply_body_limits(max_request, max_response, allow_unbounded)
            {
                nested_error = Some(error);
            }
        });
        if let Some(error) = nested_error {
            return Err(error);
        }
        Ok(())
    }

    /// Global request body ceiling; `None` means unbounded was allowed.
    #[must_use]
    pub fn request_body_ceiling(&self) -> Option<usize> {
        self.request_body_ceiling
    }

    /// Global response body ceiling; `None` means unbounded was allowed.
    #[must_use]
    pub fn response_body_ceiling(&self) -> Option<usize> {
        self.response_body_ceiling
    }

    /// Pre-computed body processing capabilities for this pipeline.
    pub fn body_capabilities(&self) -> &BodyCapabilities {
        &self.body_capabilities
    }

    /// Reset request-body completion flags before replaying an upstream attempt.
    pub fn clear_request_body_done(&self, body_done_indices: &mut [bool]) {
        for &idx in &self.request_body_filter_indices {
            if let Some(done) = body_done_indices.get_mut(idx) {
                *done = false;
            }
        }
    }

    /// Whether any filter in the pipeline needs body access.
    pub fn needs_body_filters(&self) -> bool {
        self.body_capabilities.needs_request_body || self.body_capabilities.needs_response_body
    }

    /// Number of filters in the pipeline.
    pub fn len(&self) -> usize {
        self.filters.len()
    }

    /// Whether the pipeline has no filters.
    pub fn is_empty(&self) -> bool {
        self.filters.is_empty()
    }

    /// Whether any top-level filter has the given type name.
    ///
    /// ```
    /// use praxis_filter::{FilterPipeline, FilterRegistry};
    ///
    /// let registry = FilterRegistry::with_builtins();
    /// let pipeline = FilterPipeline::build(&mut [], &registry).unwrap();
    /// assert!(!pipeline.contains_filter("access_log"));
    /// ```
    pub fn contains_filter(&self, type_name: &str) -> bool {
        self.filters.iter().any(|pf| pf.filter.name() == type_name)
    }

    /// Names of filters in this pipeline whose protocol level is not
    /// supported by `listener_protocol`.
    ///
    /// A TCP listener silently skips HTTP-level filters at runtime, so an
    /// HTTP security filter placed on a TCP listener would never run. This
    /// surfaces that mismatch at build time.
    pub fn filters_unsupported_by(&self, listener_protocol: praxis_core::config::ProtocolKind) -> Vec<&'static str> {
        self.filters
            .iter()
            .filter(|pf| !listener_protocol.supports(pf.filter.protocol_level()))
            .map(|pf| pf.filter.name())
            .collect()
    }

    /// Names of filters in this pipeline that operate below the HTTP layer.
    ///
    /// Unlike [`filters_unsupported_by`], which honors a listener's protocol
    /// stack (an HTTP listener legitimately runs TCP-level filters at the
    /// connection layer), this reports filters that a *filtered sub-request*
    /// cannot run: that executor drives only the HTTP request phase, so any
    /// filter whose protocol level is not [`ProtocolKind::Http`] is never
    /// invoked. Binding one into an outbound chain is a silent runtime no-op;
    /// this surfaces it at build time.
    ///
    /// [`filters_unsupported_by`]: Self::filters_unsupported_by
    /// [`ProtocolKind::Http`]: praxis_core::config::ProtocolKind::Http
    pub fn non_http_filters(&self) -> Vec<&'static str> {
        let mut names = Vec::new();
        for_each_pipeline_filter(&self.filters, &mut |pf| {
            if pf.filter.protocol_level() != praxis_core::config::ProtocolKind::Http {
                names.push(pf.filter.name());
            }
        });
        names
    }

    /// Names of terminal filters in this pipeline, recursively including those
    /// nested inside branch sub-chains.
    ///
    /// A terminal filter short-circuits the request phase with a response and no
    /// upstream. The HTTP filtered sub-request executor forwards to a resolved
    /// upstream and cannot surface such a response, so a terminal filter bound
    /// into an outbound chain (at the top level or buried in a branch) must be
    /// rejected at build time rather than silently activate and drop its response
    /// at runtime.
    ///
    /// Detection is capability-based
    /// ([`HttpFilter::produces_terminal_response`]), not a match against the
    /// hard-coded builtin names in [`TERMINAL_FILTERS`], so a custom filter that
    /// can return a terminal action is caught even though its name is unknown to
    /// the builtin list.
    ///
    /// [`HttpFilter::produces_terminal_response`]: crate::HttpFilter::produces_terminal_response
    /// [`TERMINAL_FILTERS`]: praxis_core::config::TERMINAL_FILTERS
    pub fn terminal_filters(&self) -> Vec<&'static str> {
        let mut names = Vec::new();
        for_each_pipeline_filter(&self.filters, &mut |pf| {
            if let crate::any_filter::AnyFilter::Http(filter) = &pf.filter
                && filter.produces_terminal_response()
            {
                names.push(filter.name());
            }
        });
        names
    }

    /// Whether any filter of `type_name` has request conditions matching
    /// `request` (an unconditional entry always matches).
    ///
    /// Used by protocol-level fallbacks that emit on a filter's behalf, so
    /// an operator's `when`/`unless` scoping is honored outside the normal
    /// request phase.
    pub fn filter_request_conditions_match(&self, type_name: &str, request: &crate::Request) -> bool {
        self.filters
            .iter()
            .filter(|pf| pf.filter.name() == type_name)
            .any(|pf| crate::condition::should_execute(&pf.conditions, request))
    }

    /// Compression configuration, if a compression filter is present.
    pub fn compression_config(&self) -> Option<&CompressionConfig> {
        self.compression.as_ref()
    }

    /// Set the shared [`HealthRegistry`] for this pipeline.
    pub fn set_health_registry(&mut self, registry: HealthRegistry) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_health_registry(Arc::clone(&registry)));
        self.health_registry = Some(registry);
    }

    /// Enable or disable recording of per-filter duration metrics.
    pub fn set_record_filter_duration_metrics(&mut self, enabled: bool) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_record_filter_duration_metrics(enabled));
        self.record_filter_duration_metrics = enabled;
    }

    /// Whether per-filter duration metrics are recorded.
    pub fn records_filter_duration_metrics(&self) -> bool {
        self.record_filter_duration_metrics
    }

    /// Set the compiled path templates used for the `route` metric label.
    pub fn set_route_templates(&mut self, templates: Arc<praxis_core::config::RouteTemplates>) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_route_templates(Arc::clone(&templates)));
        self.route_templates = templates;
    }

    /// The compiled path templates for the `route` metric label.
    pub fn route_templates(&self) -> &praxis_core::config::RouteTemplates {
        &self.route_templates
    }

    /// The shared health registry, if set.
    pub fn health_registry(&self) -> Option<&HealthRegistry> {
        self.health_registry.as_ref()
    }

    /// The shared request ID generator.
    pub fn id_generator(&self) -> &IdGenerator {
        &self.id_generator
    }

    /// Override the [`IdGenerator`] for this pipeline.
    pub fn set_id_generator(&mut self, generator: Arc<IdGenerator>) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_id_generator(Arc::clone(&generator)));
        self.id_generator = generator;
    }

    /// The shared KV store registry, if set.
    pub fn kv_stores(&self) -> Option<&KvStoreRegistry> {
        self.kv_stores.as_ref()
    }

    /// Set the shared [`KvStoreRegistry`] for this pipeline.
    pub fn set_kv_stores(&mut self, stores: KvStoreRegistry) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_kv_stores(stores.clone()));
        self.kv_stores = Some(stores);
    }

    /// The shared session store registry, if set.
    pub fn session_stores(&self) -> Option<&Arc<crate::SessionStoreRegistry>> {
        self.session_stores.as_ref()
    }

    /// Set the shared [`crate::SessionStoreRegistry`] for this pipeline.
    pub fn set_session_stores(&mut self, stores: Arc<crate::SessionStoreRegistry>) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_session_stores(Arc::clone(&stores)));
        self.session_stores = Some(stores);
    }

    /// The shared sub-request client, if set.
    pub fn subrequest_client(&self) -> Option<&praxis_core::subrequest::SubRequestClient> {
        self.subrequest_client.as_ref()
    }

    /// Whether any filter in this pipeline or its branches may select a
    /// streaming sub-request response.
    pub fn may_select_streaming_subrequest_response(&self) -> bool {
        self.may_select_streaming_subrequest_response
    }

    /// Set the shared [`SubRequestClient`] for this pipeline.
    ///
    /// [`SubRequestClient`]: praxis_core::subrequest::SubRequestClient
    pub fn set_subrequest_client(&mut self, client: praxis_core::subrequest::SubRequestClient) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_subrequest_client(client.clone()));
        self.subrequest_client = Some(client);
    }

    /// Register an external pipeline extension.
    ///
    /// Extensions are called once per request via
    /// [`prepare_extensions`] to inject pipeline-scoped resources
    /// into the per-request [`RequestExtensions`] container.
    ///
    /// [`prepare_extensions`]: FilterPipeline::prepare_extensions
    /// [`RequestExtensions`]: crate::RequestExtensions
    pub fn add_pipeline_extension(&mut self, ext: Box<dyn PipelineExtension>) {
        self.pipeline_extensions.push(ext);
    }

    /// Inject pipeline-level resources into per-request extensions.
    ///
    /// Called by the protocol adapter when building each request's
    /// filter context. Delegates to each registered
    /// [`PipelineExtension`].
    pub fn prepare_extensions(&self, extensions: &mut RequestExtensions) {
        for ext in &self.pipeline_extensions {
            ext.prepare(extensions);
        }
    }

    /// The wall-clock time source.
    pub fn time_source(&self) -> &dyn TimeSource {
        &*self.time_source
    }

    /// Override the [`TimeSource`] for this pipeline.
    pub fn set_time_source(&mut self, source: Arc<dyn TimeSource>) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_time_source(Arc::clone(&source)));
        self.time_source = source;
    }

    /// Filesystem paths the filters in this pipeline read configuration from,
    /// beyond the main Praxis config.
    ///
    /// Used by the config watcher to decide which files should trigger a reload.
    /// Without this, a filter that loads an external document never picks up edits
    /// to it, because the reload gate only ever sees the main config's bytes.
    ///
    /// Walks branch sub-chains recursively, so a document referenced solely from
    /// a filter inside a branch is observed too.
    pub fn referenced_files(&self) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        for_each_pipeline_filter(&self.filters, &mut |pf| {
            if let crate::any_filter::AnyFilter::Http(f) = &pf.filter {
                files.extend(f.referenced_files());
            }
        });
        files
    }

    /// Whether upstream hostnames are allowed to resolve to private or
    /// reserved IP addresses.
    ///
    /// Mirrors `insecure_options.allow_private_upstreams`. Defaults to
    /// `false`, so a pipeline that was never configured fails closed.
    pub fn allow_private_upstreams(&self) -> bool {
        self.allow_private_upstreams
    }

    /// Set the runtime private-upstream override, including for nested pipelines.
    ///
    /// Called once per (re)configuration from
    /// `insecure_options.allow_private_upstreams`, so a hot reload that
    /// flips the flag takes effect with the swapped-in pipeline.
    pub fn set_allow_private_upstreams(&mut self, allow: bool) {
        self.visit_nested_pipelines(&mut |pipeline| pipeline.set_allow_private_upstreams(allow));
        self.allow_private_upstreams = allow;
    }

    /// Apply [`InsecureOptions`] to all filters in the pipeline.
    ///
    /// Delegates to each filter's [`apply_insecure_options`] method, recursing
    /// into branch sub-chains so a filter buried in a branch honors the override
    /// too. Filters that support insecure overrides (e.g. CSRF log-only mode)
    /// handle the relevant flags; others ignore the call.
    ///
    /// [`apply_insecure_options`]: crate::HttpFilter::apply_insecure_options
    /// [`InsecureOptions`]: praxis_core::config::InsecureOptions
    pub fn apply_insecure_options(&self, options: &InsecureOptions) {
        for_each_pipeline_filter(&self.filters, &mut |pf| {
            if let crate::any_filter::AnyFilter::Http(f) = &pf.filter {
                f.apply_insecure_options(options);
            }
        });
    }

    /// Apply a mutation to every pipeline directly embedded by a filter,
    /// including filters nested inside branch sub-chains.
    fn visit_nested_pipelines(&mut self, visitor: &mut dyn FnMut(&mut FilterPipeline)) {
        visit_branch_nested_pipelines(&mut self.filters, visitor);
    }
}

/// Visit every filter in `filters` and, recursively, every filter nested inside
/// their branch sub-chains.
///
/// The shared read-only walk behind the pipeline-wide scans (non-HTTP filter
/// detection, terminal-filter detection, referenced-file discovery, insecure
/// option application) so a filter buried in a branch is treated exactly like a
/// top-level one rather than silently skipped.
fn for_each_pipeline_filter(filters: &[PipelineFilter], visit: &mut dyn FnMut(&PipelineFilter)) {
    for pf in filters {
        visit(pf);
        for branch in &pf.branches {
            for_each_pipeline_filter(&branch.filters, visit);
        }
    }
}

/// Invoke each filter's [`visit_nested_pipelines`], descending recursively into
/// branch sub-chains so pipelines embedded by branch-contained filters (for
/// example an outbound chain bound by a callout placed inside a branch) receive
/// the same mutation as top-level ones.
///
/// [`visit_nested_pipelines`]: crate::HttpFilter::visit_nested_pipelines
fn visit_branch_nested_pipelines(filters: &mut [PipelineFilter], visitor: &mut dyn FnMut(&mut FilterPipeline)) {
    for pf in filters {
        if let crate::any_filter::AnyFilter::Http(filter) = &mut pf.filter {
            filter.visit_nested_pipelines(visitor);
        }
        for branch in &mut pf.branches {
            visit_branch_nested_pipelines(&mut branch.filters, visitor);
        }
    }
}

// -----------------------------------------------------------------------------
// Body Limit Utilities
// -----------------------------------------------------------------------------

/// Tighten a body mode's size limit to the given ceiling.
/// When `filter_declared` is true a filter explicitly chose Stream
/// mode; preserve it so streaming filters keep working. When false
/// the mode is the default (no filter needs body); convert to
/// `SizeLimit` so the body limit is enforced by buffering.
fn clamp_body_mode(mode: BodyMode, ceiling: usize, filter_declared: bool) -> BodyMode {
    match mode {
        BodyMode::StreamBuffer { max_bytes } => BodyMode::StreamBuffer {
            max_bytes: Some(max_bytes.map_or(ceiling, |m| m.min(ceiling))),
        },
        BodyMode::SizeLimit { max_bytes } => BodyMode::SizeLimit {
            max_bytes: max_bytes.min(ceiling),
        },
        BodyMode::Stream if filter_declared => BodyMode::Stream,
        BodyMode::Stream => BodyMode::SizeLimit { max_bytes: ceiling },
    }
}

/// Reject or clamp unbounded [`StreamBuffer`] body modes.
///
/// When `allow_unbounded` is `true`, the mode is clamped to
/// [`ABSOLUTE_MAX_BODY_BYTES`] and a warning is emitted.
///
/// # Errors
///
/// Returns [`FilterError`] when the body mode is unbounded
/// and `allow_unbounded` is `false`.
///
/// [`StreamBuffer`]: BodyMode::StreamBuffer
/// [`ABSOLUTE_MAX_BODY_BYTES`]: praxis_core::config::ABSOLUTE_MAX_BODY_BYTES
fn check_unbounded_stream_buffer(
    direction: &str,
    mode: &mut BodyMode,
    allow_unbounded: bool,
) -> Result<(), FilterError> {
    if let BodyMode::StreamBuffer { max_bytes: max @ None } = mode {
        if allow_unbounded {
            warn!(
                direction = direction,
                ceiling = ABSOLUTE_MAX_BODY_BYTES,
                "StreamBuffer body mode has no per-filter size limit; \
                 clamped to absolute ceiling ({} MiB)",
                ABSOLUTE_MAX_BODY_BYTES / 1_048_576
            );
            *max = Some(ABSOLUTE_MAX_BODY_BYTES);
        } else {
            return Err(format!(
                "StreamBuffer {direction} body mode has no size limit; \
                 set max_{direction}_body_bytes or set \
                 insecure_options.allow_unbounded_body: true to allow"
            )
            .into());
        }
    }
    Ok(())
}

// -----------------------------------------------------------------------------
// Failure Mode
// -----------------------------------------------------------------------------

/// Check failure mode and either swallow or propagate a filter error.
///
/// When `failure_mode` is [`FailureMode::Open`], the error is logged as a
/// warning and `Ok(())` is returned so the caller can continue.
pub(crate) fn check_failure_mode(
    filter_name: &str,
    error: FilterError,
    phase: &str,
    failure_mode: FailureMode,
) -> Result<(), FilterError> {
    match failure_mode {
        FailureMode::Open => {
            warn!(
                filter = filter_name,
                error = %error,
                phase,
                failure_mode = "open",
                "filter error, continuing"
            );
            Ok(())
        },
        FailureMode::Closed => {
            error!(
                filter = filter_name,
                error = %error,
                phase,
                failure_mode = "closed",
                "filter error, aborting request"
            );
            Err(error)
        },
    }
}