-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
LibraryEngine.ts
561 lines (488 loc) · 17.8 KB
/
LibraryEngine.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
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
import Debug from '@prisma/debug'
import { DMMF } from '@prisma/generator-helper'
import type { Platform } from '@prisma/get-platform'
import { getPlatform, isNodeAPISupported, platforms } from '@prisma/get-platform'
import chalk from 'chalk'
import fs from 'fs'
import type {
BatchQueryEngineResult,
DatasourceOverwrite,
EngineConfig,
EngineEventType,
RequestBatchOptions,
RequestOptions,
} from '../common/Engine'
import { Engine } from '../common/Engine'
import { PrismaClientInitializationError } from '../common/errors/PrismaClientInitializationError'
import { PrismaClientKnownRequestError } from '../common/errors/PrismaClientKnownRequestError'
import { PrismaClientRustPanicError } from '../common/errors/PrismaClientRustPanicError'
import { PrismaClientUnknownRequestError } from '../common/errors/PrismaClientUnknownRequestError'
import { RequestError } from '../common/errors/types/RequestError'
import { getErrorMessageWithLink } from '../common/errors/utils/getErrorMessageWithLink'
import { prismaGraphQLToJSError } from '../common/errors/utils/prismaGraphQLToJSError'
import { EventEmitter } from '../common/types/Events'
import { EngineMetricsOptions, Metrics, MetricsOptionsJson, MetricsOptionsPrometheus } from '../common/types/Metrics'
import type {
ConfigMetaFormat,
EngineSpanEvent,
QueryEngineBatchRequest,
QueryEngineEvent,
QueryEngineLogLevel,
QueryEnginePanicEvent,
QueryEngineQueryEvent,
QueryEngineRequest,
QueryEngineResult,
RustRequestError,
SyncRustError,
} from '../common/types/QueryEngine'
import type * as Tx from '../common/types/Transaction'
import { createSpan, getTraceParent, runInChildSpan } from '../tracing'
import { DefaultLibraryLoader } from './DefaultLibraryLoader'
import { type BeforeExitListener, ExitHooks } from './ExitHooks'
import type { Library, LibraryLoader, QueryEngineConstructor, QueryEngineInstance } from './types/Library'
const debug = Debug('prisma:client:libraryEngine')
function isQueryEvent(event: QueryEngineEvent): event is QueryEngineQueryEvent {
return event['item_type'] === 'query' && 'query' in event
}
function isPanicEvent(event: QueryEngineEvent): event is QueryEnginePanicEvent {
if ('level' in event) {
return event.level === 'error' && event['message'] === 'PANIC'
} else {
return false
}
}
const knownPlatforms: Platform[] = [...platforms, 'native']
let engineInstanceCount = 0
const exitHooks = new ExitHooks()
export class LibraryEngine extends Engine {
private engine?: QueryEngineInstance
private libraryInstantiationPromise?: Promise<void>
private libraryStartingPromise?: Promise<void>
private libraryStoppingPromise?: Promise<void>
private libraryStarted: boolean
private executingQueryPromise?: Promise<any>
private config: EngineConfig
private QueryEngineConstructor?: QueryEngineConstructor
private libraryLoader: LibraryLoader
private library?: Library
private logEmitter: EventEmitter
libQueryEnginePath?: string
platform?: Platform
datasourceOverrides: Record<string, string>
datamodel: string
logQueries: boolean
logLevel: QueryEngineLogLevel
lastQuery?: string
loggerRustPanic?: any
versionInfo?: {
commit: string
version: string
}
get beforeExitListener() {
return exitHooks.getListener(this)
}
set beforeExitListener(listener: BeforeExitListener | undefined) {
exitHooks.setListener(this, listener)
}
constructor(config: EngineConfig, loader: LibraryLoader = new DefaultLibraryLoader(config)) {
super()
this.datamodel = fs.readFileSync(config.datamodelPath, 'utf-8')
this.config = config
this.libraryStarted = false
this.logQueries = config.logQueries ?? false
this.logLevel = config.logLevel ?? 'error'
this.libraryLoader = loader
this.logEmitter = config.logEmitter
this.datasourceOverrides = config.datasources ? this.convertDatasources(config.datasources) : {}
if (config.enableDebugLogs) {
this.logLevel = 'debug'
}
this.libraryInstantiationPromise = this.instantiateLibrary()
exitHooks.install()
this.checkForTooManyEngines()
}
private checkForTooManyEngines() {
if (engineInstanceCount === 10) {
console.warn(
`${chalk.yellow('warn(prisma-client)')} There are already 10 instances of Prisma Client actively running.`,
)
}
}
async transaction(action: 'start', headers: Tx.TransactionHeaders, options?: Tx.Options): Promise<Tx.Info<undefined>>
async transaction(action: 'commit', headers: Tx.TransactionHeaders, info: Tx.Info<undefined>): Promise<undefined>
async transaction(action: 'rollback', headers: Tx.TransactionHeaders, info: Tx.Info<undefined>): Promise<undefined>
async transaction(action: any, headers: Tx.TransactionHeaders, arg?: any) {
await this.start()
const headerStr = JSON.stringify(headers)
let result: string | undefined
if (action === 'start') {
const jsonOptions = JSON.stringify({
max_wait: arg?.maxWait ?? 2000, // default
timeout: arg?.timeout ?? 5000, // default
isolation_level: arg?.isolationLevel,
})
result = await this.engine?.startTransaction(jsonOptions, headerStr)
} else if (action === 'commit') {
result = await this.engine?.commitTransaction(arg.id, headerStr)
} else if (action === 'rollback') {
result = await this.engine?.rollbackTransaction(arg.id, headerStr)
}
const response = this.parseEngineResponse<{ [K: string]: unknown }>(result)
if (response.error_code) {
throw new PrismaClientKnownRequestError(response.message as string, {
code: response.error_code as string,
clientVersion: this.config.clientVersion as string,
meta: response.meta as Record<string, unknown>,
})
}
return response as Tx.Info<undefined> | undefined
}
private async instantiateLibrary(): Promise<void> {
debug('internalSetup')
if (this.libraryInstantiationPromise) {
return this.libraryInstantiationPromise
}
await isNodeAPISupported()
this.platform = await this.getPlatform()
await this.loadEngine()
this.version()
}
private async getPlatform() {
if (this.platform) return this.platform
const platform = await getPlatform()
if (!knownPlatforms.includes(platform)) {
throw new PrismaClientInitializationError(
`Unknown ${chalk.red('PRISMA_QUERY_ENGINE_LIBRARY')} ${chalk.redBright.bold(
platform,
)}. Possible binaryTargets: ${chalk.greenBright(
knownPlatforms.join(', '),
)} or a path to the query engine library.
You may have to run ${chalk.greenBright('prisma generate')} for your changes to take effect.`,
this.config.clientVersion!,
)
}
return platform
}
private parseEngineResponse<T>(response?: string): T {
if (!response) {
throw new PrismaClientUnknownRequestError(`Response from the Engine was empty`, {
clientVersion: this.config.clientVersion!,
})
}
try {
const config = JSON.parse(response)
return config as T
} catch (err) {
throw new PrismaClientUnknownRequestError(`Unable to JSON.parse response from engine`, {
clientVersion: this.config.clientVersion!,
})
}
}
private convertDatasources(datasources: DatasourceOverwrite[]): Record<string, string> {
const obj = Object.create(null)
for (const { name, url } of datasources) {
obj[name] = url
}
return obj
}
private async loadEngine(): Promise<void> {
if (!this.engine) {
if (!this.QueryEngineConstructor) {
this.library = await this.libraryLoader.loadLibrary()
this.QueryEngineConstructor = this.library.QueryEngine
}
try {
// Using strong reference to `this` inside of log callback will prevent
// this instance from being GCed while native engine is alive. At the same time,
// `this.engine` field will prevent native instance from being GCed. Using weak ref helps
// to avoid this cycle
const weakThis = new WeakRef(this)
this.engine = new this.QueryEngineConstructor(
{
datamodel: this.datamodel,
env: process.env,
logQueries: this.config.logQueries ?? false,
ignoreEnvVarErrors: false,
datasourceOverrides: this.datasourceOverrides,
logLevel: this.logLevel,
configDir: this.config.cwd!,
},
(log) => {
weakThis.deref()?.logger(log)
},
)
engineInstanceCount++
} catch (_e) {
const e = _e as Error
const error = this.parseInitError(e.message)
if (typeof error === 'string') {
throw e
} else {
throw new PrismaClientInitializationError(error.message, this.config.clientVersion!, error.error_code)
}
}
}
}
private logger(log: string) {
const event = this.parseEngineResponse<QueryEngineEvent | null>(log)
if (!event) return
if ('span' in event) {
if (this.config.tracingConfig.enabled === true) {
void createSpan(event as EngineSpanEvent)
}
return
}
event.level = event?.level.toLowerCase() ?? 'unknown'
if (isQueryEvent(event)) {
this.logEmitter.emit('query', {
timestamp: new Date(),
query: event.query,
params: event.params,
duration: Number(event.duration_ms),
target: event.module_path,
})
} else if (isPanicEvent(event)) {
// The error built is saved to be thrown later
this.loggerRustPanic = new PrismaClientRustPanicError(
this.getErrorMessageWithLink(
`${event.message}: ${event.reason} in ${event.file}:${event.line}:${event.column}`,
),
this.config.clientVersion!,
)
} else {
this.logEmitter.emit(event.level, {
timestamp: new Date(),
message: event.message,
target: event.module_path,
})
}
}
private getErrorMessageWithLink(title: string) {
return getErrorMessageWithLink({
platform: this.platform,
title,
version: this.config.clientVersion!,
engineVersion: this.versionInfo?.commit,
database: this.config.activeProvider as any,
query: this.lastQuery!,
})
}
private parseInitError(str: string): SyncRustError | string {
try {
const error = JSON.parse(str)
return error
} catch (e) {
//
}
return str
}
private parseRequestError(str: string): RustRequestError | string {
try {
const error = JSON.parse(str)
return error
} catch (e) {
//
}
return str
}
on(event: EngineEventType, listener: (args?: any) => any): void {
if (event === 'beforeExit') {
this.beforeExitListener = listener
} else {
this.logEmitter.on(event, listener)
}
}
async start(): Promise<void> {
await this.libraryInstantiationPromise
await this.libraryStoppingPromise
if (this.libraryStartingPromise) {
debug(`library already starting, this.libraryStarted: ${this.libraryStarted}`)
return this.libraryStartingPromise
}
if (this.libraryStarted) {
return
}
const startFn = async () => {
debug('library starting')
try {
const headers = {
traceparent: getTraceParent({ tracingConfig: this.config.tracingConfig }),
}
// TODO: not used yet by the engine
await this.engine?.connect(JSON.stringify(headers))
this.libraryStarted = true
debug('library started')
} catch (err) {
const error = this.parseInitError(err.message as string)
// The error message thrown by the query engine should be a stringified JSON
// if parsing fails then we just reject the error
if (typeof error === 'string') {
throw err
} else {
throw new PrismaClientInitializationError(error.message, this.config.clientVersion!, error.error_code)
}
} finally {
this.libraryStartingPromise = undefined
}
}
const spanConfig = {
name: 'connect',
enabled: this.config.tracingConfig.enabled,
}
this.libraryStartingPromise = runInChildSpan(spanConfig, startFn)
return this.libraryStartingPromise
}
async stop(): Promise<void> {
await this.libraryStartingPromise
await this.executingQueryPromise
if (this.libraryStoppingPromise) {
debug('library is already stopping')
return this.libraryStoppingPromise
}
if (!this.libraryStarted) {
return
}
const stopFn = async () => {
await new Promise((r) => setTimeout(r, 5))
debug('library stopping')
const headers = {
traceparent: getTraceParent({ tracingConfig: this.config.tracingConfig }),
}
await this.engine?.disconnect(JSON.stringify(headers))
this.libraryStarted = false
this.libraryStoppingPromise = undefined
debug('library stopped')
}
const spanConfig = {
name: 'disconnect',
enabled: this.config.tracingConfig.enabled,
}
this.libraryStoppingPromise = runInChildSpan(spanConfig, stopFn)
return this.libraryStoppingPromise
}
async getConfig(): Promise<ConfigMetaFormat> {
await this.libraryInstantiationPromise
return this.library!.getConfig({
datamodel: this.datamodel,
datasourceOverrides: this.datasourceOverrides,
ignoreEnvVarErrors: true,
env: process.env,
})
}
async getDmmf(): Promise<DMMF.Document> {
await this.libraryInstantiationPromise
return JSON.parse(await this.library!.dmmf(this.datamodel))
}
version(): string {
this.versionInfo = this.library?.version()
return this.versionInfo?.version ?? 'unknown'
}
/**
* Triggers an artificial panic
*/
debugPanic(message?: string): Promise<never> {
return this.library?.debugPanic(message) as Promise<never>
}
async request<T>({ query, headers = {} }: RequestOptions<undefined>): Promise<{ data: T; elapsed: number }> {
debug(`sending request, this.libraryStarted: ${this.libraryStarted}`)
const request: QueryEngineRequest = { query, variables: {} }
const headerStr = JSON.stringify(headers) // object equivalent to http headers for the library
const queryStr = JSON.stringify(request)
try {
await this.start()
this.executingQueryPromise = this.engine?.query(queryStr, headerStr, headers.transactionId)
this.lastQuery = queryStr
const data = this.parseEngineResponse<any>(await this.executingQueryPromise)
if (data.errors) {
if (data.errors.length === 1) {
throw this.buildQueryError(data.errors[0])
}
// this case should not happen, as the query engine only returns one error
throw new PrismaClientUnknownRequestError(JSON.stringify(data.errors), {
clientVersion: this.config.clientVersion!,
})
} else if (this.loggerRustPanic) {
throw this.loggerRustPanic
}
// TODO Implement Elapsed: https://github.com/prisma/prisma/issues/7726
return { data, elapsed: 0 }
} catch (e: any) {
if (e instanceof PrismaClientInitializationError) {
throw e
}
if (e.code === 'GenericFailure' && e.message?.startsWith('PANIC:')) {
throw new PrismaClientRustPanicError(this.getErrorMessageWithLink(e.message), this.config.clientVersion!)
}
const error = this.parseRequestError(e.message)
if (typeof error === 'string') {
throw e
} else {
throw new PrismaClientUnknownRequestError(`${error.message}\n${error.backtrace}`, {
clientVersion: this.config.clientVersion!,
})
}
}
}
async requestBatch<T>({
queries,
headers = {},
transaction,
}: RequestBatchOptions): Promise<BatchQueryEngineResult<T>[]> {
debug('requestBatch')
const request: QueryEngineBatchRequest = {
batch: queries.map((query) => ({ query, variables: {} })),
transaction: Boolean(transaction),
isolationLevel: transaction?.isolationLevel,
}
await this.start()
this.lastQuery = JSON.stringify(request)
this.executingQueryPromise = this.engine!.query(this.lastQuery, JSON.stringify(headers), headers.transactionId)
const result = await this.executingQueryPromise
const data = this.parseEngineResponse<any>(result)
if (data.errors) {
if (data.errors.length === 1) {
throw this.buildQueryError(data.errors[0])
}
// this case should not happen, as the query engine only returns one error
throw new PrismaClientUnknownRequestError(JSON.stringify(data.errors), {
clientVersion: this.config.clientVersion!,
})
}
const { batchResult, errors } = data
if (Array.isArray(batchResult)) {
return batchResult.map((result) => {
if (result.errors && result.errors.length > 0) {
return this.loggerRustPanic ?? this.buildQueryError(result.errors[0])
}
return {
data: result,
elapsed: 0, // TODO Implement Elapsed: https://github.com/prisma/prisma/issues/7726
}
})
} else {
if (errors && errors.length === 1) {
throw new Error(errors[0].error)
}
throw new Error(JSON.stringify(data))
}
}
private buildQueryError(error: RequestError) {
if (error.user_facing_error.is_panic) {
return new PrismaClientRustPanicError(
this.getErrorMessageWithLink(error.user_facing_error.message),
this.config.clientVersion!,
)
}
return prismaGraphQLToJSError(error, this.config.clientVersion!)
}
async metrics(options: MetricsOptionsJson): Promise<Metrics>
async metrics(options: MetricsOptionsPrometheus): Promise<string>
async metrics(options: EngineMetricsOptions): Promise<Metrics | string> {
await this.start()
const responseString = await this.engine!.metrics(JSON.stringify(options))
if (options.format === 'prometheus') {
return responseString
}
return this.parseEngineResponse(responseString)
}
}