Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathgraphqlClient.ts
More file actions
Latest commit
297 lines (249 loc) · 9.45 KB
/
Copy pathgraphqlClient.ts
File metadata and controls
297 lines (249 loc) · 9.45 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
importtype{Client,IntegrationFn}from'@sentry/core';
import{
defineIntegration,
hasSpanStreamingEnabled,
isObjectLike,
isString,
SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,
spanToJSON,
stringMatchesSomePattern,
}from'@sentry/core';
importtype{FetchHint,XhrHint}from'@sentry/browser-utils';
import{getBodyString,getFetchRequestArgBody,SENTRY_XHR_DATA_KEY}from'@sentry/browser-utils';
import{
GRAPHQL_DOCUMENT,
GRAPHQL_OPERATION_NAME,
GRAPHQL_OPERATION_TYPE,
HTTP_METHOD,
SENTRY_OP,
URL_FULL,
}from'@sentry/conventions/attributes';
interfaceGraphQLClientOptions{
endpoints: Array<string|RegExp>;
}
/** Standard graphql request shape: https://graphql.org/learn/serving-over-http/#post-request-and-body */
interfaceGraphQLStandardRequest{
query: string;
operationName?: string;
variables?: Record<string,unknown>;
extensions?: Record<string,unknown>;
}
/** Persisted operation request */
interfaceGraphQLPersistedRequest{
operationName: string;
variables?: Record<string,unknown>;
extensions: {
persistedQuery: {
version: number;
sha256Hash: string;
};
}&Record<string,unknown>;
}
typeGraphQLRequestPayload=GraphQLStandardRequest|GraphQLPersistedRequest;
interfaceGraphQLOperation{
operationType?: string;
operationName?: string;
}
constINTEGRATION_NAME='GraphQLClient'asconst;
const_graphqlClientIntegration=((options: GraphQLClientOptions)=>{
return{
name: INTEGRATION_NAME,
setup(client: Client){
_updateSpanWithGraphQLData(client,options);
_updateBreadcrumbWithGraphQLData(client,options);
},
};
})satisfiesIntegrationFn;
function_updateSpanWithGraphQLData(client: Client,options: GraphQLClientOptions): void{
client.on('beforeOutgoingRequestSpan',(span,hint)=>{
constspanJSON=spanToJSON(span);
constspanAttributes=spanJSON.attributes;
constspanOp=spanAttributes[SENTRY_OP];
constisHttpClientSpan=spanOp==='http.client';
if(!isHttpClientSpan){
return;
}
consthttpUrl=spanAttributes[URL_FULL];
// oxlint-disable-next-line typescript/no-deprecated
consthttpMethod=spanAttributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD]||spanAttributes[HTTP_METHOD];
if(!isString(httpUrl)||!isString(httpMethod)){
return;
}
const{ endpoints }=options;
constisTracedGraphqlEndpoint=stringMatchesSomePattern(httpUrl,endpoints);
constpayload=getRequestPayloadXhrOrFetch(hintasXhrHint|FetchHint);
if(isTracedGraphqlEndpoint&&payload){
constgraphqlBody=getGraphQLRequestPayload(payload);
if(graphqlBody){
// With span streaming the span already carries a low-cardinality name, so it must not be
// renamed back to one containing the URL. The operation stays reachable as an attribute.
if(!hasSpanStreamingEnabled(client)){
span.updateName(`${httpMethod}${httpUrl} (${_getGraphQLOperation(graphqlBody)})`);
}
const{ operationName, operationType }=_getGraphQLOperationDetails(graphqlBody);
span.setAttribute(GRAPHQL_OPERATION_NAME,operationName);
span.setAttribute(GRAPHQL_OPERATION_TYPE,operationType);
// Handle standard requests - capture the query document when enabled via dataCollection (default true)
if(isStandardRequest(graphqlBody)&&client.getDataCollectionOptions().graphQL.document===true){
span.setAttribute(GRAPHQL_DOCUMENT,graphqlBody.query);
}
// Handle persisted operations - capture hash for debugging
if(isPersistedRequest(graphqlBody)){
span.setAttribute('graphql.persisted_query.hash.sha256',graphqlBody.extensions.persistedQuery.sha256Hash);
span.setAttribute('graphql.persisted_query.version',graphqlBody.extensions.persistedQuery.version);
}
}
}
});
}
function_updateBreadcrumbWithGraphQLData(client: Client,options: GraphQLClientOptions): void{
client.on('beforeOutgoingRequestBreadcrumb',(breadcrumb,handlerData)=>{
const{ category, type, data }=breadcrumb;
constisFetch=category==='fetch';
constisXhr=category==='xhr';
constisHttpBreadcrumb=type==='http';
if(isHttpBreadcrumb&&(isFetch||isXhr)){
consthttpUrl=data?.url;
const{ endpoints }=options;
constisTracedGraphqlEndpoint=stringMatchesSomePattern(httpUrl,endpoints);
constpayload=getRequestPayloadXhrOrFetch(handlerDataasXhrHint|FetchHint);
if(isTracedGraphqlEndpoint&&data&&payload){
constgraphqlBody=getGraphQLRequestPayload(payload);
if(!data.graphql&&graphqlBody){
constoperationInfo=_getGraphQLOperation(graphqlBody);
data['graphql.operation']=operationInfo;
if(isStandardRequest(graphqlBody)&&client.getDataCollectionOptions().graphQL.document===true){
data[GRAPHQL_DOCUMENT]=graphqlBody.query;
}
if(isPersistedRequest(graphqlBody)){
data['graphql.persisted_query.hash.sha256']=graphqlBody.extensions.persistedQuery.sha256Hash;
data['graphql.persisted_query.version']=graphqlBody.extensions.persistedQuery.version;
}
}
}
}
});
}
/**
* The operation name and type of a GraphQL request. Persisted operations carry no query document, so
* their type is unknown.
*/
function_getGraphQLOperationDetails(requestBody: GraphQLRequestPayload): GraphQLOperation{
if(isPersistedRequest(requestBody)){
return{operationName: requestBody.operationName,operationType: undefined};
}
if(isStandardRequest(requestBody)){
const{query: graphqlQuery,operationName: graphqlOperationName}=requestBody;
const{ operationName =graphqlOperationName, operationType }=parseGraphQLQuery(graphqlQuery);
return{ operationName, operationType };
}
return{operationName: undefined,operationType: undefined};
}
/**
* @param requestBody - GraphQL request
* @returns A formatted version of the request: 'TYPE NAME' or 'TYPE' or 'persisted NAME'
*/
exportfunction_getGraphQLOperation(requestBody: GraphQLRequestPayload): string{
// Handle persisted operations
if(isPersistedRequest(requestBody)){
return`persisted ${requestBody.operationName}`;
}
// Handle standard GraphQL requests
if(isStandardRequest(requestBody)){
const{ operationName, operationType }=_getGraphQLOperationDetails(requestBody);
returnoperationName ? `${operationType}${operationName}` : `${operationType}`;
}
// Fallback for unknown request types
return'unknown';
}
/**
* Get the request body/payload based on the shape of the hint.
*
* Exported for tests only.
*/
exportfunctiongetRequestPayloadXhrOrFetch(hint: XhrHint|FetchHint): string|undefined{
constisXhr='xhr'inhint;
letbody: string|undefined;
if(isXhr){
constsentryXhrData=hint.xhr[SENTRY_XHR_DATA_KEY];
body=sentryXhrData&&getBodyString(sentryXhrData.body)[0];
}else{
constsentryFetchData=getFetchRequestArgBody(hint.input);
body=getBodyString(sentryFetchData)[0];
}
returnbody;
}
/**
* Extract the name and type of the operation from the GraphQL query.
*
* Exported for tests only.
*/
exportfunctionparseGraphQLQuery(query: string): GraphQLOperation{
constnamedQueryRe=/^(?:\s*)(query|mutation|subscription)(?:\s*)(\w+)(?:\s*)[{(]/;
constunnamedQueryRe=/^(?:\s*)(query|mutation|subscription)(?:\s*)[{(]/;
constnamedMatch=query.match(namedQueryRe);
if(namedMatch){
return{
operationType: namedMatch[1],
operationName: namedMatch[2],
};
}
constunnamedMatch=query.match(unnamedQueryRe);
if(unnamedMatch){
return{
operationType: unnamedMatch[1],
operationName: undefined,
};
}
return{
operationType: undefined,
operationName: undefined,
};
}
/**
* Helper to safely check if a value is a non-null object
*/
/**
* Type guard to check if a request is a standard GraphQL request
*/
functionisStandardRequest(payload: unknown): payload is GraphQLStandardRequest{
returnisObjectLike(payload)&&typeofpayload.query==='string';
}
/**
* Type guard to check if a request is a persisted operation request
*/
functionisPersistedRequest(payload: unknown): payload is GraphQLPersistedRequest{
return(
isObjectLike(payload)&&
typeofpayload.operationName==='string'&&
isObjectLike(payload.extensions)&&
isObjectLike(payload.extensions.persistedQuery)&&
typeofpayload.extensions.persistedQuery.sha256Hash==='string'&&
typeofpayload.extensions.persistedQuery.version==='number'
);
}
/**
* Extract the payload of a request if it's GraphQL.
* Exported for tests only.
* @param payload - A valid JSON string
* @returns A POJO or undefined
*/
exportfunctiongetGraphQLRequestPayload(payload: string): GraphQLRequestPayload|undefined{
try{
constrequestBody=JSON.parse(payload);
// Return any valid GraphQL request (standard, persisted, or APQ retry with both)
if(isStandardRequest(requestBody)||isPersistedRequest(requestBody)){
returnrequestBody;
}
// Not a GraphQL request
returnundefined;
}catch{
// Invalid JSON
returnundefined;
}
}
/**
* This integration ensures that GraphQL requests made in the browser
* have their GraphQL-specific data captured and attached to spans and breadcrumbs.
*/
exportconstgraphqlClientIntegration=defineIntegration(_graphqlClientIntegration);