-
Notifications
You must be signed in to change notification settings - Fork 244
/
subgraph_service.rs
2382 lines (2184 loc) 路 93.6 KB
/
subgraph_service.rs
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
//! Tower fetcher for subgraphs.
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
use std::sync::Arc;
use std::task::Poll;
use bytes::Bytes;
use futures::future::BoxFuture;
use futures::SinkExt;
use futures::StreamExt;
use futures::TryFutureExt;
use http::header::ACCEPT;
use http::header::CONTENT_TYPE;
use http::header::{self};
use http::response::Parts;
use http::HeaderValue;
use http::Request;
use hyper::Body;
use hyper_rustls::ConfigBuilderExt;
use mediatype::names::APPLICATION;
use mediatype::names::JSON;
use mediatype::MediaType;
use mime::APPLICATION_JSON;
use rustls::RootCertStore;
use serde::Serialize;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::connect_async_tls_with_config;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tower::util::BoxService;
use tower::BoxError;
use tower::Service;
use tower::ServiceExt;
use tracing::Instrument;
use uuid::Uuid;
use super::http::HttpClientServiceFactory;
use super::http::HttpRequest;
use super::layers::content_negotiation::GRAPHQL_JSON_RESPONSE_HEADER_VALUE;
use super::Plugins;
use crate::configuration::TlsClientAuth;
use crate::error::FetchError;
use crate::graphql;
use crate::json_ext::Object;
use crate::plugins::authentication::subgraph::SigningParamsConfig;
use crate::plugins::file_uploads;
use crate::plugins::subscription::create_verifier;
use crate::plugins::subscription::CallbackMode;
use crate::plugins::subscription::SubscriptionConfig;
use crate::plugins::subscription::SubscriptionMode;
use crate::plugins::subscription::WebSocketConfiguration;
use crate::plugins::subscription::SUBSCRIPTION_WS_CUSTOM_CONNECTION_PARAMS;
use crate::plugins::telemetry::LOGGING_DISPLAY_BODY;
use crate::plugins::telemetry::LOGGING_DISPLAY_HEADERS;
use crate::protocols::websocket::convert_websocket_stream;
use crate::protocols::websocket::GraphqlWebSocket;
use crate::query_planner::OperationKind;
use crate::services::layers::apq;
use crate::services::SubgraphRequest;
use crate::services::SubgraphResponse;
use crate::Configuration;
use crate::Context;
use crate::Notify;
const PERSISTED_QUERY_NOT_FOUND_EXTENSION_CODE: &str = "PERSISTED_QUERY_NOT_FOUND";
const PERSISTED_QUERY_NOT_SUPPORTED_EXTENSION_CODE: &str = "PERSISTED_QUERY_NOT_SUPPORTED";
const PERSISTED_QUERY_NOT_FOUND_MESSAGE: &str = "PersistedQueryNotFound";
const PERSISTED_QUERY_NOT_SUPPORTED_MESSAGE: &str = "PersistedQueryNotSupported";
const CODE_STRING: &str = "code";
const PERSISTED_QUERY_KEY: &str = "persistedQuery";
const HASH_VERSION_KEY: &str = "version";
const HASH_VERSION_VALUE: i32 = 1;
const HASH_KEY: &str = "sha256Hash";
const GRAPHQL_RESPONSE: mediatype::Name = mediatype::Name::new_unchecked("graphql-response");
#[allow(clippy::declare_interior_mutable_const)]
static CALLBACK_PROTOCOL_ACCEPT: HeaderValue =
HeaderValue::from_static("application/json;callbackSpec=1.0");
pub(crate) static APPLICATION_JSON_HEADER_VALUE: HeaderValue =
HeaderValue::from_static("application/json");
static ACCEPT_GRAPHQL_JSON: HeaderValue =
HeaderValue::from_static("application/json, application/graphql-response+json");
enum APQError {
PersistedQueryNotSupported,
PersistedQueryNotFound,
Other,
}
#[cfg_attr(test, derive(serde::Deserialize))]
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
struct SubscriptionExtension {
subscription_id: String,
callback_url: url::Url,
verifier: String,
heartbeat_interval_ms: u64,
}
/// Client for interacting with subgraphs.
#[derive(Clone)]
pub(crate) struct SubgraphService {
// we hold a HTTP client service factory here because a service with plugins applied
// cannot be cloned
pub(crate) client_factory: HttpClientServiceFactory,
service: Arc<String>,
/// Whether apq is enabled in the router for subgraph calls
/// This is enabled by default can be configured as
/// subgraph:
/// apq: <bool>
/// If a subgraph sends the error message PERSISTED_QUERY_NOT_SUPPORTED,
/// apq is set to false
apq: Arc<AtomicBool>,
/// Subscription config if enabled
subscription_config: Option<SubscriptionConfig>,
notify: Notify<String, graphql::Response>,
}
impl SubgraphService {
pub(crate) fn from_config(
service: impl Into<String>,
configuration: &Configuration,
subscription_config: Option<SubscriptionConfig>,
client_factory: crate::services::http::HttpClientServiceFactory,
) -> Result<Self, BoxError> {
let name: String = service.into();
let enable_apq = configuration
.apq
.subgraph
.subgraphs
.get(&name)
.map(|apq| apq.enabled)
.unwrap_or(configuration.apq.subgraph.all.enabled);
SubgraphService::new(
name,
enable_apq,
subscription_config,
configuration.notify.clone(),
client_factory,
)
}
pub(crate) fn new(
service: impl Into<String>,
enable_apq: bool,
subscription_config: Option<SubscriptionConfig>,
notify: Notify<String, graphql::Response>,
client_factory: crate::services::http::HttpClientServiceFactory,
) -> Result<Self, BoxError> {
Ok(Self {
client_factory,
service: Arc::new(service.into()),
apq: Arc::new(<AtomicBool>::new(enable_apq)),
subscription_config,
notify,
})
}
}
pub(crate) fn generate_tls_client_config(
tls_cert_store: Option<RootCertStore>,
client_cert_config: Option<&TlsClientAuth>,
) -> Result<rustls::ClientConfig, BoxError> {
let tls_builder = rustls::ClientConfig::builder().with_safe_defaults();
Ok(match (tls_cert_store, client_cert_config) {
(None, None) => tls_builder.with_native_roots().with_no_client_auth(),
(Some(store), None) => tls_builder
.with_root_certificates(store)
.with_no_client_auth(),
(None, Some(client_auth_config)) => tls_builder.with_native_roots().with_client_auth_cert(
client_auth_config.certificate_chain.clone(),
client_auth_config.key.clone(),
)?,
(Some(store), Some(client_auth_config)) => tls_builder
.with_root_certificates(store)
.with_client_auth_cert(
client_auth_config.certificate_chain.clone(),
client_auth_config.key.clone(),
)?,
})
}
impl tower::Service<SubgraphRequest> for SubgraphService {
type Response = SubgraphResponse;
type Error = BoxError;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut request: SubgraphRequest) -> Self::Future {
let subscription_config = (request.operation_kind == OperationKind::Subscription)
.then(|| self.subscription_config.clone())
.flatten();
let service_name = (*self.service).to_owned();
// Do it only for subscription to dedup them
let hashed_request = if request.operation_kind == OperationKind::Subscription {
let subscription_config = match &subscription_config {
Some(sub_cfg) => sub_cfg,
None => {
return Box::pin(async move {
Err(BoxError::from(FetchError::SubrequestWsError {
service: service_name,
reason: "subscription is not enabled".to_string(),
}))
});
}
};
if subscription_config.enable_deduplication {
request.to_sha256()
} else {
Uuid::new_v4().to_string()
}
} else {
String::new()
};
let SubgraphRequest {
subgraph_request,
context,
..
} = request.clone();
let (_, mut body) = subgraph_request.into_parts();
let client_factory = self.client_factory.clone();
let arc_apq_enabled = self.apq.clone();
let mut notify = self.notify.clone();
let make_calls = async move {
// Subscription handling
if request.operation_kind == OperationKind::Subscription
&& request.subscription_stream.is_some()
{
let subscription_config =
subscription_config.ok_or_else(|| FetchError::SubrequestHttpError {
service: service_name.clone(),
reason: "subscription is not enabled".to_string(),
status_code: None,
})?;
let mode = subscription_config.mode.get_subgraph_config(&service_name);
match &mode {
Some(SubscriptionMode::Passthrough(ws_conf)) => {
// call_websocket for passthrough mode
return call_websocket(
notify,
request,
context,
service_name,
ws_conf,
hashed_request,
)
.await;
}
Some(SubscriptionMode::Callback(CallbackMode {
public_url,
heartbeat_interval,
..
})) => {
// Hash the subgraph_request
let subscription_id = hashed_request;
// Call create_or_subscribe on notify
let (handle, created) = notify
.create_or_subscribe(subscription_id.clone(), true)
.await?;
// If it existed before just send the right stream (handle) and early return
let stream_tx = request.subscription_stream.clone().ok_or_else(|| {
FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot get the callback stream".to_string(),
}
})?;
stream_tx.send(Box::pin(handle.into_stream())).await?;
tracing::info!(
monotonic_counter.apollo.router.operations.subscriptions = 1u64,
subscriptions.mode = %"callback",
subscriptions.deduplicated = !created,
subgraph.service.name = service_name,
);
if !created {
tracing::info!(
monotonic_counter.apollo_router_deduplicated_subscriptions_total = 1u64,
mode = %"callback",
);
// Dedup happens here
return Ok(SubgraphResponse::builder()
.context(context)
.extensions(Object::default())
.build());
}
// If not then put the subscription_id in the extensions for callback mode and continue
// Do this if the topic doesn't already exist
let mut callback_url = public_url.clone();
if callback_url.path_segments_mut().is_err() {
callback_url = callback_url.join(&subscription_id)?;
} else {
callback_url
.path_segments_mut()
.expect("can't happen because we checked before")
.push(&subscription_id);
}
// Generate verifier
let verifier = create_verifier(&subscription_id).map_err(|err| {
FetchError::SubrequestHttpError {
service: service_name.clone(),
reason: format!("{err:?}"),
status_code: None,
}
})?;
request
.subgraph_request
.headers_mut()
.append(ACCEPT, CALLBACK_PROTOCOL_ACCEPT.clone());
let subscription_extension = SubscriptionExtension {
subscription_id,
callback_url,
verifier,
heartbeat_interval_ms: heartbeat_interval
.into_option()
.map(|duration| duration.as_millis() as u64)
.unwrap_or(0),
};
body.extensions.insert(
"subscription",
serde_json_bytes::to_value(subscription_extension).map_err(|err| {
FetchError::SubrequestHttpError {
service: service_name.clone(),
reason: format!(
"cannot serialize the subscription extension: {err:?}",
),
status_code: None,
}
})?,
);
}
_ => {
return Err(Box::new(FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "subscription mode is not enabled".to_string(),
}));
}
}
}
let client = client_factory.create(&service_name);
// If APQ is not enabled, simply make the graphql call
// with the same request body.
let apq_enabled = arc_apq_enabled.as_ref();
if !apq_enabled.load(Relaxed) {
return call_http(request, body, context, client, &service_name).await;
}
// Else, if APQ is enabled,
// Calculate the query hash and try the request with
// a persistedQuery instead of the whole query.
let graphql::Request {
query,
operation_name,
variables,
extensions,
} = body.clone();
let hash_value = apq::calculate_hash_for_query(query.as_deref().unwrap_or_default());
let persisted_query = serde_json_bytes::json!({
HASH_VERSION_KEY: HASH_VERSION_VALUE,
HASH_KEY: hash_value
});
let mut extensions_with_apq = extensions.clone();
extensions_with_apq.insert(PERSISTED_QUERY_KEY, persisted_query);
let mut apq_body = graphql::Request {
query: None,
operation_name,
variables,
extensions: extensions_with_apq,
};
let response = call_http(
request.clone(),
apq_body.clone(),
context.clone(),
client_factory.create(&service_name),
&service_name,
)
.await?;
// Check the error for the request with only persistedQuery.
// If PersistedQueryNotSupported, disable APQ for this subgraph
// If PersistedQueryNotFound, add the original query to the request and retry.
// Else, return the response like before.
let gql_response = response.response.body();
match get_apq_error(gql_response) {
APQError::PersistedQueryNotSupported => {
apq_enabled.store(false, Relaxed);
call_http(request, body, context, client, &service_name).await
}
APQError::PersistedQueryNotFound => {
apq_body.query = query;
call_http(request, apq_body, context, client, &service_name).await
}
_ => Ok(response),
}
};
Box::pin(make_calls)
}
}
/// call websocket makes websocket calls with modified graphql::Request (body)
async fn call_websocket(
mut notify: Notify<String, graphql::Response>,
request: SubgraphRequest,
context: Context,
service_name: String,
subgraph_cfg: &WebSocketConfiguration,
subscription_hash: String,
) -> Result<SubgraphResponse, BoxError> {
let operation_name = request
.subgraph_request
.body()
.operation_name
.clone()
.unwrap_or_default();
let SubgraphRequest {
subgraph_request,
subscription_stream,
..
} = request;
let subscription_stream_tx =
subscription_stream.ok_or_else(|| FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot get the websocket stream".to_string(),
})?;
let (handle, created) = notify
.create_or_subscribe(subscription_hash.clone(), false)
.await?;
tracing::info!(
monotonic_counter.apollo.router.operations.subscriptions = 1u64,
subscriptions.mode = %"passthrough",
subscriptions.deduplicated = !created,
subgraph.service.name = service_name,
);
if !created {
subscription_stream_tx
.send(Box::pin(handle.into_stream()))
.await?;
tracing::info!(
monotonic_counter.apollo_router_deduplicated_subscriptions_total = 1u64,
mode = %"passthrough",
);
// Dedup happens here
return Ok(SubgraphResponse::builder()
.context(context)
.extensions(Object::default())
.build());
}
let (parts, body) = subgraph_request.into_parts();
// Check context key and Authorization header (context key takes precedence) to set connection params if needed
let connection_params = match (
context.get_json_value(SUBSCRIPTION_WS_CUSTOM_CONNECTION_PARAMS),
parts
.headers
.get(http::header::AUTHORIZATION)
.and_then(|auth| auth.to_str().ok()),
) {
(Some(connection_params), _) => Some(connection_params),
(None, Some(authorization)) => Some(serde_json_bytes::json!({ "token": authorization })),
_ => None,
};
let request = get_websocket_request(service_name.clone(), parts, subgraph_cfg)?;
let display_headers = context.contains_key(LOGGING_DISPLAY_HEADERS);
let display_body = context.contains_key(LOGGING_DISPLAY_BODY);
let signing_params = context
.extensions()
.lock()
.get::<SigningParamsConfig>()
.cloned();
let request = if let Some(signing_params) = signing_params {
signing_params
.sign_empty(request, service_name.as_str())
.await?
} else {
request
};
if display_headers {
tracing::info!(http.request.headers = ?request.headers(), apollo.subgraph.name = %service_name, "Websocket request headers to subgraph {service_name:?}");
}
if display_body {
tracing::info!(http.request.body = ?request.body(), apollo.subgraph.name = %service_name, "Websocket request body to subgraph {service_name:?}");
}
let uri = request.uri();
let path = uri.path();
let host = uri.host().unwrap_or_default();
let port = uri.port_u16().unwrap_or_else(|| {
let scheme = uri.scheme_str();
if scheme == Some("wss") {
443
} else if scheme == Some("ws") {
80
} else {
0
}
});
let subgraph_req_span = tracing::info_span!("subgraph_request",
"otel.kind" = "CLIENT",
"net.peer.name" = %host,
"net.peer.port" = %port,
"http.route" = %path,
"http.url" = %uri,
"net.transport" = "ip_tcp",
"apollo.subgraph.name" = %service_name,
"graphql.operation.name" = %operation_name,
);
let (ws_stream, mut resp) = match request.uri().scheme_str() {
Some("wss") => {
connect_async_tls_with_config(request, None, false, None)
.instrument(subgraph_req_span)
.await
}
_ => connect_async(request).instrument(subgraph_req_span).await,
}
.map_err(|err| {
if display_body || display_headers {
tracing::info!(
http.response.error = format!("{:?}", &err), apollo.subgraph.name = %service_name, "Websocket connection error from subgraph {service_name:?} received"
);
}
FetchError::SubrequestWsError {
service: service_name.clone(),
reason: format!("cannot connect websocket to subgraph: {err}"),
}
})?;
if display_headers {
tracing::info!(response.headers = ?resp.headers(), apollo.subgraph.name = %service_name, "Websocket response headers to subgraph {service_name:?}");
}
if display_body {
tracing::info!(
response.body = %String::from_utf8_lossy(&resp.body_mut().take().unwrap_or_default()), apollo.subgraph.name = %service_name, "Websocket response body from subgraph {service_name:?} received"
);
}
let mut gql_stream = GraphqlWebSocket::new(
convert_websocket_stream(ws_stream, subscription_hash.clone()),
subscription_hash,
subgraph_cfg.protocol,
connection_params,
subgraph_cfg.heartbeat_interval.into_option(),
)
.await
.map_err(|_| FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot get the GraphQL websocket stream".to_string(),
})?;
gql_stream
.send(body)
.await
.map_err(|err| FetchError::SubrequestWsError {
service: service_name,
reason: format!("cannot send the subgraph request to websocket stream: {err:?}"),
})?;
let (mut gql_sink, gql_stream) = gql_stream.split();
let (handle_sink, handle_stream) = handle.split();
tokio::task::spawn(async move {
let _ = gql_stream
.map(Ok::<_, graphql::Error>)
.forward(handle_sink)
.await;
if let Err(err) = gql_sink.close().await {
tracing::trace!("cannot close the websocket stream: {err:?}");
}
});
subscription_stream_tx.send(Box::pin(handle_stream)).await?;
Ok(SubgraphResponse::new_from_response(
resp.map(|_| graphql::Response::default()),
context,
))
}
/// call_http makes http calls with modified graphql::Request (body)
async fn call_http(
request: SubgraphRequest,
body: graphql::Request,
context: Context,
client: crate::services::http::BoxService,
service_name: &str,
) -> Result<SubgraphResponse, BoxError> {
let SubgraphRequest {
subgraph_request, ..
} = request;
let operation_name = subgraph_request
.body()
.operation_name
.clone()
.unwrap_or_default();
let (parts, _) = subgraph_request.into_parts();
let body = serde_json::to_string(&body).expect("JSON serialization should not fail");
let mut request = http::Request::from_parts(parts, Body::from(body));
request
.headers_mut()
.insert(CONTENT_TYPE, APPLICATION_JSON_HEADER_VALUE.clone());
request
.headers_mut()
.append(ACCEPT, ACCEPT_GRAPHQL_JSON.clone());
let schema_uri = request.uri();
let host = schema_uri.host().unwrap_or_default();
let port = schema_uri.port_u16().unwrap_or_else(|| {
let scheme = schema_uri.scheme_str();
if scheme == Some("https") {
443
} else if scheme == Some("http") {
80
} else {
0
}
});
let path = schema_uri.path();
let subgraph_req_span = tracing::info_span!("subgraph_request",
"otel.kind" = "CLIENT",
"net.peer.name" = %host,
"net.peer.port" = %port,
"http.route" = %path,
"http.url" = %schema_uri,
"net.transport" = "ip_tcp",
"apollo.subgraph.name" = %service_name,
"graphql.operation.name" = %operation_name,
);
// The graphql spec is lax about what strategy to use for processing responses: https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md#processing-the-response
//
// "If the response uses a non-200 status code and the media type of the response payload is application/json
// then the client MUST NOT rely on the body to be a well-formed GraphQL response since the source of the response
// may not be the server but instead some intermediary such as API gateways, proxies, firewalls, etc."
//
// The TLDR of this is that it's really asking us to do the best we can with whatever information we have with some modifications depending on content type.
// Our goal is to give the user the most relevant information possible in the response errors
//
// Rules:
// 1. If the content type of the response is not `application/json` or `application/graphql-response+json` then we won't try to parse.
// 2. If an HTTP status is not 2xx it will always be attached as a graphql error.
// 3. If the response type is `application/json` and status is not 2xx and the body the entire body will be output if the response is not valid graphql.
let display_body = context.contains_key(LOGGING_DISPLAY_BODY);
// TODO: Temporary solution to plug FileUploads plugin until 'http_client' will be fixed https://github.com/apollographql/router/pull/4666
let request = file_uploads::http_request_wrapper(request).await;
// Perform the actual fetch. If this fails then we didn't manage to make the call at all, so we can't do anything with it.
let (parts, content_type, body) =
do_fetch(client, &context, service_name, request, display_body)
.instrument(subgraph_req_span)
.await?;
if display_body {
if let Some(Ok(b)) = &body {
tracing::info!(
response.body = %String::from_utf8_lossy(b), apollo.subgraph.name = %service_name, "Raw response body from subgraph {service_name:?} received"
);
}
}
let mut graphql_response = match (content_type, body, parts.status.is_success()) {
(Ok(ContentType::ApplicationGraphqlResponseJson), Some(Ok(body)), _)
| (Ok(ContentType::ApplicationJson), Some(Ok(body)), true) => {
// Application graphql json expects valid graphql response
// Application json expects valid graphql response if 2xx
tracing::debug_span!("parse_subgraph_response").in_scope(|| {
// Application graphql json expects valid graphql response
graphql::Response::from_bytes(service_name, body).unwrap_or_else(|error| {
graphql::Response::builder()
.error(error.to_graphql_error(None))
.build()
})
})
}
(Ok(ContentType::ApplicationJson), Some(Ok(body)), false) => {
// Application json does not expect a valid graphql response if not 2xx.
// If parse fails then attach the entire payload as an error
tracing::debug_span!("parse_subgraph_response").in_scope(|| {
// Application graphql json expects valid graphql response
let mut original_response = String::from_utf8_lossy(&body).to_string();
if original_response.is_empty() {
original_response = "<empty response body>".into()
}
graphql::Response::from_bytes(service_name, body).unwrap_or_else(|_error| {
graphql::Response::builder()
.error(
FetchError::SubrequestMalformedResponse {
service: service_name.to_string(),
reason: original_response,
}
.to_graphql_error(None),
)
.build()
})
})
}
(content_type, body, _) => {
// Something went wrong, compose a response with errors if they are present
let mut graphql_response = graphql::Response::builder().build();
if let Err(err) = content_type {
graphql_response.errors.push(err.to_graphql_error(None));
}
if let Some(Err(err)) = body {
graphql_response.errors.push(err.to_graphql_error(None));
}
graphql_response
}
};
// Add an error for response codes that are not 2xx
if !parts.status.is_success() {
let status = parts.status;
graphql_response.errors.insert(
0,
FetchError::SubrequestHttpError {
service: service_name.to_string(),
status_code: Some(status.as_u16()),
reason: format!(
"{}: {}",
status.as_str(),
status.canonical_reason().unwrap_or("Unknown")
),
}
.to_graphql_error(None),
)
}
let resp = http::Response::from_parts(parts, graphql_response);
Ok(SubgraphResponse::new_from_response(resp, context))
}
enum ContentType {
ApplicationJson,
ApplicationGraphqlResponseJson,
}
fn get_graphql_content_type(service_name: &str, parts: &Parts) -> Result<ContentType, FetchError> {
let content_type = parts
.headers
.get(header::CONTENT_TYPE)
.map(|v| v.to_str().map(MediaType::parse));
match content_type {
Some(Ok(Ok(content_type))) => {
if content_type.ty == APPLICATION && content_type.subty == JSON {
Ok(ContentType::ApplicationJson)
} else if content_type.ty == APPLICATION
&& content_type.subty == GRAPHQL_RESPONSE
&& content_type.suffix == Some(JSON)
{
Ok(ContentType::ApplicationGraphqlResponseJson)
} else {
Err(FetchError::SubrequestHttpError {
status_code: Some(parts.status.as_u16()),
service: service_name.to_string(),
reason: format!("subgraph didn't return JSON (expected content-type: {} or content-type: {}; found content-type: {content_type})", APPLICATION_JSON.essence_str(), GRAPHQL_JSON_RESPONSE_HEADER_VALUE),
})
}
}
None | Some(_) => Err(FetchError::SubrequestHttpError {
status_code: Some(parts.status.as_u16()),
service: service_name.to_string(),
reason: format!(
"subgraph didn't return JSON (expected content-type: {} or content-type: {})",
APPLICATION_JSON.essence_str(),
GRAPHQL_JSON_RESPONSE_HEADER_VALUE
),
}),
}
}
async fn do_fetch(
mut client: crate::services::http::BoxService,
context: &Context,
service_name: &str,
request: Request<Body>,
display_body: bool,
) -> Result<
(
Parts,
Result<ContentType, FetchError>,
Option<Result<Bytes, FetchError>>,
),
FetchError,
> {
let _active_request_guard = context.enter_active_request();
let response = client
.call(HttpRequest {
http_request: request,
context: context.clone(),
})
.map_err(|err| {
tracing::error!(fetch_error = ?err);
FetchError::SubrequestHttpError {
status_code: None,
service: service_name.to_string(),
reason: err.to_string(),
}
})
.await?;
let (parts, body) = response.http_response.into_parts();
let content_type = get_graphql_content_type(service_name, &parts);
let body = if content_type.is_ok() {
let body = hyper::body::to_bytes(body)
.instrument(tracing::debug_span!("aggregate_response_data"))
.await
.map_err(|err| {
tracing::error!(fetch_error = ?err);
FetchError::SubrequestHttpError {
status_code: Some(parts.status.as_u16()),
service: service_name.to_string(),
reason: err.to_string(),
}
});
if let Ok(body) = &body {
if display_body {
tracing::info!(
http.response.body = %String::from_utf8_lossy(body), apollo.subgraph.name = %service_name, "Raw response body from subgraph {service_name:?} received"
);
}
}
Some(body)
} else {
if display_body {
let body = hyper::body::to_bytes(body)
.instrument(tracing::debug_span!("aggregate_response_data"))
.await
.map_err(|err| {
tracing::error!(fetch_error = ?err);
FetchError::SubrequestHttpError {
status_code: Some(parts.status.as_u16()),
service: service_name.to_string(),
reason: err.to_string(),
}
});
if let Ok(body) = &body {
tracing::info!(
http.response.body = %String::from_utf8_lossy(body), apollo.subgraph.name = %service_name, "Raw response body from subgraph {service_name:?} received"
);
}
}
None
};
Ok((parts, content_type, body))
}
fn get_websocket_request(
service_name: String,
mut parts: http::request::Parts,
subgraph_ws_cfg: &WebSocketConfiguration,
) -> Result<http::Request<()>, FetchError> {
let mut subgraph_url = url::Url::parse(&parts.uri.to_string()).map_err(|err| {
tracing::error!("cannot parse subgraph url {}: {err:?}", parts.uri);
FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot parse subgraph url".to_string(),
}
})?;
let new_scheme = match subgraph_url.scheme() {
"http" => "ws",
"https" => "wss",
_ => "ws",
};
subgraph_url.set_scheme(new_scheme).map_err(|err| {
tracing::error!("cannot set a scheme '{new_scheme}' on subgraph url: {err:?}");
FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot set a scheme on websocket url".to_string(),
}
})?;
let subgraph_url = match &subgraph_ws_cfg.path {
Some(path) => subgraph_url
.join(path)
.map_err(|_| FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot parse subgraph url with the specific websocket path".to_string(),
})?,
None => subgraph_url,
};
let mut request = subgraph_url.into_client_request().map_err(|err| {
tracing::error!("cannot create websocket client request: {err:?}");
FetchError::SubrequestWsError {
service: service_name.clone(),
reason: "cannot create websocket client request".to_string(),
}
})?;
request.headers_mut().insert(
http::header::SEC_WEBSOCKET_PROTOCOL,
subgraph_ws_cfg.protocol.into(),
);
parts.headers.extend(request.headers_mut().drain());
*request.headers_mut() = parts.headers;
Ok(request)
}
fn get_apq_error(gql_response: &graphql::Response) -> APQError {
for error in &gql_response.errors {
// Check if error message is an APQ error
match error.message.as_str() {
PERSISTED_QUERY_NOT_FOUND_MESSAGE => {
return APQError::PersistedQueryNotFound;
}
PERSISTED_QUERY_NOT_SUPPORTED_MESSAGE => {
return APQError::PersistedQueryNotSupported;
}
_ => {}
}
// Check if extensions contains the APQ error in "code"
if let Some(value) = error.extensions.get(CODE_STRING) {
if value == PERSISTED_QUERY_NOT_FOUND_EXTENSION_CODE {
return APQError::PersistedQueryNotFound;
} else if value == PERSISTED_QUERY_NOT_SUPPORTED_EXTENSION_CODE {
return APQError::PersistedQueryNotSupported;
}
}
}
APQError::Other
}
#[derive(Clone)]
pub(crate) struct SubgraphServiceFactory {
pub(crate) services: Arc<HashMap<String, Arc<dyn MakeSubgraphService>>>,
pub(crate) plugins: Arc<Plugins>,
}
impl SubgraphServiceFactory {
pub(crate) fn new(
services: Vec<(String, Arc<dyn MakeSubgraphService>)>,
plugins: Arc<Plugins>,
) -> Self {
SubgraphServiceFactory {
services: Arc::new(services.into_iter().collect()),
plugins,
}
}
pub(crate) fn create(
&self,
name: &str,
) -> Option<BoxService<SubgraphRequest, SubgraphResponse, BoxError>> {
self.services.get(name).map(|service| {
let service = service.make();
self.plugins
.iter()
.rev()
.fold(service, |acc, (_, e)| e.subgraph_service(name, acc))
})
}
}
/// make new instances of the subgraph service