/
IntrospectionEngine.ts
346 lines (327 loc) · 9.6 KB
/
IntrospectionEngine.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
import chalk from 'chalk'
import { ChildProcess, spawn } from 'child_process'
import debugLib from 'debug'
import byline from './utils/byline'
const debugRpc = debugLib('IntrospectionEngine:rpc')
const debugStderr = debugLib('IntrospectionEngine:stderr')
const debugStdin = debugLib('IntrospectionEngine:stdin')
import { getPlatform } from '@prisma/get-platform'
import fs from 'fs'
import { now } from './utils/now'
import path from 'path'
export interface IntrospectionEngineOptions {
binaryPath?: string
debug?: boolean
cwd?: string
}
export interface RPCPayload {
id: number
jsonrpc: string
method: string
params: any
}
export class EngineError extends Error {
public code: number
constructor(message: string, code: number) {
super(message)
this.code = code
}
}
export class IntrospectionPanic extends Error {
public request: any
public rustStack: string
constructor(message: string, rustStack: string, request: any) {
super(message)
this.rustStack = rustStack
this.request = request
}
}
let messageId = 1
/* tslint:disable */
export class IntrospectionEngine {
private binaryPath?: string
private debug: boolean
private cwd: string
private child?: ChildProcess
private listeners: { [key: string]: (result: any, err?: any) => any } = {}
private messages: string[] = []
private lastRequest?: any
private lastError?: any
private initPromise?: Promise<void>
constructor(
{ binaryPath, debug, cwd }: IntrospectionEngineOptions = {
binaryPath: process.env.PRISMA_INTROSPECTION_ENGINE_BINARY, // ncc go home
debug: false,
cwd: process.cwd(),
},
) {
this.binaryPath =
binaryPath || process.env.PRISMA_INTROSPECTION_ENGINE_BINARY
if (debug) {
debugLib.enable('IntrospectionEngine*')
}
this.debug = Boolean(debug)
this.cwd = cwd || process.cwd()
}
public stop() {
if (this.child) {
this.child.kill()
}
}
private rejectAll(err: any) {
Object.entries(this.listeners).map(([id, listener]) => {
listener(null, err)
delete this.listeners[id]
})
}
private registerCallback(
id: number,
callback: (result: any, err?: Error) => any,
) {
this.listeners[id] = callback
}
public introspect(url: string): Promise<string> {
return this.runCommand(this.getRPCPayload('introspect', { url }))
}
public listDatabases(url: string): Promise<string[]> {
return this.runCommand(this.getRPCPayload('listDatabases', { url }))
}
public getDatabaseMetadata(
url: string,
): Promise<{ size_in_bytes: number; table_count: number }> {
return this.runCommand(this.getRPCPayload('getDatabaseMetadata', { url }))
}
private handleResponse(response: any) {
let result
try {
result = JSON.parse(response)
} catch (e) {
console.error(
`Could not parse introspection engine response: ${response.slice(
0,
200,
)}`,
)
}
if (result) {
if (result.backtrace) {
// if there is a backtrace on the result, it's probably an error
console.log(result)
}
if (!result.id) {
console.error(
`Response ${JSON.stringify(
result,
)} doesn't have an id and I can't handle that (yet)`,
)
}
if (!this.listeners[result.id]) {
console.error(`Got result for unknown id ${result.id}`)
}
if (this.listeners[result.id]) {
this.listeners[result.id](result)
delete this.listeners[result.id]
}
}
}
private init(): Promise<void> {
if (!this.initPromise) {
this.initPromise = this.internalInit()
}
return this.initPromise!
}
private async getBinaryPath() {
if (this.binaryPath) {
return this.binaryPath
}
const platform = await getPlatform()
const extension = platform === 'windows' ? '.exe' : ''
this.binaryPath = path.join(
eval(`require('path').join(__dirname, '../')`),
`introspection-engine-${platform}${extension}`,
)
if (!fs.existsSync(this.binaryPath)) {
throw new Error(
`Expected introspection engine at ${this.binaryPath} does not exist.`,
)
}
return this.binaryPath
}
private internalInit(): Promise<void> {
return new Promise(async (resolve, reject) => {
try {
const { PWD, ...env } = process.env
const binaryPath = await this.getBinaryPath()
debugRpc('starting introspection engine with binary: ' + binaryPath)
this.child = spawn(binaryPath, {
stdio: ['pipe', 'pipe', this.debug ? process.stderr : 'pipe'],
env: {
...env,
RUST_LOG: 'info',
RUST_BACKTRACE: '1',
},
cwd: this.cwd,
})
this.child.on('error', err => {
console.error('[introspection-engine] error: %s', err)
reject(err)
this.rejectAll(err)
})
this.child.on('exit', (code, signal) => {
const messages = this.messages.join('\n')
let err: any
if (code !== 0 || messages.includes('panicked at')) {
let errorMessage =
chalk.red.bold('Error in introspection engine: ') + messages
if (messages.includes('\u001b[1;94m-->\u001b[0m')) {
errorMessage = `${chalk.red.bold('Schema parsing\n')}` + messages
} else if (this.lastError && this.lastError.msg === 'PANIC') {
errorMessage = serializePanic(this.lastError)
err = new IntrospectionPanic(
errorMessage,
messages,
this.lastRequest,
)
} else if (messages.includes('panicked at')) {
err = new IntrospectionPanic(
errorMessage,
messages,
this.lastRequest,
)
}
err = err || new Error(errorMessage)
this.rejectAll(err)
reject(err)
}
})
this.child.stdin!.on('error', err => {
debugStdin(err)
})
byline(this.child.stderr).on('data', data => {
const msg = String(data)
this.messages.push(msg)
debugStderr(msg)
try {
const json = JSON.parse(msg)
if (json.backtrace) {
console.log('setting lastError')
this.lastError = json
}
if (json.level === 'ERRO') {
this.lastError = json
}
} catch (e) {
//
}
})
byline(this.child.stdout).on('data', line => {
this.handleResponse(String(line))
})
setImmediate(() => {
resolve()
})
} catch (e) {
reject(e)
}
})
}
private async runCommand(request: RPCPayload): Promise<any> {
await this.init()
return new Promise((resolve, reject) => {
this.registerCallback(request.id, (response, err) => {
if (err) {
return reject(err)
}
if (typeof response.result !== 'undefined') {
resolve(response.result)
} else {
if (response.error) {
if (
response.error.data &&
response.error.data.error &&
response.error.data.code
) {
reject(
new EngineError(
response.error.data.error,
response.error.data.code,
),
)
} else {
const text = this.persistError(request, this.messages.join('\n'))
reject(
new Error(
`${chalk.redBright(
'Error in RPC',
)}\n Request: ${JSON.stringify(
request,
null,
2,
)}\nResponse: ${JSON.stringify(response, null, 2)}\n${
response.error.message
}\n\n${text}\n`,
),
)
}
} else {
reject(
new Error(
`Got invalid RPC response without .result property: ${JSON.stringify(
response,
)}`,
),
)
}
}
})
debugRpc('SENDING RPC CALL', JSON.stringify(request))
this.child!.stdin!.write(JSON.stringify(request) + '\n')
this.lastRequest = request
})
}
private persistError(request: any, message: string): string {
const filename = `failed-${request.method}-${now()}.md`
const file = `# Failed ${request.method} at ${new Date().toISOString()}
## RPC One-Liner
\`\`\`json
${JSON.stringify(request)}
\`\`\`
## RPC Input Readable
\`\`\`json
${JSON.stringify(request, null, 2)}
\`\`\`
## Stack Trace
\`\`\`bash
${message}
\`\`\`
`
fs.writeFileSync(filename, file)
return `Wrote ${chalk.bold(filename)} with debugging information.
Please put that file into a gist and post it in Slack.
1. ${chalk.greenBright(`cat ${filename} | pbcopy`)}
2. Create a gist ${chalk.greenBright.underline(`https://gist.github.com/new`)}`
}
private getRPCPayload(method: string, params: any): RPCPayload {
return {
id: messageId++,
jsonrpc: '2.0',
method,
params: [
{
...params,
},
],
}
}
}
function serializePanic(log) {
return `${chalk.red.bold(
'Error in introspection engine.\nReason: ',
)}${chalk.red(
`${log.reason} in ${chalk.underline(
`${log.file}:${log.line}:${log.column}`,
)}`,
)}
Please create an issue in the ${chalk.bold('prisma2')} repo with the error 🙏:
${chalk.underline('https://github.com/prisma/prisma2/issues/new')}\n`
}