Skip to main content

pingora_proxy/
proxy_trait.rs

1// Copyright 2026 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::*;
16use pingora_cache::{
17    key::HashBinary,
18    CacheKey, CacheMeta, ForcedFreshness, HitHandler,
19    RespCacheable::{self, *},
20};
21use proxy_cache::range_filter::{self};
22use std::any::Any;
23use std::time::Duration;
24
25/// Context for proxy warning logs that can be suppressed by
26/// [`ProxyHttp::suppress_proxy_warn_log`].
27///
28/// These contexts are distinct from final proxy errors, which are handled by
29/// [`ProxyHttp::suppress_error_log`].
30///
31/// Experimental: this API may change or be removed until indicated otherwise.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33#[non_exhaustive]
34pub enum ProxyWarnLogContext {
35    /// A proxy upstream attempt failed with a retryable error.
36    UpstreamRetry,
37    /// A downstream error was ignored so cache fill could continue.
38    DownstreamCache,
39}
40
41/// The interface to control the HTTP proxy
42///
43/// The methods in [ProxyHttp] are filters/callbacks which will be performed on all requests at their
44/// particular stage (if applicable).
45///
46/// If any of the filters returns [Result::Err], the request will fail, and the error will be logged.
47#[cfg_attr(not(doc_async_trait), async_trait)]
48pub trait ProxyHttp {
49    /// The per request object to share state across the different filters
50    type CTX;
51
52    /// Define how the `ctx` should be created.
53    fn new_ctx(&self) -> Self::CTX;
54
55    /// Define where the proxy should send the request to.
56    ///
57    /// The returned [HttpPeer] contains the information regarding where and how this request should
58    /// be forwarded to.
59    async fn upstream_peer(
60        &self,
61        session: &mut Session,
62        ctx: &mut Self::CTX,
63    ) -> Result<Box<HttpPeer>>;
64
65    /// Set up downstream modules.
66    ///
67    /// In this phase, users can add or configure [HttpModules] before the server starts up.
68    ///
69    /// In the default implementation of this method, [ResponseCompressionBuilder] is added
70    /// and disabled.
71    fn init_downstream_modules(&self, modules: &mut HttpModules) {
72        // Add disabled downstream compression module by default
73        modules.add_module(ResponseCompressionBuilder::enable(0));
74    }
75
76    /// Set up upstream modules.
77    ///
78    /// In this phase, users can add [HttpModules] that will process upstream responses
79    /// **before** `upstream_compression`. This is the correct place to register modules
80    /// that need to observe the raw (pre-compression) upstream response body, such as
81    /// a dictionary store for shared dictionary compression.
82    ///
83    /// Upstream modules are ordered by [`HttpModuleBuilder::order()`]: higher values run
84    /// first. They are invoked on each upstream response task (header, body, trailers)
85    /// before `upstream_compression` processes the task.
86    ///
87    /// By default this method does nothing.
88    ///
89    /// This method requires the `upstream_modules` feature to be enabled.
90    #[cfg(feature = "upstream_modules")]
91    fn init_upstream_modules(&self, _modules: &mut HttpModules) {}
92
93    /// Handle the incoming request.
94    ///
95    /// In this phase, users can parse, validate, rate limit, perform access control and/or
96    /// return a response for this request.
97    ///
98    /// If the user already sent a response to this request, an `Ok(true)` should be returned so that
99    /// the proxy would exit. The proxy continues to the next phases when `Ok(false)` is returned.
100    ///
101    /// By default this filter does nothing and returns `Ok(false)`.
102    async fn request_filter(&self, _session: &mut Session, _ctx: &mut Self::CTX) -> Result<bool>
103    where
104        Self::CTX: Send + Sync,
105    {
106        Ok(false)
107    }
108
109    /// Handle the incoming request before any downstream module is executed.
110    ///
111    /// This function is similar to [Self::request_filter()] but executes before any other logic,
112    /// including downstream module logic. The main purpose of this function is to provide finer
113    /// grained control of the behavior of the modules.
114    ///
115    /// Note that because this function is executed before any module that might provide access
116    /// control or rate limiting, logic should stay in request_filter() if it can in order to be
117    /// protected by said modules.
118    async fn early_request_filter(&self, _session: &mut Session, _ctx: &mut Self::CTX) -> Result<()>
119    where
120        Self::CTX: Send + Sync,
121    {
122        Ok(())
123    }
124
125    /// Returns whether this session is allowed to spawn subrequests.
126    ///
127    /// This function is checked after [Self::early_request_filter] to allow that filter to configure
128    /// this if required. This will also run for subrequests themselves, which may allowed to spawn
129    /// their own subrequests.
130    ///
131    /// Note that this doesn't prevent subrequests from being spawned based on the session by proxy
132    /// core functionality, e.g. background cache revalidation requires spawning subrequests.
133    fn allow_spawning_subrequest(&self, _session: &Session, _ctx: &Self::CTX) -> bool
134    where
135        Self::CTX: Send + Sync,
136    {
137        false
138    }
139
140    /// Handle the incoming request body.
141    ///
142    /// This function will be called every time a piece of request body is received. The `body` is
143    /// **not the entire request body**.
144    ///
145    /// The async nature of this function allows to throttle the upload speed and/or executing
146    /// heavy computation logic such as WAF rules on offloaded threads without blocking the threads
147    /// who process the requests themselves.
148    async fn request_body_filter(
149        &self,
150        _session: &mut Session,
151        _body: &mut Option<Bytes>,
152        _end_of_stream: bool,
153        _ctx: &mut Self::CTX,
154    ) -> Result<()>
155    where
156        Self::CTX: Send + Sync,
157    {
158        Ok(())
159    }
160
161    /// This filter decides if the request is cacheable and what cache backend to use
162    ///
163    /// The caller can interact with `Session.cache` to enable caching.
164    ///
165    /// By default this filter does nothing which effectively disables caching.
166    // Ideally only session.cache should be modified, TODO: reflect that in this interface
167    fn request_cache_filter(&self, _session: &mut Session, _ctx: &mut Self::CTX) -> Result<()>
168    where
169        Self::CTX: Send + Sync,
170    {
171        Ok(())
172    }
173
174    /// This callback generates the cache key.
175    ///
176    /// This callback is called only when cache is enabled for this request.
177    ///
178    /// There is no sensible default cache key for all proxy applications. The
179    /// correct key depends on which request properties affect upstream responses
180    /// (e.g. `Vary` headers, custom request filters that modify the origin host).
181    /// Getting this wrong leads to cache poisoning.
182    ///
183    /// See `pingora-proxy/tests/utils/server_utils.rs` for a minimal (not
184    /// production-ready) reference implementation.
185    ///
186    /// # Panics
187    ///
188    /// The default implementation panics. You **must** override this method when
189    /// caching is enabled.
190    fn cache_key_callback(&self, _session: &Session, _ctx: &mut Self::CTX) -> Result<CacheKey> {
191        unimplemented!("cache_key_callback must be implemented when caching is enabled")
192    }
193
194    /// This callback is invoked when a cacheable response is ready to be admitted to cache.
195    fn cache_miss(&self, session: &mut Session, _ctx: &mut Self::CTX) {
196        session.cache.cache_miss();
197    }
198
199    /// This filter is called after a successful cache lookup and before the
200    /// cache asset is ready to be used.
201    ///
202    /// This filter allows the user to log or force invalidate the asset, or
203    /// to adjust the body reader associated with the cache hit.
204    /// This also runs on stale hit assets (for which `is_fresh` is false).
205    ///
206    /// The value returned indicates if the force invalidation should be used,
207    /// and which kind. Returning `None` indicates no forced invalidation
208    async fn cache_hit_filter(
209        &self,
210        _session: &mut Session,
211        _meta: &CacheMeta,
212        _hit_handler: &mut HitHandler,
213        _is_fresh: bool,
214        _ctx: &mut Self::CTX,
215    ) -> Result<Option<ForcedFreshness>>
216    where
217        Self::CTX: Send + Sync,
218    {
219        Ok(None)
220    }
221
222    /// Decide if a request should continue to upstream after not being served from cache.
223    ///
224    /// returns: Ok(true) if the request should continue, Ok(false) if a response was written by the
225    /// callback and the session should be finished, or an error
226    ///
227    /// This filter can be used for deferring checks like rate limiting or access control to when they
228    /// actually needed after cache miss.
229    ///
230    /// By default the session will attempt to be reused after returning Ok(false). It is the
231    /// caller's responsibility to disable keepalive or drain the request body if needed.
232    async fn proxy_upstream_filter(
233        &self,
234        _session: &mut Session,
235        _ctx: &mut Self::CTX,
236    ) -> Result<bool>
237    where
238        Self::CTX: Send + Sync,
239    {
240        Ok(true)
241    }
242
243    /// Decide if the response is cacheable
244    fn response_cache_filter(
245        &self,
246        _session: &Session,
247        _resp: &ResponseHeader,
248        _ctx: &mut Self::CTX,
249    ) -> Result<RespCacheable> {
250        Ok(Uncacheable(NoCacheReason::Custom("default")))
251    }
252
253    /// Decide how to generate cache vary key from both request and response
254    ///
255    /// None means no variance is needed.
256    fn cache_vary_filter(
257        &self,
258        _meta: &CacheMeta,
259        _ctx: &mut Self::CTX,
260        _req: &RequestHeader,
261    ) -> Option<HashBinary> {
262        // default to None for now to disable vary feature
263        None
264    }
265
266    /// Decide if the incoming request's condition _fails_ against the cached response.
267    ///
268    /// Returning `Ok(true)` means that the response does _not_ match against the condition, and
269    /// that the proxy can return `304 Not Modified` downstream.
270    ///
271    /// An example is a conditional GET request with `If-None-Match: "foobar"`. If the cached
272    /// response contains the `ETag: "foobar"`, then the condition fails, and `304 Not Modified`
273    /// should be returned. Else, the condition passes which means the full `200 OK` response must
274    /// be sent.
275    fn cache_not_modified_filter(
276        &self,
277        session: &Session,
278        resp: &ResponseHeader,
279        _ctx: &mut Self::CTX,
280    ) -> Result<bool> {
281        Ok(
282            pingora_core::protocols::http::conditional_filter::not_modified_filter(
283                session.req_header(),
284                resp,
285            ),
286        )
287    }
288
289    /// This filter is called when cache is enabled to determine what byte range to return (in both
290    /// cache hit and miss cases) from the response body. It is only used when caching is enabled,
291    /// otherwise the upstream is responsible for any filtering. It allows users to define the range
292    /// this request is for via its return type `range_filter::RangeType`.
293    ///
294    /// It also allow users to modify the response header accordingly.
295    ///
296    /// The default implementation can handle a single-range as per [RFC7232].
297    ///
298    /// [RFC7232]: https://www.rfc-editor.org/rfc/rfc7232
299    fn range_header_filter(
300        &self,
301        session: &mut Session,
302        resp: &mut ResponseHeader,
303        _ctx: &mut Self::CTX,
304    ) -> range_filter::RangeType {
305        const DEFAULT_MAX_RANGES: Option<usize> = Some(200);
306        proxy_cache::range_filter::range_header_filter(
307            session.req_header(),
308            resp,
309            DEFAULT_MAX_RANGES,
310        )
311    }
312
313    /// Modify the request before it is sent to the upstream
314    ///
315    /// Unlike [Self::request_filter()], this filter allows to change the request headers to send
316    /// to the upstream.
317    async fn upstream_request_filter(
318        &self,
319        _session: &mut Session,
320        _upstream_request: &mut RequestHeader,
321        _ctx: &mut Self::CTX,
322    ) -> Result<()>
323    where
324        Self::CTX: Send + Sync,
325    {
326        Ok(())
327    }
328
329    /// Adjust upstream modules before they process the response header.
330    ///
331    /// This filter is called when the upstream response header arrives, before upstream modules
332    /// (such as `upstream_compression`) run their response header filter. Use this to configure
333    /// module behavior based on the response, e.g. setting a dictionary for dictionary-based
334    /// content encoding.
335    ///
336    /// This filter may be called more than once per request if the upstream sends informational
337    /// (1xx) response headers before the final response. Implementations can check
338    /// [`upstream_response.status.is_informational()`](http::StatusCode::is_informational) to
339    /// distinguish informational headers from the final response if needed.
340    ///
341    /// `end_of_stream` indicates whether the response header is also the end of the response
342    /// (e.g. for HEAD responses or 304s with no body).
343    ///
344    /// The response header is provided as an immutable reference. To modify the response header
345    /// itself, use [`Self::upstream_response_filter()`] instead.
346    ///
347    /// This filter requires the `upstream_modules` feature to be enabled.
348    #[cfg(feature = "upstream_modules")]
349    async fn adjust_upstream_modules(
350        &self,
351        _session: &mut Session,
352        _upstream_response: &ResponseHeader,
353        _end_of_stream: bool,
354        _ctx: &mut Self::CTX,
355    ) -> Result<()>
356    where
357        Self::CTX: Send + Sync,
358    {
359        Ok(())
360    }
361
362    /// Modify the response header from the upstream
363    ///
364    /// The modification is before caching, so any change here will be stored in the cache if enabled.
365    ///
366    /// Responses served from cache won't trigger this filter. If the cache needed revalidation,
367    /// only the 304 from upstream will trigger the filter (though it will be merged into the
368    /// cached header, not served directly to downstream).
369    async fn upstream_response_filter(
370        &self,
371        _session: &mut Session,
372        _upstream_response: &mut ResponseHeader,
373        _ctx: &mut Self::CTX,
374    ) -> Result<()>
375    where
376        Self::CTX: Send + Sync,
377    {
378        Ok(())
379    }
380
381    /// Modify the response header before it is send to the downstream
382    ///
383    /// The modification is after caching. This filter is called for all responses including
384    /// responses served from cache.
385    async fn response_filter(
386        &self,
387        _session: &mut Session,
388        _upstream_response: &mut ResponseHeader,
389        _ctx: &mut Self::CTX,
390    ) -> Result<()>
391    where
392        Self::CTX: Send + Sync,
393    {
394        Ok(())
395    }
396
397    // custom_forwarding is called when downstream and upstream connections are successfully established.
398    #[doc(hidden)]
399    async fn custom_forwarding(
400        &self,
401        _session: &mut Session,
402        _ctx: &mut Self::CTX,
403        _custom_message_to_upstream: Option<mpsc::Sender<Bytes>>,
404        _custom_message_to_downstream: mpsc::Sender<Bytes>,
405    ) -> Result<()>
406    where
407        Self::CTX: Send + Sync,
408    {
409        Ok(())
410    }
411
412    // received a custom message from the downstream before sending it to the upstream.
413    #[doc(hidden)]
414    async fn downstream_custom_message_proxy_filter(
415        &self,
416        _session: &mut Session,
417        custom_message: Bytes,
418        _ctx: &mut Self::CTX,
419        _final_hop: bool,
420    ) -> Result<Option<Bytes>>
421    where
422        Self::CTX: Send + Sync,
423    {
424        Ok(Some(custom_message))
425    }
426
427    // received a custom message from the upstream before sending it to the downstream.
428    #[doc(hidden)]
429    async fn upstream_custom_message_proxy_filter(
430        &self,
431        _session: &mut Session,
432        custom_message: Bytes,
433        _ctx: &mut Self::CTX,
434        _final_hop: bool,
435    ) -> Result<Option<Bytes>>
436    where
437        Self::CTX: Send + Sync,
438    {
439        Ok(Some(custom_message))
440    }
441
442    /// Similar to [Self::upstream_response_filter()] but for response body
443    ///
444    /// This function will be called every time a piece of response body is received. The `body` is
445    /// **not the entire response body**.
446    fn upstream_response_body_filter(
447        &self,
448        _session: &mut Session,
449        _body: &mut Option<Bytes>,
450        _end_of_stream: bool,
451        _ctx: &mut Self::CTX,
452    ) -> Result<Option<Duration>> {
453        Ok(None)
454    }
455
456    /// Similar to [Self::upstream_response_filter()] but for response trailers
457    fn upstream_response_trailer_filter(
458        &self,
459        _session: &mut Session,
460        _upstream_trailers: &mut header::HeaderMap,
461        _ctx: &mut Self::CTX,
462    ) -> Result<()> {
463        Ok(())
464    }
465
466    /// Similar to [Self::response_filter()] but for response body chunks
467    fn response_body_filter(
468        &self,
469        _session: &mut Session,
470        _body: &mut Option<Bytes>,
471        _end_of_stream: bool,
472        _ctx: &mut Self::CTX,
473    ) -> Result<Option<Duration>>
474    where
475        Self::CTX: Send + Sync,
476    {
477        Ok(None)
478    }
479
480    /// Similar to [Self::response_filter()] but for response trailers.
481    /// Note, returning an Ok(Some(Bytes)) will result in the downstream response
482    /// trailers being written to the response body.
483    ///
484    /// TODO: make this interface more intuitive
485    async fn response_trailer_filter(
486        &self,
487        _session: &mut Session,
488        _upstream_trailers: &mut header::HeaderMap,
489        _ctx: &mut Self::CTX,
490    ) -> Result<Option<Bytes>>
491    where
492        Self::CTX: Send + Sync,
493    {
494        Ok(None)
495    }
496
497    /// This filter is called when the entire response is sent to the downstream successfully or
498    /// there is a fatal error that terminate the request.
499    ///
500    /// An error log is already emitted if there is any error. This phase is used for collecting
501    /// metrics and sending access logs.
502    async fn logging(&self, _session: &mut Session, _e: Option<&Error>, _ctx: &mut Self::CTX)
503    where
504        Self::CTX: Send + Sync,
505    {
506    }
507
508    /// Called after [`Self::logging`] when the downstream connection will be reused for another
509    /// HTTP/1.x keepalive request. The returned value, if any, will be carried to the next
510    /// request on this connection and delivered via [`Self::on_connection_reuse`].
511    ///
512    /// Use this to persist debugging or timing information across keepalive requests.
513    /// This is only called for HTTP/1.x keepalive connections, not for HTTP/2.
514    /// It is also called on error paths when the downstream connection is eligible for reuse.
515    ///
516    /// The default implementation returns `None` (no context persisted).
517    fn persist_connection_context(
518        &self,
519        _session: &Session,
520        _ctx: &Self::CTX,
521    ) -> Option<Box<dyn Any + Send + Sync>> {
522        None
523    }
524
525    /// Called at the start of a new request on a reused HTTP/1.x keepalive connection,
526    /// before [`Self::early_request_filter`]. The `prev_ctx` argument is the value returned
527    /// by [`Self::persist_connection_context`] from the previous request on this connection.
528    ///
529    /// This is only called for HTTP/1.x keepalive connections, not for HTTP/2.
530    /// It is not called when `persist_connection_context` returned `None` on the previous request.
531    ///
532    /// Use this to transfer state from the previous request into the new request's context.
533    fn on_connection_reuse(
534        &self,
535        _session: &mut Session,
536        _ctx: &mut Self::CTX,
537        _prev_ctx: Box<dyn Any + Send + Sync>,
538    ) {
539    }
540
541    /// A value of true means that the log message will be suppressed. The default value is false.
542    ///
543    /// See also: [`Self::suppress_proxy_warn_log`].
544    fn suppress_error_log(&self, _session: &Session, _ctx: &Self::CTX, _error: &Error) -> bool {
545        false
546    }
547
548    /// A value of true means that the proxy warning log message will be suppressed.
549    /// The default value is false.
550    ///
551    /// This hook currently applies to retryable proxy upstream failures and downstream errors
552    /// ignored while cache fill continues. Final proxy errors are still handled by
553    /// [`Self::suppress_error_log`].
554    ///
555    /// Suppressing retry warning logs can remove the only per-retry audit record. Callers that
556    /// suppress these logs should provide alternative observability, such as metrics or logs in
557    /// their implementation of this hook.
558    ///
559    /// This hook runs inline on retry and cache-error paths, so implementations should be cheap.
560    ///
561    /// Experimental: this API may change or be removed until indicated otherwise.
562    fn suppress_proxy_warn_log(
563        &self,
564        _session: &Session,
565        _ctx: &Self::CTX,
566        _error: &Error,
567        _context: ProxyWarnLogContext,
568    ) -> bool {
569        false
570    }
571
572    /// This filter is called when there is an error **after** a connection is established (or reused)
573    /// to the upstream.
574    fn error_while_proxy(
575        &self,
576        peer: &HttpPeer,
577        session: &mut Session,
578        e: Box<Error>,
579        _ctx: &mut Self::CTX,
580        client_reused: bool,
581    ) -> Box<Error> {
582        let mut e = e.more_context(format!("Peer: {}", peer));
583        // only reused client connections where retry buffer is not truncated
584        e.retry
585            .decide_reuse(client_reused && !session.as_ref().retry_buffer_truncated());
586        e
587    }
588
589    /// This filter is called when there is an error in the process of establishing a connection
590    /// to the upstream.
591    ///
592    /// In this filter the user can decide whether the error is retry-able by marking the error `e`.
593    ///
594    /// If the error can be retried, [Self::upstream_peer()] will be called again so that the user
595    /// can decide whether to send the request to the same upstream or another upstream that is possibly
596    /// available.
597    fn fail_to_connect(
598        &self,
599        _session: &mut Session,
600        _peer: &HttpPeer,
601        _ctx: &mut Self::CTX,
602        e: Box<Error>,
603    ) -> Box<Error> {
604        e
605    }
606
607    /// This filter is called when the request encounters a fatal error.
608    ///
609    /// Users may write an error response to the downstream if the downstream is still writable.
610    ///
611    /// The response status code of the error response may be returned for logging purposes.
612    /// Additionally, the user can return whether this session may be reused in spite of the error.
613    /// Today this reuse status is only respected for errors that occur prior to upstream peer
614    /// selection, and the keepalive configured on the `Session` itself still takes precedent.
615    async fn fail_to_proxy(
616        &self,
617        session: &mut Session,
618        e: &Error,
619        _ctx: &mut Self::CTX,
620    ) -> FailToProxy
621    where
622        Self::CTX: Send + Sync,
623    {
624        let code = match e.etype() {
625            HTTPStatus(code) => *code,
626            _ => {
627                match e.esource() {
628                    ErrorSource::Upstream => 502,
629                    ErrorSource::Downstream => {
630                        match e.etype() {
631                            WriteError | ReadError | ConnectionClosed => {
632                                /* conn already dead */
633                                0
634                            }
635                            _ => 400,
636                        }
637                    }
638                    ErrorSource::Internal | ErrorSource::Unset => 500,
639                }
640            }
641        };
642        if code > 0 {
643            session.respond_error(code).await.unwrap_or_else(|e| {
644                error!("failed to send error response to downstream: {e}");
645            });
646        }
647
648        FailToProxy {
649            error_code: code,
650            // default to no reuse, which is safest
651            can_reuse_downstream: false,
652        }
653    }
654
655    /// Decide whether should serve stale when encountering an error or during revalidation
656    ///
657    /// An implementation should follow
658    /// <https://datatracker.ietf.org/doc/html/rfc9111#section-4.2.4>
659    /// <https://www.rfc-editor.org/rfc/rfc5861#section-4>
660    ///
661    /// This filter is only called if cache is enabled.
662    // 5xx HTTP status will be encoded as ErrorType::HTTPStatus(code)
663    fn should_serve_stale(
664        &self,
665        _session: &mut Session,
666        _ctx: &mut Self::CTX,
667        error: Option<&Error>, // None when it is called during stale while revalidate
668    ) -> bool {
669        // A cache MUST NOT generate a stale response unless
670        // it is disconnected
671        // or doing so is explicitly permitted by the client or origin server
672        // (e.g. headers or an out-of-band contract)
673        error.is_some_and(|e| e.esource() == &ErrorSource::Upstream)
674    }
675
676    /// This filter is called when the request just established or reused a connection to the upstream
677    ///
678    /// This filter allows user to log timing and connection related info.
679    async fn connected_to_upstream(
680        &self,
681        _session: &mut Session,
682        _reused: bool,
683        _peer: &HttpPeer,
684        #[cfg(unix)] _fd: std::os::unix::io::RawFd,
685        #[cfg(windows)] _sock: std::os::windows::io::RawSocket,
686        _digest: Option<&Digest>,
687        _ctx: &mut Self::CTX,
688    ) -> Result<()>
689    where
690        Self::CTX: Send + Sync,
691    {
692        Ok(())
693    }
694
695    /// This callback is invoked every time request related error log needs to be generated
696    ///
697    /// Users can define what is important to be written about this request via the returned string.
698    fn request_summary(&self, session: &Session, _ctx: &Self::CTX) -> String {
699        session.as_ref().request_summary()
700    }
701
702    /// Whether the request should be used to invalidate(delete) the HTTP cache
703    ///
704    /// - `true`: this request will be used to invalidate the cache.
705    /// - `false`: this request is a treated as a normal request
706    fn is_purge(&self, _session: &Session, _ctx: &Self::CTX) -> bool {
707        false
708    }
709
710    /// This filter is called after the proxy cache generates the downstream response to the purge
711    /// request (to invalidate or delete from the HTTP cache), based on the purge status, which
712    /// indicates whether the request succeeded or failed.
713    ///
714    /// The filter allows the user to modify or replace the generated downstream response.
715    /// If the filter returns `Err`, the proxy will instead send a 500 response.
716    fn purge_response_filter(
717        &self,
718        _session: &Session,
719        _ctx: &mut Self::CTX,
720        _purge_status: PurgeStatus,
721        _purge_response: &mut std::borrow::Cow<'static, ResponseHeader>,
722    ) -> Result<()> {
723        Ok(())
724    }
725}
726
727/// Context struct returned by `fail_to_proxy`.
728pub struct FailToProxy {
729    pub error_code: u16,
730    pub can_reuse_downstream: bool,
731}