-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathlib.rs
More file actions
1059 lines (961 loc) · 36 KB
/
lib.rs
File metadata and controls
1059 lines (961 loc) · 36 KB
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 Cloudflare, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # pingora-proxy
//!
//! Programmable HTTP proxy built on top of [pingora_core].
//!
//! # Features
//! - HTTP/1.x and HTTP/2 for both downstream and upstream
//! - Connection pooling
//! - TLSv1.3, mutual TLS, customizable CA
//! - Request/Response scanning, modification or rejection
//! - Dynamic upstream selection
//! - Configurable retry and failover
//! - Fully programmable and customizable at any stage of a HTTP request
//!
//! # How to use
//!
//! Users of this crate defines their proxy by implementing [ProxyHttp] trait, which contains the
//! callbacks to be invoked at each stage of a HTTP request.
//!
//! Then the service can be passed into [`http_proxy_service()`] for a [pingora_core::server::Server] to
//! run it.
//!
//! See `examples/load_balancer.rs` for a detailed example.
use async_trait::async_trait;
use bytes::Bytes;
use futures::future::BoxFuture;
use futures::future::FutureExt;
use http::{header, version::Version};
use log::{debug, error, trace, warn};
use once_cell::sync::Lazy;
use pingora_http::{RequestHeader, ResponseHeader};
use std::fmt::Debug;
use std::str;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, Notify};
use tokio::time;
use pingora_cache::NoCacheReason;
use pingora_core::apps::{
HttpPersistentSettings, HttpServerApp, HttpServerOptions, ReusedHttpStream,
};
use pingora_core::connectors::http::custom;
use pingora_core::connectors::{http::Connector, ConnectorOptions};
use pingora_core::modules::http::compression::ResponseCompressionBuilder;
use pingora_core::modules::http::{HttpModuleCtx, HttpModules};
use pingora_core::protocols::http::client::HttpSession as ClientSession;
use pingora_core::protocols::http::custom::CustomMessageWrite;
use pingora_core::protocols::http::v1::client::HttpSession as HttpSessionV1;
use pingora_core::protocols::http::v2::server::H2Options;
use pingora_core::protocols::http::HttpTask;
use pingora_core::protocols::http::ServerSession as HttpSession;
use pingora_core::protocols::http::SERVER_NAME;
use pingora_core::protocols::Stream;
use pingora_core::protocols::{Digest, UniqueID};
use pingora_core::server::configuration::ServerConf;
use pingora_core::server::ShutdownWatch;
use pingora_core::upstreams::peer::{HttpPeer, Peer};
use pingora_error::{Error, ErrorSource, ErrorType::*, OrErr, Result};
const TASK_BUFFER_SIZE: usize = 4;
mod proxy_cache;
mod proxy_common;
mod proxy_custom;
mod proxy_h1;
mod proxy_h2;
mod proxy_purge;
mod proxy_trait;
pub mod subrequest;
use subrequest::{BodyMode, Ctx as SubrequestCtx};
pub use proxy_cache::range_filter::{range_header_filter, RangeType};
pub use proxy_purge::PurgeStatus;
pub use proxy_trait::{FailToProxy, ProxyHttp};
pub mod prelude {
pub use crate::{http_proxy_service, ProxyHttp, Session};
}
pub type ProcessCustomSession<SV, C> = Arc<
dyn Fn(Arc<HttpProxy<SV, C>>, Stream, &ShutdownWatch) -> BoxFuture<'static, Option<Stream>>
+ Send
+ Sync
+ Unpin
+ 'static,
>;
/// The concrete type that holds the user defined HTTP proxy.
///
/// Users don't need to interact with this object directly.
pub struct HttpProxy<SV, C = ()>
where
C: custom::Connector, // Upstream custom connector
{
inner: SV, // TODO: name it better than inner
client_upstream: Connector<C>,
shutdown: Notify,
pub server_options: Option<HttpServerOptions>,
pub h2_options: Option<H2Options>,
pub downstream_modules: HttpModules,
max_retries: usize,
process_custom_session: Option<ProcessCustomSession<SV, C>>,
}
impl<SV> HttpProxy<SV, ()> {
fn new(inner: SV, conf: Arc<ServerConf>) -> Self {
HttpProxy {
inner,
client_upstream: Connector::new(Some(ConnectorOptions::from_server_conf(&conf))),
shutdown: Notify::new(),
server_options: None,
h2_options: None,
downstream_modules: HttpModules::new(),
max_retries: conf.max_retries,
process_custom_session: None,
}
}
}
impl<SV, C> HttpProxy<SV, C>
where
C: custom::Connector,
{
fn new_custom(
inner: SV,
conf: Arc<ServerConf>,
connector: C,
on_custom: ProcessCustomSession<SV, C>,
) -> Self
where
SV: ProxyHttp + Send + Sync + 'static,
SV::CTX: Send + Sync,
{
let client_upstream =
Connector::new_custom(Some(ConnectorOptions::from_server_conf(&conf)), connector);
HttpProxy {
inner,
client_upstream,
shutdown: Notify::new(),
server_options: None,
downstream_modules: HttpModules::new(),
max_retries: conf.max_retries,
process_custom_session: Some(on_custom),
h2_options: None,
}
}
fn handle_init_modules(&mut self)
where
SV: ProxyHttp,
{
self.inner
.init_downstream_modules(&mut self.downstream_modules);
}
async fn handle_new_request(
&self,
mut downstream_session: Box<HttpSession>,
) -> Option<Box<HttpSession>>
where
SV: ProxyHttp + Send + Sync,
SV::CTX: Send + Sync,
{
// phase 1 read request header
let res = tokio::select! {
biased; // biased select is cheaper, and we don't want to drop already buffered requests
res = downstream_session.read_request() => { res }
_ = self.shutdown.notified() => {
// service shutting down, dropping the connection to stop more req from coming in
return None;
}
};
match res {
Ok(true) => {
// TODO: check n==0
debug!("Successfully get a new request");
}
Ok(false) => {
return None; // TODO: close connection?
}
Err(mut e) => {
e.as_down();
error!("Fail to proxy: {e}");
if matches!(e.etype, InvalidHTTPHeader) {
downstream_session
.respond_error(400)
.await
.unwrap_or_else(|e| {
error!("failed to send error response to downstream: {e}");
});
} // otherwise the connection must be broken, no need to send anything
downstream_session.shutdown().await;
return None;
}
}
trace!(
"Request header: {:?}",
downstream_session.req_header().as_ref()
);
Some(downstream_session)
}
// return bool: server_session can be reused, and error if any
async fn proxy_to_upstream(
&self,
session: &mut Session,
ctx: &mut SV::CTX,
) -> (bool, Option<Box<Error>>)
where
SV: ProxyHttp + Send + Sync,
SV::CTX: Send + Sync,
{
let peer = match self.inner.upstream_peer(session, ctx).await {
Ok(p) => p,
Err(e) => return (false, Some(e)),
};
let client_session = self.client_upstream.get_http_session(&*peer).await;
match client_session {
Ok((client_session, client_reused)) => {
let (server_reused, error) = match client_session {
ClientSession::H1(mut h1) => {
let (server_reused, client_reuse, error) = self
.proxy_to_h1_upstream(session, &mut h1, client_reused, &peer, ctx)
.await;
if client_reuse {
let session = ClientSession::H1(h1);
self.client_upstream
.release_http_session(session, &*peer, peer.idle_timeout())
.await;
}
(server_reused, error)
}
ClientSession::H2(mut h2) => {
let (server_reused, mut error) = self
.proxy_to_h2_upstream(session, &mut h2, client_reused, &peer, ctx)
.await;
let session = ClientSession::H2(h2);
self.client_upstream
.release_http_session(session, &*peer, peer.idle_timeout())
.await;
if let Some(e) = error.as_mut() {
// try to downgrade if A. origin says so or B. origin sends an invalid
// response, which usually means origin h2 is not production ready
if matches!(e.etype, H2Downgrade | InvalidH2) {
if peer
.get_alpn()
.map_or(true, |alpn| alpn.get_min_http_version() == 1)
{
// Add the peer to prefer h1 so that all following requests
// will use h1
self.client_upstream.prefer_h1(&*peer);
} else {
// the peer doesn't allow downgrading to h1 (e.g. gRPC)
e.retry = false.into();
}
}
}
(server_reused, error)
}
ClientSession::Custom(mut c) => {
let (server_reused, error) = self
.proxy_to_custom_upstream(session, &mut c, client_reused, &peer, ctx)
.await;
let session = ClientSession::Custom(c);
self.client_upstream
.release_http_session(session, &*peer, peer.idle_timeout())
.await;
(server_reused, error)
}
};
(
server_reused,
error.map(|e| {
self.inner
.error_while_proxy(&peer, session, e, ctx, client_reused)
}),
)
}
Err(mut e) => {
e.as_up();
let new_err = self.inner.fail_to_connect(session, &peer, ctx, e);
(false, Some(new_err.into_up()))
}
}
}
async fn upstream_filter(
&self,
session: &mut Session,
task: &mut HttpTask,
ctx: &mut SV::CTX,
) -> Result<Option<Duration>>
where
SV: ProxyHttp + Send + Sync,
SV::CTX: Send + Sync,
{
let duration = match task {
HttpTask::Header(header, _eos) => {
self.inner
.upstream_response_filter(session, header, ctx)
.await?;
None
}
HttpTask::Body(data, eos) => self
.inner
.upstream_response_body_filter(session, data, *eos, ctx)?,
HttpTask::Trailer(Some(trailers)) => {
self.inner
.upstream_response_trailer_filter(session, trailers, ctx)?;
None
}
_ => {
// task does not support a filter
None
}
};
Ok(duration)
}
async fn finish(
&self,
mut session: Session,
ctx: &mut SV::CTX,
reuse: bool,
error: Option<&Error>,
) -> Option<ReusedHttpStream>
where
SV: ProxyHttp + Send + Sync,
SV::CTX: Send + Sync,
{
self.inner.logging(&mut session, error, ctx).await;
if reuse {
// TODO: log error
let persistent_settings = HttpPersistentSettings::for_session(&session);
session
.downstream_session
.finish()
.await
.ok()
.flatten()
.map(|s| ReusedHttpStream::new(s, Some(persistent_settings)))
} else {
None
}
}
fn cleanup_sub_req(&self, session: &mut Session) {
if let Some(ctx) = session.subrequest_ctx.as_mut() {
ctx.release_write_lock();
}
}
}
use pingora_cache::HttpCache;
use pingora_core::protocols::http::compression::ResponseCompressionCtx;
/// The established HTTP session
///
/// This object is what users interact with in order to access the request itself or change the proxy
/// behavior.
pub struct Session {
/// the HTTP session to downstream (the client)
pub downstream_session: Box<HttpSession>,
/// The interface to control HTTP caching
pub cache: HttpCache,
/// (de)compress responses coming into the proxy (from upstream)
pub upstream_compression: ResponseCompressionCtx,
/// ignore downstream range (skip downstream range filters)
pub ignore_downstream_range: bool,
/// Were the upstream request headers modified?
pub upstream_headers_mutated_for_cache: bool,
/// The context from parent request, if this is a subrequest.
pub subrequest_ctx: Option<Box<SubrequestCtx>>,
/// Handle to allow spawning subrequests, assigned by the `Subrequest` app logic.
pub subrequest_spawner: Option<SubrequestSpawner>,
// Downstream filter modules
pub downstream_modules_ctx: HttpModuleCtx,
}
impl Session {
fn new(
downstream_session: impl Into<Box<HttpSession>>,
downstream_modules: &HttpModules,
) -> Self {
Session {
downstream_session: downstream_session.into(),
cache: HttpCache::new(),
// disable both upstream and downstream compression
upstream_compression: ResponseCompressionCtx::new(0, false, false),
ignore_downstream_range: false,
upstream_headers_mutated_for_cache: false,
subrequest_ctx: None,
subrequest_spawner: None, // optionally set later on
downstream_modules_ctx: downstream_modules.build_ctx(),
}
}
/// Create a new [Session] from the given [Stream]
///
/// This function is mostly used for testing and mocking.
pub fn new_h1(stream: Stream) -> Self {
let modules = HttpModules::new();
Self::new(Box::new(HttpSession::new_http1(stream)), &modules)
}
/// Create a new [Session] from the given [Stream] with modules
///
/// This function is mostly used for testing and mocking.
pub fn new_h1_with_modules(stream: Stream, downstream_modules: &HttpModules) -> Self {
Self::new(Box::new(HttpSession::new_http1(stream)), downstream_modules)
}
pub fn as_downstream_mut(&mut self) -> &mut HttpSession {
&mut self.downstream_session
}
pub fn as_downstream(&self) -> &HttpSession {
&self.downstream_session
}
/// Write HTTP response with the given error code to the downstream.
pub async fn respond_error(&mut self, error: u16) -> Result<()> {
self.as_downstream_mut().respond_error(error).await
}
/// Write HTTP response with the given error code to the downstream with a body.
pub async fn respond_error_with_body(&mut self, error: u16, body: Bytes) -> Result<()> {
self.as_downstream_mut()
.respond_error_with_body(error, body)
.await
}
/// Write the given HTTP response header to the downstream
///
/// Different from directly calling [HttpSession::write_response_header], this function also
/// invokes the filter modules.
pub async fn write_response_header(
&mut self,
mut resp: Box<ResponseHeader>,
end_of_stream: bool,
) -> Result<()> {
self.downstream_modules_ctx
.response_header_filter(&mut resp, end_of_stream)
.await?;
self.downstream_session.write_response_header(resp).await
}
/// Write the given HTTP response body chunk to the downstream
///
/// Different from directly calling [HttpSession::write_response_body], this function also
/// invokes the filter modules.
pub async fn write_response_body(
&mut self,
mut body: Option<Bytes>,
end_of_stream: bool,
) -> Result<()> {
self.downstream_modules_ctx
.response_body_filter(&mut body, end_of_stream)?;
if body.is_none() && !end_of_stream {
return Ok(());
}
let data = body.unwrap_or_default();
self.downstream_session
.write_response_body(data, end_of_stream)
.await
}
pub async fn write_response_tasks(&mut self, mut tasks: Vec<HttpTask>) -> Result<bool> {
for task in tasks.iter_mut() {
match task {
HttpTask::Header(resp, end) => {
self.downstream_modules_ctx
.response_header_filter(resp, *end)
.await?;
}
HttpTask::Body(data, end) => {
self.downstream_modules_ctx
.response_body_filter(data, *end)?;
}
HttpTask::Trailer(trailers) => {
if let Some(buf) = self
.downstream_modules_ctx
.response_trailer_filter(trailers)?
{
// Write the trailers into the body if the filter
// returns a buffer.
//
// Note, this will not work if end of stream has already
// been seen or we've written content-length bytes.
*task = HttpTask::Body(Some(buf), true);
}
}
HttpTask::Done => {
// `Done` can be sent in certain response paths to mark end
// of response if not already done via trailers or body with
// end flag set.
// If the filter returns body bytes on Done,
// write them into the response.
//
// Note, this will not work if end of stream has already
// been seen or we've written content-length bytes.
if let Some(buf) = self.downstream_modules_ctx.response_done_filter()? {
*task = HttpTask::Body(Some(buf), true);
}
}
_ => { /* Failed */ }
}
}
self.downstream_session.response_duplex_vec(tasks).await
}
/// Mark the upstream headers as modified by caching. This should lead to range filters being
/// skipped when responding to the downstream.
pub fn mark_upstream_headers_mutated_for_cache(&mut self) {
self.upstream_headers_mutated_for_cache = true;
}
/// Check whether the upstream headers were marked as mutated during the request.
pub fn upstream_headers_mutated_for_cache(&self) -> bool {
self.upstream_headers_mutated_for_cache
}
pub fn downstream_custom_message(
&mut self,
) -> Result<
Option<Box<dyn futures::Stream<Item = Result<Bytes>> + Unpin + Send + Sync + 'static>>,
> {
if let Some(custom_session) = self.downstream_session.as_custom_mut() {
custom_session
.take_custom_message_reader()
.map(Some)
.ok_or(Error::explain(
ReadError,
"can't extract custom reader from downstream",
))
} else {
Ok(None)
}
}
}
impl AsRef<HttpSession> for Session {
fn as_ref(&self) -> &HttpSession {
&self.downstream_session
}
}
impl AsMut<HttpSession> for Session {
fn as_mut(&mut self) -> &mut HttpSession {
&mut self.downstream_session
}
}
use std::ops::{Deref, DerefMut};
impl Deref for Session {
type Target = HttpSession;
fn deref(&self) -> &Self::Target {
&self.downstream_session
}
}
impl DerefMut for Session {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.downstream_session
}
}
impl Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("downstream_session", &"HttpSession")
.field("cache", &"HttpCache")
.field("upstream_compression", &"ResponseCompressionCtx")
.field("ignore_downstream_range", &self.ignore_downstream_range)
.field(
"upstream_headers_mutated_for_cache",
&self.upstream_headers_mutated_for_cache,
)
.finish_non_exhaustive()
}
}
// generic HTTP 502 response sent when proxy_upstream_filter refuses to connect to upstream
static BAD_GATEWAY: Lazy<ResponseHeader> = Lazy::new(|| {
let mut resp = ResponseHeader::build(http::StatusCode::BAD_GATEWAY, Some(3)).unwrap();
resp.insert_header(header::SERVER, &SERVER_NAME[..])
.unwrap();
resp.insert_header(header::CONTENT_LENGTH, 0).unwrap();
resp.insert_header(header::CACHE_CONTROL, "private, no-store")
.unwrap();
resp
});
impl<SV, C> HttpProxy<SV, C>
where
C: custom::Connector,
{
async fn process_request(
self: &Arc<Self>,
mut session: Session,
mut ctx: <SV as ProxyHttp>::CTX,
) -> Option<ReusedHttpStream>
where
SV: ProxyHttp + Send + Sync + 'static,
<SV as ProxyHttp>::CTX: Send + Sync,
{
if let Err(e) = self
.inner
.early_request_filter(&mut session, &mut ctx)
.await
{
return self
.handle_error(session, &mut ctx, e, "Fail to early filter request:")
.await;
}
if self.inner.allow_spawning_subrequest(&session, &ctx) {
session.subrequest_spawner = Some(SubrequestSpawner::new(self.clone()));
}
let req = session.downstream_session.req_header_mut();
// Built-in downstream request filters go first
if let Err(e) = session
.downstream_modules_ctx
.request_header_filter(req)
.await
{
return self
.handle_error(
session,
&mut ctx,
e,
"Failed in downstream modules request filter:",
)
.await;
}
match self.inner.request_filter(&mut session, &mut ctx).await {
Ok(response_sent) => {
if response_sent {
// TODO: log error
self.inner.logging(&mut session, None, &mut ctx).await;
self.cleanup_sub_req(&mut session);
let persistent_settings = HttpPersistentSettings::for_session(&session);
return session
.downstream_session
.finish()
.await
.ok()
.flatten()
.map(|s| ReusedHttpStream::new(s, Some(persistent_settings)));
}
/* else continue */
}
Err(e) => {
return self
.handle_error(session, &mut ctx, e, "Fail to filter request:")
.await;
}
}
if let Some((reuse, err)) = self.proxy_cache(&mut session, &mut ctx).await {
// cache hit
return self.finish(session, &mut ctx, reuse, err.as_deref()).await;
}
// either uncacheable, or cache miss
// there should not be a write lock in the sub req ctx after this point
self.cleanup_sub_req(&mut session);
// decide if the request is allowed to go to upstream
match self
.inner
.proxy_upstream_filter(&mut session, &mut ctx)
.await
{
Ok(proxy_to_upstream) => {
if !proxy_to_upstream {
// The hook can choose to write its own response, but if it doesn't, we respond
// with a generic 502
if session.cache.enabled() {
// drop the cache lock that this request may be holding onto
session.cache.disable(NoCacheReason::DeclinedToUpstream);
}
if session.response_written().is_none() {
match session.write_response_header_ref(&BAD_GATEWAY).await {
Ok(()) => {}
Err(e) => {
return self
.handle_error(
session,
&mut ctx,
e,
"Error responding with Bad Gateway:",
)
.await;
}
}
}
return self.finish(session, &mut ctx, true, None).await;
}
/* else continue */
}
Err(e) => {
if session.cache.enabled() {
session.cache.disable(NoCacheReason::InternalError);
}
return self
.handle_error(
session,
&mut ctx,
e,
"Error deciding if we should proxy to upstream:",
)
.await;
}
}
let mut retries: usize = 0;
let mut server_reuse = false;
let mut proxy_error: Option<Box<Error>> = None;
while retries < self.max_retries {
retries += 1;
let (reuse, e) = self.proxy_to_upstream(&mut session, &mut ctx).await;
server_reuse = reuse;
match e {
Some(error) => {
let retry = error.retry();
proxy_error = Some(error);
if !retry {
break;
}
// only log error that will be retried here, the final error will be logged below
warn!(
"Fail to proxy: {}, tries: {}, retry: {}, {}",
proxy_error.as_ref().unwrap(),
retries,
retry,
self.inner.request_summary(&session, &ctx)
);
}
None => {
proxy_error = None;
break;
}
};
}
// serve stale if error
// Check both error and cache before calling the function because await is not cheap
// allow unwrap until if let chains
#[allow(clippy::unnecessary_unwrap)]
let serve_stale_result = if proxy_error.is_some() && session.cache.can_serve_stale_error() {
self.handle_stale_if_error(&mut session, &mut ctx, proxy_error.as_ref().unwrap())
.await
} else {
None
};
let final_error = if let Some((reuse, stale_cache_error)) = serve_stale_result {
// don't reuse server conn if serve stale polluted it
server_reuse = server_reuse && reuse;
stale_cache_error
} else {
proxy_error
};
if let Some(e) = final_error.as_ref() {
// If we have errored and are still holding a cache lock, release it.
if session.cache.enabled() {
let reason = if *e.esource() == ErrorSource::Upstream {
NoCacheReason::UpstreamError
} else {
NoCacheReason::InternalError
};
session.cache.disable(reason);
}
let res = self.inner.fail_to_proxy(&mut session, e, &mut ctx).await;
// final error will have > 0 status unless downstream connection is dead
if !self.inner.suppress_error_log(&session, &ctx, e) {
error!(
"Fail to proxy: {}, status: {}, tries: {}, retry: {}, {}",
final_error.as_ref().unwrap(),
res.error_code,
retries,
false, // we never retry here
self.inner.request_summary(&session, &ctx)
);
}
}
// logging() will be called in finish()
self.finish(session, &mut ctx, server_reuse, final_error.as_deref())
.await
}
async fn handle_error(
&self,
mut session: Session,
ctx: &mut <SV as ProxyHttp>::CTX,
e: Box<Error>,
context: &str,
) -> Option<ReusedHttpStream>
where
SV: ProxyHttp + Send + Sync + 'static,
<SV as ProxyHttp>::CTX: Send + Sync,
{
let res = self.inner.fail_to_proxy(&mut session, &e, ctx).await;
if !self.inner.suppress_error_log(&session, ctx, &e) {
error!(
"{context} {}, status: {}, {}",
e,
res.error_code,
self.inner.request_summary(&session, ctx)
);
}
self.inner.logging(&mut session, Some(&e), ctx).await;
self.cleanup_sub_req(&mut session);
if res.can_reuse_downstream {
let persistent_settings = HttpPersistentSettings::for_session(&session);
session
.downstream_session
.finish()
.await
.ok()
.flatten()
.map(|s| ReusedHttpStream::new(s, Some(persistent_settings)))
} else {
None
}
}
}
/* Make process_subrequest() a trait to workaround https://github.com/rust-lang/rust/issues/78649
if process_subrequest() is implemented as a member of HttpProxy, rust complains
error[E0391]: cycle detected when computing type of `proxy_cache::<impl at pingora-proxy/src/proxy_cache.rs:7:1: 7:23>::proxy_cache::{opaque#0}`
--> pingora-proxy/src/proxy_cache.rs:13:10
|
13 | ) -> Option<(bool, Option<Box<Error>>)>
*/
#[async_trait]
pub trait Subrequest {
async fn process_subrequest(
self: Arc<Self>,
session: Box<HttpSession>,
sub_req_ctx: Box<SubrequestCtx>,
);
}
#[async_trait]
impl<SV, C> Subrequest for HttpProxy<SV, C>
where
SV: ProxyHttp + Send + Sync + 'static,
<SV as ProxyHttp>::CTX: Send + Sync,
C: custom::Connector,
{
async fn process_subrequest(
self: Arc<Self>,
session: Box<HttpSession>,
sub_req_ctx: Box<SubrequestCtx>,
) {
debug!("starting subrequest");
let mut session = match self.handle_new_request(session).await {
Some(downstream_session) => Session::new(downstream_session, &self.downstream_modules),
None => return, // bad request
};
// no real downstream to keepalive, but it doesn't matter what is set here because at the end
// of this fn the dummy connection will be dropped
session.set_keepalive(None);
session.subrequest_ctx.replace(sub_req_ctx);
trace!("processing subrequest");
let ctx = self.inner.new_ctx();
self.process_request(session, ctx).await;
trace!("subrequest done");
}
}
/// A handle to the underlying HTTP proxy app that allows spawning subrequests.
pub struct SubrequestSpawner {
app: Arc<dyn Subrequest + Send + Sync>,
}
impl SubrequestSpawner {
/// Create a new [`SubrequestSpawner`].
pub fn new(app: Arc<dyn Subrequest + Send + Sync>) -> SubrequestSpawner {
SubrequestSpawner { app }
}
/// Spawn a background subrequest and return a join handle.
// TODO: allow configuring the subrequest session before use
pub fn spawn_background_subrequest(
&self,
session: &HttpSession,
ctx: SubrequestCtx,
) -> tokio::task::JoinHandle<()> {
let new_app = self.app.clone(); // Clone the Arc
let (mut session, handle) = subrequest::create_session(session);
if ctx.body_mode() == BodyMode::NoBody {
session
.as_subrequest_mut()
.expect("created subrequest session")
.clear_request_body_headers();
}
let sub_req_ctx = Box::new(ctx);
handle.drain_tasks();
tokio::spawn(async move {
new_app
.process_subrequest(Box::new(session), sub_req_ctx)
.await;
})
}
}
#[async_trait]
impl<SV, C> HttpServerApp for HttpProxy<SV, C>
where
SV: ProxyHttp + Send + Sync + 'static,
<SV as ProxyHttp>::CTX: Send + Sync,
C: custom::Connector,
{
async fn process_new_http(
self: &Arc<Self>,
session: HttpSession,
_shutdown: &ShutdownWatch,
) -> Option<ReusedHttpStream> {
let session = Box::new(session);
// TODO: keepalive pool, use stack
let session = match self.handle_new_request(session).await {
Some(downstream_session) => Session::new(downstream_session, &self.downstream_modules),
None => return None, // bad request
};
let ctx = self.inner.new_ctx();
self.process_request(session, ctx).await
}
async fn http_cleanup(&self) {
// Notify all keepalived requests blocking on read_request() to abort
self.shutdown.notify_waiters();
// TODO: impl shutting down flag so that we don't need to read stack.is_shutting_down()
}
fn server_options(&self) -> Option<&HttpServerOptions> {
self.server_options.as_ref()
}
fn h2_options(&self) -> Option<H2Options> {
self.h2_options.clone()
}
async fn process_custom_session(
self: Arc<Self>,
stream: Stream,
shutdown: &ShutdownWatch,
) -> Option<Stream> {
let app = self.clone();