/
RequestHandler.ts
280 lines (251 loc) · 8.24 KB
/
RequestHandler.ts
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
import { Context } from '@opentelemetry/api'
import Debug from '@prisma/debug'
import { getTraceParent, TracingConfig } from '@prisma/engine-core'
import stripAnsi from 'strip-ansi'
import {
PrismaClientInitializationError,
PrismaClientKnownRequestError,
PrismaClientRustPanicError,
PrismaClientUnknownRequestError,
} from '.'
import { PrismaPromiseTransaction } from './core/request/PrismaPromise'
import { DataLoader } from './DataLoader'
import type { Client, Unpacker } from './getPrismaClient'
import type { EngineMiddleware } from './MiddlewareHandler'
import type { Document } from './query'
import { Args, unpack } from './query'
import { CallSite } from './utils/CallSite'
import { createErrorMessageWithContext } from './utils/createErrorMessageWithContext'
import type { RejectOnNotFound } from './utils/rejectOnNotFound'
import { throwIfNotFound } from './utils/rejectOnNotFound'
const debug = Debug('prisma:client:request_handler')
export type RequestParams = {
document: Document
dataPath: string[]
rootField: string
typeName: string
isList: boolean
clientMethod: string
callsite?: CallSite
rejectOnNotFound?: RejectOnNotFound
transaction?: PrismaPromiseTransaction
engineHook?: EngineMiddleware
args: any
headers?: Record<string, string>
unpacker?: Unpacker
otelParentCtx?: Context
otelChildCtx?: Context
}
export type HandleErrorParams = {
error: any
clientMethod: string
callsite?: CallSite
}
export type Request = {
document: Document
transaction?: PrismaPromiseTransaction
headers?: Record<string, string>
otelParentCtx?: Context
otelChildCtx?: Context
tracingConfig?: TracingConfig
}
function getRequestInfo(request: Request) {
const transaction = request.transaction
const headers = request.headers ?? {}
const traceparent = getTraceParent({ tracingConfig: request.tracingConfig })
if (transaction?.kind === 'itx') {
headers.transactionId = transaction.id
}
if (traceparent !== undefined) {
headers.traceparent = traceparent
}
return {
batchTransaction: transaction?.kind === 'batch' ? transaction : undefined,
headers,
}
}
export class RequestHandler {
client: Client
hooks: any
dataloader: DataLoader<Request>
constructor(client: Client, hooks?: any) {
this.client = client
this.hooks = hooks
this.dataloader = new DataLoader({
batchLoader: (requests) => {
const info = getRequestInfo(requests[0])
const queries = requests.map((r) => String(r.document))
const traceparent = getTraceParent({ context: requests[0].otelParentCtx, tracingConfig: client._tracingConfig })
if (traceparent) info.headers.traceparent = traceparent
// TODO: pass the child information to QE for it to issue links to queries
// const links = requests.map((r) => trace.getSpanContext(r.otelChildCtx!))
return this.client._engine.requestBatch(queries, info.headers, {
isolationLevel: info.batchTransaction?.isolationLevel,
})
},
singleLoader: (request) => {
const info = getRequestInfo(request)
const query = String(request.document)
return this.client._engine.request(query, info.headers)
},
batchBy: (request) => {
if (request.transaction?.id) {
return `transaction-${request.transaction.id}`
}
return batchFindUniqueBy(request)
},
})
}
async request({
document,
dataPath = [],
rootField,
typeName,
isList,
callsite,
rejectOnNotFound,
clientMethod,
engineHook,
args,
headers,
transaction,
unpacker,
otelParentCtx,
otelChildCtx,
}: RequestParams) {
if (this.hooks && this.hooks.beforeRequest) {
const query = String(document)
this.hooks.beforeRequest({
query,
path: dataPath,
rootField,
typeName,
document,
isList,
clientMethod,
args,
})
}
try {
/**
* If there's an engine hook, use it here
*/
let data, elapsed
if (engineHook) {
const result = await engineHook(
{
document,
runInTransaction: Boolean(transaction),
},
(params) => this.dataloader.request({ ...params, tracingConfig: this.client._tracingConfig }),
)
data = result.data
elapsed = result.elapsed
} else {
const result = await this.dataloader.request({
document,
headers,
transaction,
otelParentCtx,
otelChildCtx,
tracingConfig: this.client._tracingConfig,
})
data = result?.data
elapsed = result?.elapsed
}
/**
* Unpack
*/
const unpackResult = this.unpack(document, data, dataPath, rootField, unpacker)
throwIfNotFound(unpackResult, clientMethod, typeName, rejectOnNotFound)
if (process.env.PRISMA_CLIENT_GET_TIME) {
return { data: unpackResult, elapsed }
}
return unpackResult
} catch (error) {
this.handleRequestError({ error, clientMethod, callsite })
}
}
handleRequestError({ error, clientMethod, callsite }: HandleErrorParams): never {
debug(error)
let message = error.message
if (callsite) {
message = createErrorMessageWithContext({
callsite,
originalMethod: clientMethod,
isPanic: error.isPanic,
showColors: this.client._errorFormat === 'pretty',
message,
})
}
message = this.sanitizeMessage(message)
// TODO: Do request with callsite instead, so we don't need to rethrow
if (error.code) {
throw new PrismaClientKnownRequestError(message, error.code, this.client._clientVersion, error.meta)
} else if (error.isPanic) {
throw new PrismaClientRustPanicError(message, this.client._clientVersion)
} else if (error instanceof PrismaClientUnknownRequestError) {
throw new PrismaClientUnknownRequestError(message, this.client._clientVersion)
} else if (error instanceof PrismaClientInitializationError) {
throw new PrismaClientInitializationError(message, this.client._clientVersion)
} else if (error instanceof PrismaClientRustPanicError) {
throw new PrismaClientRustPanicError(message, this.client._clientVersion)
}
error.clientVersion = this.client._clientVersion
throw error
}
sanitizeMessage(message) {
if (this.client._errorFormat && this.client._errorFormat !== 'pretty') {
return stripAnsi(message)
}
return message
}
unpack(document, data, path, rootField, unpacker?: Unpacker) {
if (data?.data) {
data = data.data
}
// to lift up _all in count
if (unpacker) {
data[rootField] = unpacker(data[rootField])
}
const getPath: any[] = []
if (rootField) {
getPath.push(rootField)
}
getPath.push(...path.filter((p) => p !== 'select' && p !== 'include'))
return unpack({ document, data, path: getPath })
}
get [Symbol.toStringTag]() {
return 'RequestHandler'
}
}
/**
* Determines which `findUnique` queries can be batched together so that the
* query engine can collapse/optimize the queries into a single one. This is
* especially useful for GQL to generate more efficient queries.
*
* @see https://www.prisma.io/docs/guides/performance-and-optimization/query-optimization-performance
* @param request
* @returns
*/
function batchFindUniqueBy(request: Request) {
// if it's not a findUnique query then we don't attempt optimizing
if (!request.document.children[0].name.startsWith('findUnique')) {
return undefined
}
// we generate a string for the fields we have used in the `where`
const args = request.document.children[0].args?.args
.map((a) => {
if (a.value instanceof Args) {
return `${a.key}-${a.value.args.map((a) => a.key).join(',')}`
}
return a.key
})
.join(',')
// we generate a string for the fields we have used in the `includes`
const selectionSet = request.document.children[0].children!.join(',')
// queries that share this token will be batched and collapsed alltogether
return `${request.document.children[0].name}|${args}|${selectionSet}`
// this way, the query engine will be able to collapse into a single call
// and that is because all the queries share their `where` and `includes`
}