-
Notifications
You must be signed in to change notification settings - Fork 204
Expand file tree
/
Copy pathproxy_service.rs
More file actions
1917 lines (1708 loc) · 58.4 KB
/
Copy pathproxy_service.rs
File metadata and controls
1917 lines (1708 loc) · 58.4 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
use anyhow::{Context, Result, bail, ensure};
use bytes::Bytes;
use futures_util::{SinkExt, StreamExt};
use http_body_util::{BodyExt, Full, Limited};
use hyper::{
Request, Response, StatusCode,
body::Incoming as BodyIncoming,
header::{HeaderName, HeaderValue},
};
use hyper_tungstenite;
use hyper_util::{client::legacy::Client, rt::TokioExecutor};
use moka::future::Cache;
use opentelemetry_http::{HeaderExtractor, HeaderInjector};
use rand::seq::SliceRandom;
use rivet_api_builder::{RequestIds, X_RIVET_RAY_ID};
use rivet_util::Id;
use tracing_opentelemetry::OpenTelemetrySpanExt;
use rivet_runner_protocol as protocol;
use std::{
net::{IpAddr, SocketAddr},
sync::Arc,
time::{Duration, Instant},
};
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tracing::Instrument;
use url::Url;
use crate::RouteTarget;
use crate::request_context::RequestContext;
use crate::response_body::ResponseBody;
use crate::route::{CacheKeyFn, ResolveRouteOutput, RouteCache, RoutingFn, RoutingOutput};
use crate::utils::InFlightCounter;
use crate::{
WebSocketHandle, custom_serve::HibernationResult, errors, metrics, task_group::TaskGroup, utils,
};
pub const X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for");
pub const X_RIVET_ERROR: HeaderName = HeaderName::from_static("x-rivet-error");
const PROXY_STATE_CACHE_TTL: Duration = Duration::from_secs(60 * 60); // 1 hour
const WEBSOCKET_CLOSE_LINGER: Duration = Duration::from_millis(5); // Keep TCP connection open briefly after WebSocket close
// State shared across all request handlers
pub struct ProxyState {
config: rivet_config::Config,
routing_fn: RoutingFn,
cache_key_fn: CacheKeyFn,
// NOTE: Using the hyper legacy client is the only option currently.
// This is what reqwest uses under the hood. Eventually we'll migrate to h3 once it's ready.
client: Client<
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>,
Full<Bytes>,
>,
route_cache: RouteCache,
// We use moka::Cache instead of scc::HashMap because it automatically handles TTL and capacity
rate_limiters: Cache<std::net::IpAddr, Arc<Mutex<rivet_util::throttle::RateLimiter>>>,
in_flight_counters: Cache<std::net::IpAddr, Arc<Mutex<InFlightCounter>>>,
in_flight_requests: Cache<protocol::RequestId, ()>,
tasks: Arc<TaskGroup>,
}
impl ProxyState {
pub fn new(
config: rivet_config::Config,
routing_fn: RoutingFn,
cache_key_fn: CacheKeyFn,
) -> Self {
let https_connector_builder =
match hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
Ok(builder) => builder,
Err(err) => {
tracing::warn!(
?err,
"failed to load native TLS roots; falling back to webpki roots"
);
hyper_rustls::HttpsConnectorBuilder::new().with_webpki_roots()
}
};
let https_connector = https_connector_builder
.https_or_http()
.enable_http1()
.enable_http2()
.build();
let client = Client::builder(TokioExecutor::new())
.pool_idle_timeout(Duration::from_secs(30))
.build(https_connector);
let route_cache_ttl = config.guard().route_cache_ttl();
Self {
config,
routing_fn,
cache_key_fn,
client,
route_cache: RouteCache::new(route_cache_ttl),
rate_limiters: Cache::builder()
.max_capacity(10_000)
.time_to_idle(PROXY_STATE_CACHE_TTL)
.build(),
in_flight_counters: Cache::builder()
.max_capacity(10_000)
.time_to_idle(PROXY_STATE_CACHE_TTL)
.build(),
in_flight_requests: Cache::builder().max_capacity(10_000_000).build(),
tasks: TaskGroup::new(),
}
}
#[tracing::instrument(skip_all)]
async fn resolve_route(
&self,
req_ctx: &mut RequestContext,
ignore_cache: bool,
) -> Result<ResolveRouteOutput> {
tracing::debug!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
method = %req_ctx.method,
"Resolving route for request"
);
let cache_key = (self.cache_key_fn)(req_ctx)?;
// Check cache first
let cache_res = if !ignore_cache {
self.route_cache.get(&cache_key).await
} else {
None
};
let res = if let Some(res) = cache_res {
res
} else {
// Not in cache, call routing function with a configured backstop timeout.
// Primary timeout signals live in per-phase fences inside each routing module.
let route_timeout = self.config.guard().route_timeout();
tracing::debug!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
cache_hit = false,
timeout_seconds = route_timeout.as_secs(),
"Cache miss, calling routing function"
);
let routing_res = timeout(route_timeout, (self.routing_fn)(req_ctx))
.await
.map_err(|_| {
errors::RequestTimeout {
phase: "route_resolution".to_owned(),
timeout_seconds: route_timeout.as_secs(),
}
.build()
})??;
// TODO: Disable route caching for now, determine edge cases with gateway
// // Cache the result
// self.route_cache
// .insert(cache_key, routing_res.clone())
// .await;
// tracing::debug!("Added route to cache");
routing_res
};
match res {
RoutingOutput::Route(result) => {
tracing::debug!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
targets_count = result.targets.len(),
"Received routing result"
);
// Choose a random target
if let Some(target) = choose_random_target(&result.targets) {
tracing::debug!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
target_host = %target.host,
target_port = target.port,
target_path = %target.path,
"Selected target for request"
);
Ok(ResolveRouteOutput::Target(target.clone()))
} else {
tracing::warn!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
"No route targets available from result"
);
Err(errors::NoRouteTargets {
hostname: req_ctx.hostname.clone(),
path: req_ctx.path.clone(),
}
.build())
}
}
RoutingOutput::CustomServe(handler) => {
tracing::debug!(
hostname = %req_ctx.hostname,
path = %req_ctx.path,
"Routing returned custom serve handler"
);
Ok(ResolveRouteOutput::CustomServe(handler))
}
}
}
/// Returns true if the rate limit was hit.
#[tracing::instrument(skip_all)]
async fn check_rate_limit(&self, req_ctx: &RequestContext) -> Result<bool> {
// Get existing limiter or create a new one
let limiter_arc =
if let Some(existing_limiter) = self.rate_limiters.get(&req_ctx.client_ip).await {
existing_limiter
} else {
let new_limiter = Arc::new(Mutex::new(rivet_util::throttle::RateLimiter::new(
rivet_util::throttle::RateLimitMethod::FixedWindow {
requests: req_ctx.rate_limit.requests,
period: Duration::from_secs(req_ctx.rate_limit.period),
},
)));
self.rate_limiters
.insert(req_ctx.client_ip, new_limiter.clone())
.await;
metrics::RATE_LIMITER_COUNT.set(self.rate_limiters.entry_count() as i64);
new_limiter
};
// Try to acquire from the limiter
let acquired = {
let mut limiter = limiter_arc.lock().await;
limiter.try_acquire()
};
Ok(!acquired)
}
/// Returns true if the counter could not be acquired.
#[tracing::instrument(skip_all)]
async fn acquire_in_flight(&self, req_ctx: &mut RequestContext) -> Result<bool> {
let cache_key = req_ctx.client_ip;
// Get existing counter or create a new one
let counter_arc =
if let Some(existing_counter) = self.in_flight_counters.get(&cache_key).await {
existing_counter
} else {
let new_counter = Arc::new(Mutex::new(InFlightCounter::new(
req_ctx.max_in_flight.amount,
)));
self.in_flight_counters
.insert(cache_key, new_counter.clone())
.await;
metrics::IN_FLIGHT_COUNTER_COUNT.set(self.in_flight_counters.entry_count() as i64);
new_counter
};
// Try to acquire from the counter
let acquired = {
let mut counter = counter_arc.lock().await;
counter.try_acquire()
};
if !acquired {
return Ok(true); // Rate limited
}
// Generate unique request ID
req_ctx.in_flight_request_id = Some(self.generate_unique_in_flight_request_id().await?);
Ok(false)
}
#[tracing::instrument(skip_all)]
async fn release_in_flight(
&self,
client_ip: IpAddr,
in_flight_request_id: Option<protocol::RequestId>,
) {
if let Some(counter_arc) = self.in_flight_counters.get(&client_ip).await {
let mut counter = counter_arc.lock().await;
counter.release();
}
if let Some(in_flight_request_id) = in_flight_request_id {
// Release request ID
self.in_flight_requests
.invalidate(&in_flight_request_id)
.await;
metrics::IN_FLIGHT_REQUEST_COUNT.set(self.in_flight_requests.entry_count() as i64);
}
}
/// Generate a unique request ID that is not currently in flight
async fn generate_unique_in_flight_request_id(&self) -> Result<protocol::RequestId> {
const MAX_TRIES: u32 = 100;
for attempt in 0..MAX_TRIES {
let request_id = protocol::util::generate_request_id();
let mut inserted = false;
// Check if this ID is already in use
self.in_flight_requests
.entry(request_id)
.or_insert_with(async {
inserted = true;
})
.await;
if inserted {
metrics::IN_FLIGHT_REQUEST_COUNT.set(self.in_flight_requests.entry_count() as i64);
return Ok(request_id);
}
// Collision occurred (extremely rare with 4 bytes = 4 billion possibilities)
// Generate a new ID and try again
tracing::warn!(
?request_id,
attempt,
"request id collision, generating new id"
);
}
bail!(
"failed to generate unique request id after {} attempts",
MAX_TRIES
);
}
}
// Helper function to choose a random target from a list of targets
fn choose_random_target(targets: &[RouteTarget]) -> Option<&RouteTarget> {
targets.choose(&mut rand::thread_rng())
}
// Proxy service
pub struct ProxyService {
state: Arc<ProxyState>,
remote_addr: SocketAddr,
connection_start: Instant,
}
impl ProxyService {
pub fn new(state: Arc<ProxyState>, remote_addr: SocketAddr) -> Self {
Self {
state,
remote_addr,
connection_start: Instant::now(),
}
}
/// Process an individual request.
#[tracing::instrument(name = "guard_request", skip_all, fields(ray_id, req_id, uri=%req.uri()))]
pub async fn process(&self, mut req: Request<BodyIncoming>) -> Result<Response<ResponseBody>> {
let start_time = Instant::now();
let request_ids = RequestIds::new(self.state.config.dc_label());
req.extensions_mut().insert(request_ids);
let current_span = tracing::Span::current();
// Extract trace context from incoming request headers and use it as the parent of
// the current span, then inject the current span's context back into the request
// headers so upstream services see this request as a child of the current span.
// The injected headers ride along via `req_ctx.headers` into both the HTTP and
// WebSocket upstream paths.
if self.state.config.guard().trace_propagation() {
let parent_ctx = opentelemetry::global::get_text_map_propagator(|prop| {
prop.extract(&HeaderExtractor(req.headers()))
});
current_span.set_parent(parent_ctx);
let span_ctx = current_span.context();
opentelemetry::global::get_text_map_propagator(|prop| {
prop.inject_context(&span_ctx, &mut HeaderInjector(req.headers_mut()))
});
}
current_span.record("req_id", request_ids.req_id.to_string());
current_span.record("ray_id", request_ids.ray_id.to_string());
// Extract request information for logging and analytics before consuming the request
let incoming_ray_id = req
.headers()
.get(X_RIVET_RAY_ID)
.and_then(|h| h.to_str().ok())
.and_then(|id| Id::parse(id).ok());
let host = req
.headers()
.get(hyper::header::HOST)
.and_then(|h| h.to_str().ok())
.unwrap_or("unknown")
.to_string();
let uri_string = req.uri().to_string();
let path = req
.uri()
.path_and_query()
.map(|x| x.to_string())
.unwrap_or_else(|| req.uri().path().to_string());
let method = req.method().clone();
current_span.set_attribute("http.request.method", method.to_string());
current_span.set_attribute("http.path", uri_string.clone());
let user_agent = req
.headers()
.get(hyper::header::USER_AGENT)
.and_then(|h| h.to_str().ok())
.map(|s| s.to_string());
// Extract IP address from X-Forwarded-For header or fall back to remote_addr
let client_ip = req
.headers()
.get(X_FORWARDED_FOR)
.and_then(|h| h.to_str().ok())
.and_then(|forwarded| {
// X-Forwarded-For can be a comma-separated list, take the first IP
forwarded.split(',').next().map(|s| s.trim())
})
.and_then(|ip_str| ip_str.parse::<std::net::IpAddr>().ok())
.unwrap_or_else(|| self.remote_addr.ip());
let is_websocket = hyper_tungstenite::is_upgrade_request(&req);
let mut req_ctx = RequestContext::new(
self.remote_addr,
request_ids.ray_id,
request_ids.req_id,
host,
path,
req.method().clone(),
req.headers().clone(),
is_websocket,
client_ip,
start_time,
);
// TLS information would be set here if available (for HTTPS connections)
// This requires TLS connection introspection and is marked for future enhancement
// Debug log request information with structured fields (Apache-like access log)
tracing::debug!(
?incoming_ray_id,
ray_id=?req_ctx.ray_id,
req_id=?req_ctx.req_id,
method=%req_ctx.method,
path=%req_ctx.path,
host=%req_ctx.host,
remote_addr=%req_ctx.remote_addr,
uri=%uri_string,
user_agent=?user_agent,
"Request received"
);
// Used for ws error proxying later
let mut mock_req_builder = Request::builder()
.method(req.method().clone())
.uri(req.uri().clone())
.version(req.version().clone());
if let Some(headers) = mock_req_builder.headers_mut() {
*headers = req.headers().clone();
}
if let Some(extensions) = mock_req_builder.extensions_mut() {
*extensions = req.extensions().clone();
}
let mock_req = mock_req_builder.body(())?;
// Process the request
let mut res = match self.handle_request(req, &mut req_ctx).await {
Ok(res) => res,
Err(err) => {
// Log the error
tracing::error!(?err, "Request failed");
metrics::PROXY_REQUEST_ERROR_TOTAL
.with_label_values(&[&err.to_string()])
.inc();
// If we receive an error during a websocket request, we attempt to open the websocket anyway
// so we can send the error via websocket instead of http. Most websocket clients don't handle
// HTTP errors in a meaningful way resulting in unhelpful errors for the user
if is_websocket {
tracing::debug!("Upgrading client connection to WebSocket for error proxy");
match hyper_tungstenite::upgrade(mock_req, None) {
Ok((client_response, client_ws)) => {
tracing::debug!("Client WebSocket upgrade for error proxy successful");
self.state.tasks.spawn(
async move {
let ws_handle = match WebSocketHandle::new(client_ws).await {
Ok(ws_handle) => ws_handle,
Err(err) => {
tracing::debug!(
?err,
"failed initiating websocket handle for error proxy"
);
return;
}
};
let frame = utils::err_to_close_frame(err, request_ids.ray_id);
// Manual conversion to handle different tungstenite versions
let code_num: u16 = frame.code.into();
let reason = frame.reason.clone();
if let Err(err) = ws_handle
.send(tokio_tungstenite::tungstenite::Message::Close(Some(
tokio_tungstenite::tungstenite::protocol::CloseFrame {
code: code_num.into(),
reason,
},
)))
.await
{
tracing::debug!(
?err,
"failed sending websocket error proxy"
);
}
// Flush to ensure close frame is sent
if let Err(err) = ws_handle.flush().await {
tracing::debug!(
?err,
"failed flushing websocket in error proxy"
);
}
// Keep TCP connection open briefly to allow client to process close
tokio::time::sleep(WEBSOCKET_CLOSE_LINGER).await;
}
.instrument(tracing::info_span!("ws_error_proxy_task")),
);
// Return the response that will upgrade the client connection
// For proper WebSocket handshaking, we need to preserve the original response
// structure but convert it to our expected return type without modifying its content
tracing::debug!(
"Returning WebSocket upgrade response for error proxy to client"
);
// Extract the parts from the response but preserve all headers and status
let (mut parts, _) = client_response.into_parts();
// Add Sec-WebSocket-Protocol header to the response
// Many WebSocket clients (e.g. node-ws & Cloudflare) require a protocol in the response
parts.headers.insert(
"sec-websocket-protocol",
hyper::header::HeaderValue::from_static("rivet"),
);
// Create a new response with an empty body - WebSocket upgrades don't need a body
Response::from_parts(
parts,
ResponseBody::Full(Full::<Bytes>::new(Bytes::new())),
)
}
Err(err) => {
tracing::error!(
?err,
"Failed to upgrade client WebSocket for error proxy"
);
utils::err_into_response(
errors::ConnectionError {
error_message: format!(
"Failed to upgrade client WebSocket for error proxy: {}",
err
),
remote_addr: req_ctx.remote_addr.to_string(),
}
.build(),
)?
}
}
} else {
utils::err_into_response(err)?
}
}
};
if is_websocket && res.status() != StatusCode::SWITCHING_PROTOCOLS {
tracing::debug!("returned non-101 response to websocket");
}
// Add ray_id to response headers
if let Ok(ray_id_value) = request_ids.ray_id.to_string().parse() {
if let Some(existing_ray_id_value) = res
.headers()
.get(X_RIVET_RAY_ID)
.and_then(|h| h.to_str().ok())
{
if ray_id_value != existing_ray_id_value {
tracing::warn!(
expected_ray_id=%request_ids.ray_id,
received_ray_id=%existing_ray_id_value,
"downstream service set ray id header to a different value",
);
}
}
res.headers_mut().insert(X_RIVET_RAY_ID, ray_id_value);
}
// Add cors headers to response
if let Some(cors) = &req_ctx.cors {
let headers = res.headers_mut();
headers.insert(
"access-control-allow-origin",
HeaderValue::from_str(&cors.allow_origin)?,
);
headers.insert(
"access-control-allow-credentials",
HeaderValue::from_static(if cors.allow_credentials {
"true"
} else {
"false"
}),
);
headers.insert(
"access-control-expose-headers",
HeaderValue::from_str(&cors.expose_headers)?,
);
if let Some(allow_methods) = &cors.allow_methods {
headers.insert(
"access-control-allow-methods",
HeaderValue::from_str(allow_methods)?,
);
}
if let Some(allow_headers) = &cors.allow_headers {
headers.insert(
"access-control-allow-headers",
HeaderValue::from_str(allow_headers)?,
);
}
if let Some(max_age) = &cors.max_age {
headers.insert(
"access-control-max-age",
HeaderValue::from_str(&max_age.to_string())?,
);
}
// Add Vary header to prevent cache poisoning when echoing origin
if cors.allow_origin != "*" {
headers.insert("vary", HeaderValue::from_static("Origin"));
}
}
// Set span status code
let status = res.status().as_u16();
current_span.set_attribute("http.response.status_code", status as i64);
let content_length = res
.headers()
.get(hyper::header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<usize>().ok())
.unwrap_or(0);
// Log information about the completed request
tracing::debug!(
?incoming_ray_id,
ray_id=?req_ctx.ray_id,
req_id=?req_ctx.req_id,
method = %req_ctx.method,
path = %req_ctx.path,
host = %req_ctx.host,
remote_addr = %req_ctx.remote_addr,
status = %status,
content_length = %content_length,
"Request completed"
);
Ok(res)
}
#[tracing::instrument(skip_all)]
async fn handle_request(
&self,
req: Request<BodyIncoming>,
req_ctx: &mut RequestContext,
) -> Result<Response<ResponseBody>> {
// Resolve target
let target_res = self.state.resolve_route(req_ctx, false).await;
let duration_secs = req_ctx.start_time.elapsed().as_secs_f64();
metrics::RESOLVE_ROUTE_DURATION.observe(duration_secs);
let target = target_res?;
// Apply rate limiting
if self.state.check_rate_limit(req_ctx).await? {
return Err(errors::RateLimit {
method: req_ctx.method.to_string(),
path: req_ctx.path.clone(),
ip: req_ctx.client_ip.to_string(),
}
.build());
}
// Acquire in-flight limit and generate protocol request ID
if self.state.acquire_in_flight(req_ctx).await? {
return Err(errors::RateLimit {
method: req_ctx.method.to_string(),
path: req_ctx.path.clone(),
ip: req_ctx.client_ip.to_string(),
}
.build());
}
// Increment metrics
metrics::PROXY_REQUEST_PENDING.inc();
metrics::PROXY_REQUEST_TOTAL.inc();
let res = if hyper_tungstenite::is_upgrade_request(&req) {
self.handle_websocket_upgrade(req, req_ctx, target).await
} else {
self.handle_http_request(req, req_ctx, target).await
};
let status = match &res {
Ok(resp) => resp.status().as_u16().to_string(),
Err(_) => "error".to_string(),
};
// Record metrics
let duration_secs = req_ctx.start_time.elapsed().as_secs_f64();
metrics::PROXY_REQUEST_DURATION
.with_label_values(&[status])
.observe(duration_secs);
metrics::PROXY_REQUEST_PENDING.dec();
// Release in-flight counter and request ID when done
let state_clone = self.state.clone();
let client_ip = req_ctx.client_ip;
let in_flight_request_id = req_ctx.in_flight_request_id;
tokio::spawn(
async move {
state_clone
.release_in_flight(client_ip, in_flight_request_id)
.await;
}
.instrument(tracing::info_span!("release_in_flight_task")),
);
res
}
#[tracing::instrument(skip_all)]
async fn handle_http_request(
&self,
req: Request<BodyIncoming>,
req_ctx: &mut RequestContext,
resolved_route: ResolveRouteOutput,
) -> Result<Response<ResponseBody>> {
// Set up retry with backoff
let timeout_duration = Duration::from_secs(req_ctx.timeout.request_timeout);
match resolved_route {
ResolveRouteOutput::Target(mut target) => {
// Read the request body before proceeding with retries
let (req_parts, body) = req.into_parts();
let req_body =
Limited::new(body, self.state.config.guard().http_max_request_body_size())
.collect()
.await
.map_err(|err| {
errors::InvalidRequestBody {
reason: err.to_string(),
}
.build()
})?
.to_bytes();
// Use a value-returning loop to handle both errors and successful responses
let mut attempts = 0;
let mut last_status = "none".to_owned();
let mut last_error_code = "none".to_owned();
while attempts < req_ctx.retry.max_attempts {
attempts += 1;
// Use the common function to build request parts
let builder = utils::proxied_request_builder(&req_parts, req_ctx, &target)
.map_err(|err| errors::HttpRequestBuildFailed(err.to_string()).build())?;
// Create the final request with body
let proxied_req = builder
// NOTE: the `Bytes` type is cheaply cloneable, this is not resource intensive
.body(Full::new(req_body.clone()))
.map_err(|err| errors::RequestBuildError(err.to_string()).build())?;
// Send the request with timeout
let res = timeout(timeout_duration, self.state.client.request(proxied_req))
.await
.map_err(|_| {
errors::RequestTimeout {
phase: "upstream_request".to_owned(),
timeout_seconds: timeout_duration.as_secs(),
}
.build()
})?;
match res {
Ok(resp) => {
// Check if this is a retryable response
if utils::should_retry_request_inner(resp.status(), resp.headers()) {
last_status = resp.status().as_u16().to_string();
last_error_code = resp
.headers()
.get(X_RIVET_ERROR)
.and_then(|value| value.to_str().ok())
.unwrap_or("retryable_status")
.to_owned();
// Request connect error, might retry
tracing::debug!(
"Request attempt {attempts} failed (service unavailable)"
);
// Use backoff and continue
let backoff = utils::calculate_backoff(
attempts,
req_ctx.retry.initial_interval,
);
tokio::time::sleep(backoff).await;
// Resolve target again, this time ignoring cache. This makes sure
// we always re-fetch the route on error
let ResolveRouteOutput::Target(new_target) =
self.state.resolve_route(req_ctx, true).await?
else {
bail!("resolved route does not match Target");
};
target = new_target;
continue;
}
let (parts, body) = resp.into_parts();
// Check if this is a streaming response by examining headers
// let is_streaming = parts.headers.get("content-type")
// .and_then(|ct| ct.to_str().ok())
// .map(|ct| ct.contains("text/event-stream") || ct.contains("application/stream"))
// .unwrap_or(false);
let is_streaming = true;
if is_streaming {
// For streaming responses, pass through the body without buffering
tracing::debug!("Detected streaming response, preserving stream");
let streaming_body = ResponseBody::Incoming(body);
return Ok(Response::from_parts(parts, streaming_body));
} else {
// For non-streaming responses, buffer as before
let body_bytes = Limited::new(
body,
self.state.config.guard().http_max_request_body_size(),
)
.collect()
.await
.map_err(|err| {
errors::InvalidResponseBody {
reason: err.to_string(),
}
.build()
})?
.to_bytes();
let full_body = ResponseBody::Full(Full::new(body_bytes));
return Ok(Response::from_parts(parts, full_body));
}
}
Err(err) => {
if !err.is_connect() || attempts >= req_ctx.retry.max_attempts {
tracing::error!(
?err,
?target,
"Request error after {} attempts",
attempts
);
return Err(errors::UpstreamError(format!(
"Failed to connect to runner: {err}. Make sure your runners are healthy."
))
.build());
} else {
// Request connect error, might retry
tracing::debug!(?err, "Request attempt {attempts} failed");
// Use backoff and continue
let backoff = utils::calculate_backoff(
attempts,
req_ctx.retry.initial_interval,
);
tokio::time::sleep(backoff).await;
// Resolve target again, this time ignoring cache. This makes sure
// we always re-fetch the route on error
let ResolveRouteOutput::Target(new_target) =
self.state.resolve_route(req_ctx, true).await?
else {
bail!("resolved route does not match Target");
};
target = new_target;
continue;
}
}
}
}
// If we get here, all attempts failed
return Err(errors::RetryAttemptsExceeded {
attempts: req_ctx.retry.max_attempts,
last_error_code,
last_status,
last_target_kind: "target".to_owned(),
}
.build());
}
ResolveRouteOutput::CustomServe(mut handler) => {
// Collect request body
let (req_parts, body) = req.into_parts();
let req_body =
Limited::new(body, self.state.config.guard().http_max_request_body_size())
.collect()
.await
.map_err(|err| {
errors::InvalidRequestBody {
reason: err.to_string(),
}
.build()
})?
.to_bytes();
let req_collected =
hyper::Request::from_parts(req_parts, Full::<Bytes>::new(req_body));
// Attempt request
let mut attempts = 0;
let mut last_status = "none".to_owned();
let mut last_error_code = "none".to_owned();
while attempts < req_ctx.retry.max_attempts {
attempts += 1;
let res = handler.handle_request(req_collected.clone(), req_ctx).await;
if utils::should_retry_request(&res) {
match &res {
Ok(resp) => {
last_status = resp.status().as_u16().to_string();
last_error_code = resp
.headers()
.get(X_RIVET_ERROR)
.and_then(|value| value.to_str().ok())
.unwrap_or("retryable_status")
.to_owned();
}
Err(err) => {
last_status = "none".to_owned();
last_error_code = err
.chain()
.find_map(|x| x.downcast_ref::<rivet_error::RivetError>())
.map(|rivet_err| {
format!("{}.{}", rivet_err.group(), rivet_err.code())
})
.unwrap_or_else(|| "unknown".to_owned());
}
}
// Request connect error, might retry
tracing::debug!("Request attempt {attempts} failed (service unavailable)");
// Use backoff and continue
let backoff =
utils::calculate_backoff(attempts, req_ctx.retry.initial_interval);
tokio::time::sleep(backoff).await;
// Refresh route (ignore cache) so subsequent requests can hit new target
let ResolveRouteOutput::CustomServe(new_handler) =
self.state.resolve_route(req_ctx, true).await?
else {
bail!("resolved route does not match CustomServe");
};
handler = new_handler;
continue;
}
// Release in-flight counter and request ID before returning
self.state
.release_in_flight(req_ctx.client_ip, req_ctx.in_flight_request_id)
.await;