/
MigrateEngine.ts
397 lines (380 loc) · 12.9 KB
/
MigrateEngine.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
import chalk from 'chalk'
import { ChildProcess, spawn } from 'child_process'
import Debug from '@prisma/debug'
import { EngineArgs, EngineResults } from './types'
import byline from './utils/byline'
const debugRpc = Debug('prisma:migrateEngine:rpc')
const debugStderr = Debug('prisma:migrateEngine:stderr')
const debugStdin = Debug('prisma:migrateEngine:stdin')
import fs from 'fs'
import { now } from './utils/now'
import { RustPanic, ErrorArea, resolveBinary } from '@prisma/sdk'
export interface MigrateEngineOptions {
projectDir: string
schemaPath: string
debug?: boolean
enabledPreviewFeatures?: 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
}
}
let messageId = 1
/* tslint:disable */
export class MigrateEngine {
private projectDir: string
private debug: boolean
private child?: ChildProcess
private schemaPath: string
private listeners: { [key: string]: (result: any, err?: any) => any } = {}
private messages: string[] = []
private lastRequest?: any
private lastError?: any
private initPromise?: Promise<void>
private enabledPreviewFeatures?: string[]
constructor({
projectDir,
debug = false,
schemaPath,
enabledPreviewFeatures,
}: MigrateEngineOptions) {
this.projectDir = projectDir
this.schemaPath = schemaPath
if (debug) {
Debug.enable('MigrateEngine*')
}
this.debug = debug
this.enabledPreviewFeatures = enabledPreviewFeatures
}
public stop(): void {
this.child!.kill()
}
/* eslint-disable @typescript-eslint/no-unsafe-return */
// Runs dev diagnostic
public devDiagnostic(
args: EngineArgs.DevDiagnosticInput,
): Promise<EngineResults.DevDiagnosticOutput> {
return this.runCommand(this.getRPCPayload('devDiagnostic', args))
}
// List migrations in migration directory.
public listMigrationDirectories(
args: EngineArgs.ListMigrationDirectoriesInput,
): Promise<EngineResults.ListMigrationDirectoriesOutput> {
return this.runCommand(this.getRPCPayload('listMigrationDirectories', args))
}
// Mark the specified migration as applied in the migrations table. There are two possible cases:
// - The migration is already in the table, but in a failed state. In this case, we will mark it as rolled back, then create a new entry.
// - The migration is not in the table. We will create a new entry in the migrations table. The `started_at` and `finished_at` will be the same.
// - If it is already applied, we return a user-facing error.
public markMigrationApplied(
args: EngineArgs.MarkMigrationAppliedInput,
): Promise<void> {
return this.runCommand(this.getRPCPayload('markMigrationApplied', args))
}
// Mark an existing failed migration as rolled back in the migrations table. It will still be there, but ignored for all purposes except as audit trail.
public markMigrationRolledBack(
args: EngineArgs.MarkMigrationRolledBackInput,
): Promise<void> {
return this.runCommand(this.getRPCPayload('markMigrationRolledBack', args))
}
public diagnoseMigrationHistory(
args: EngineArgs.DiagnoseMigrationHistoryInput,
): Promise<EngineResults.DiagnoseMigrationHistoryOutput> {
return this.runCommand(this.getRPCPayload('diagnoseMigrationHistory', args))
}
public planMigration(
args: EngineArgs.PlanMigrationInput,
): Promise<EngineResults.PlanMigrationOutput> {
return this.runCommand(this.getRPCPayload('planMigration', args))
}
public evaluateDataLoss(
args: EngineArgs.EvaluateDataLossInput,
): Promise<EngineResults.EvaluateDataLossOutput> {
return this.runCommand(this.getRPCPayload('evaluateDataLoss', args))
}
public createMigration(
args: EngineArgs.CreateMigrationInput,
): Promise<EngineResults.CreateMigrationOutput> {
return this.runCommand(this.getRPCPayload('createMigration', args))
}
public applyMigrations(
args: EngineArgs.ApplyMigrationsInput,
): Promise<EngineResults.ApplyMigrationsOutput> {
return this.runCommand(this.getRPCPayload('applyMigrations', args))
}
public reset(): Promise<void> {
return this.runCommand(this.getRPCPayload('reset', undefined))
}
public getDatabaseVersion(): Promise<string> {
return this.runCommand(this.getRPCPayload('getDatabaseVersion', undefined))
}
public schemaPush(
args: EngineArgs.SchemaPush,
): Promise<EngineResults.SchemaPush> {
return this.runCommand(this.getRPCPayload('schemaPush', args))
}
public debugPanic(): Promise<any> {
return this.runCommand(this.getRPCPayload('debugPanic', undefined))
}
/* eslint-enable @typescript-eslint/no-unsafe-return */
private rejectAll(err: any): void {
Object.entries(this.listeners).map(([id, listener]) => {
listener(null, err)
delete this.listeners[id]
})
}
private registerCallback(
id: number,
callback: (result: any, err?: Error) => any,
): void {
this.listeners[id] = callback
}
private handleResponse(response: any): void {
let result
try {
result = JSON.parse(response)
} catch (e) {
console.error(
`Could not parse migration engine response: ${response.slice(0, 200)}`,
)
}
if (result) {
if (result.id) {
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]
}
} else {
// If the error happens before the JSON-RPC sever starts, the error doesn't have an id
if (result.is_panic) {
throw new Error(`Response: ${result.message}`)
} else if (result.message) {
console.error(chalk.red(`Response: ${result.message}`))
} else {
console.error(chalk.red(`Response: ${JSON.stringify(result)}`))
}
}
}
}
private init(): Promise<void> {
if (!this.initPromise) {
this.initPromise = this.internalInit()
}
return this.initPromise
}
private internalInit(): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { PWD, ...rest } = process.env
const binaryPath = await resolveBinary('migration-engine')
debugRpc('starting migration engine with binary: ' + binaryPath)
const args = ['-d', this.schemaPath]
if (
this.enabledPreviewFeatures &&
Array.isArray(this.enabledPreviewFeatures) &&
this.enabledPreviewFeatures.length > 0
) {
args.push(
...[
'--enabled-preview-features',
this.enabledPreviewFeatures.join(','),
],
)
}
this.child = spawn(binaryPath, args, {
cwd: this.projectDir,
stdio: ['pipe', 'pipe', this.debug ? process.stderr : 'pipe'],
env: {
...rest,
SERVER_ROOT: this.projectDir,
RUST_LOG: 'info',
RUST_BACKTRACE: '1',
},
})
this.child.on('error', (err) => {
console.error('[migration-engine] error: %s', err)
reject(err)
this.rejectAll(err)
})
this.child.on('exit', (code) => {
const messages = this.messages.join('\n')
let err: RustPanic | Error | undefined
if (code !== 0 || messages.includes('panicking')) {
let errorMessage =
chalk.red.bold('Error in migration engine: ') + messages
if (code === 250) {
// Not a panic
// It's a UserFacingError https://github.com/prisma/prisma-engines/pull/1446
errorMessage = chalk.red.bold('UserFacingError')
} else if (this.lastError && code === 255) {
errorMessage = serializePanic(this.lastError)
err = new RustPanic(
errorMessage,
this.lastError.message,
this.lastRequest,
ErrorArea.LIFT_CLI,
this.schemaPath,
)
} else if (messages.includes('panicked at') || code === 255) {
err = new RustPanic(
errorMessage,
messages,
this.lastRequest,
ErrorArea.LIFT_CLI,
this.schemaPath,
)
}
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) {
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> {
if (process.env.FORCE_PANIC_MIGRATION_ENGINE) {
request = this.getRPCPayload('debugPanic', undefined)
}
await this.init()
if (this.child?.killed) {
throw new Error(
`Can't execute ${JSON.stringify(
request,
)} because migration engine already exited.`,
)
}
return new Promise((resolve, reject) => {
this.registerCallback(request.id, (response, err) => {
if (err) {
return reject(err)
}
// can be null, for reset RPC for example
if (response.result !== undefined) {
resolve(response.result)
} else {
if (response.error) {
debugRpc(response)
if (response.error.data?.is_panic) {
// if (response.error.data && response.error.data.message) {
const message =
response.error.data?.error?.message ?? response.error.message
reject(
// Handle error and displays the interactive dialog to send panic error
new RustPanic(
message,
response.error.data.message,
this.lastRequest,
ErrorArea.LIFT_CLI,
this.schemaPath,
),
)
} else if (response.error.data?.message) {
// Print known error code & message from engine
// See known errors at https://github.com/prisma/specs/tree/master/errors#prisma-sdk
let message = `${chalk.redBright(response.error.data.message)}\n`
if (response.error.data?.error_code) {
message =
chalk.redBright(`${response.error.data.error_code}\n\n`) +
message
reject(new EngineError(message, response.error.data.error_code))
} else {
reject(new Error(message))
}
} else {
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`,
),
)
}
} else {
reject(
new Error(
`Got invalid RPC response without .result property: ${JSON.stringify(
response,
)}`,
),
)
}
}
})
if (this.child!.stdin!.destroyed) {
throw new Error(
`Can't execute ${JSON.stringify(
request,
)} because migration engine is destroyed.`,
)
}
debugRpc('SENDING RPC CALL', JSON.stringify(request))
this.child!.stdin!.write(JSON.stringify(request) + '\n')
this.lastRequest = request
})
}
private getRPCPayload(method: string, params: any): RPCPayload {
return {
id: messageId++,
jsonrpc: '2.0',
method,
params: {
...params,
},
}
}
}
function serializePanic(log): string {
return `${chalk.red.bold('Error in migration engine.\nReason: ')}${chalk.red(
`${log.message}`,
)}
Please create an issue with your \`schema.prisma\` at
${chalk.underline('https://github.com/prisma/prisma/issues/new')}\n`
}