-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
ProjectConfigIpc.ts
274 lines (220 loc) · 8.5 KB
/
ProjectConfigIpc.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
/* eslint-disable no-dupe-class-members */
import { CypressError, getError } from '@packages/errors'
import type { FullConfig, TestingType } from '@packages/types'
import { ChildProcess, fork, ForkOptions } from 'child_process'
import EventEmitter from 'events'
import path from 'path'
import inspector from 'inspector'
import debugLib from 'debug'
import { autoBindDebug } from '../util'
import _ from 'lodash'
const pkg = require('@packages/root')
const debug = debugLib(`cypress:lifecycle:ProjectConfigIpc`)
const CHILD_PROCESS_FILE_PATH = require.resolve('@packages/server/lib/plugins/child/require_async_child')
export type IpcHandler = (ipc: ProjectConfigIpc) => void
export interface SetupNodeEventsReply {
setupConfig: Cypress.ConfigOptions | null
requires: string[]
registrations: Array<{event: string, eventId: string}>
}
export interface LoadConfigReply {
initialConfig: Cypress.ConfigOptions
requires: string[]
}
export interface SerializedLoadConfigReply {
initialConfig: string // stringified Cypress.ConfigOptions
requires: string[]
}
/**
* The ProjectConfigIpc is an EventEmitter wrapping the childProcess,
* adding a "send" method for sending events from the parent process into the childProcess,
*
*/
export class ProjectConfigIpc extends EventEmitter {
private _childProcess: ChildProcess
constructor (
readonly nodePath: string | undefined | null,
readonly projectRoot: string,
readonly configFilePath: string,
readonly configFile: string | false,
readonly onError: (cypressError: CypressError, title?: string | undefined) => void,
readonly onWarning: (cypressError: CypressError) => void,
) {
super()
this._childProcess = this.forkConfigProcess()
this._childProcess.on('error', (err) => {
// this.emit('error', err)
})
this._childProcess.on('message', (msg: { event: string, args: any[] }) => {
this.emit(msg.event, ...msg.args)
})
this._childProcess.once('disconnect', () => {
this.emit('disconnect')
})
return autoBindDebug(this)
}
// TODO: options => Cypress.TestingTypeOptions
send(event: 'execute:plugins', evt: string, ids: {eventId: string, invocationId: string}, args: any[]): boolean
send(event: 'setupTestingType', testingType: TestingType, options: Cypress.PluginConfigOptions): boolean
send(event: 'loadConfig'): boolean
send (event: string, ...args: any[]) {
if (this._childProcess.killed || !this._childProcess.connected) {
return false
}
return this._childProcess.send({ event, args })
}
on(evt: 'childProcess:unhandledError', listener: (err: CypressError) => void): this
on(evt: 'warning', listener: (warningErr: CypressError) => void): this
on (evt: string, listener: (...args: any[]) => void) {
return super.on(evt, listener)
}
once(evt: `promise:fulfilled:${string}`, listener: (err: any, value: any) => void): this
/**
* When the config is loaded, it comes back with either a "reply", or an "error" if there was a problem
* sourcing the config (script error, etc.)
*/
once(evt: 'ready', listener: () => void): this
once(evt: 'loadConfig:reply', listener: (payload: SerializedLoadConfigReply) => void): this
once(evt: 'loadConfig:error', listener: (err: CypressError) => void): this
/**
* When
*/
once(evt: 'setupTestingType:reply', listener: (payload: SetupNodeEventsReply) => void): this
once(evt: 'setupTestingType:error', listener: (error: CypressError) => void): this
once (evt: string, listener: (...args: any[]) => void) {
return super.once(evt, listener)
}
emit (evt: string, ...args: any[]) {
return super.emit(evt, ...args)
}
loadConfig (): Promise<LoadConfigReply> {
return new Promise((resolve, reject) => {
if (this._childProcess.stdout && this._childProcess.stderr) {
// manually pipe plugin stdout and stderr for dashboard capture
// @see https://github.com/cypress-io/cypress/issues/7434
this._childProcess.stdout.on('data', (data) => process.stdout.write(data))
this._childProcess.stderr.on('data', (data) => process.stderr.write(data))
}
let resolved = false
this._childProcess.on('error', (err) => {
this.handleChildProcessError(err, this, resolved, reject)
reject(err)
})
/**
* This reject cannot be caught anywhere??
*
* It's supposed to be caught on lib/modes/run.js:1689,
* but it's not.
*/
this.on('childProcess:unhandledError', (err) => {
this.handleChildProcessError(err, this, resolved, reject)
reject(err)
})
this.once('loadConfig:reply', (val) => {
debug('loadConfig:reply')
resolve({ ...val, initialConfig: JSON.parse(val.initialConfig) })
resolved = true
})
this.once('loadConfig:error', (err) => {
this.killChildProcess()
reject(err)
})
debug('trigger the load of the file')
this.once('ready', () => {
this.send('loadConfig')
})
})
}
async callSetupNodeEventsWithConfig (testingType: TestingType, config: FullConfig, handlers: IpcHandler[]): Promise<SetupNodeEventsReply> {
for (const handler of handlers) {
handler(this)
}
const promise = this.registerSetupIpcHandlers()
const overrides = config[testingType] ?? {}
const mergedConfig = { ...config, ...overrides }
// alphabetize config by keys
let orderedConfig = {} as Cypress.PluginConfigOptions
Object.keys(mergedConfig).sort().forEach((key) => {
const k = key as keyof typeof mergedConfig
// @ts-ignore
orderedConfig[k] = mergedConfig[k]
})
this.send('setupTestingType', testingType, {
...orderedConfig,
projectRoot: this.projectRoot,
configFile: this.configFilePath,
version: pkg.version,
testingType,
})
return promise
}
private registerSetupIpcHandlers (): Promise<SetupNodeEventsReply> {
return new Promise((resolve, reject) => {
let resolved = false
this._childProcess.on('error', (err) => {
this.handleChildProcessError(err, this, resolved, reject)
reject(err)
})
// For every registration event, we want to turn into an RPC with the child process
this.once('setupTestingType:reply', (val) => {
resolved = true
resolve(val)
})
this.once('setupTestingType:error', (err) => {
this.onError(err)
reject(err)
})
const handleWarning = (warningErr: CypressError) => {
debug('plugins process warning:', warningErr.stack)
return this.onWarning(warningErr)
}
this.on('warning', handleWarning)
})
}
private forkConfigProcess () {
const configProcessArgs = ['--projectRoot', this.projectRoot, '--file', this.configFilePath]
// allow the use of ts-node in subprocesses tests by removing the env constant from it
// without this line, packages/ts/register.js never registers the ts-node module for config and
// run_plugins can't use the config module.
const env = _.omit(process.env, 'CYPRESS_INTERNAL_E2E_TESTING_SELF')
env.NODE_OPTIONS = process.env.ORIGINAL_NODE_OPTIONS || ''
const childOptions: ForkOptions = {
stdio: 'pipe',
cwd: path.dirname(this.configFilePath),
env,
execPath: this.nodePath ?? undefined,
}
if (inspector.url()) {
childOptions.execArgv = _.chain(process.execArgv.slice(0))
.remove('--inspect-brk')
.push(`--inspect=${process.debugPort + 1}`)
.value()
}
debug('fork child process %o', { CHILD_PROCESS_FILE_PATH, configProcessArgs, childOptions: _.omit(childOptions, 'env') })
const proc = fork(CHILD_PROCESS_FILE_PATH, configProcessArgs, childOptions)
return proc
}
private handleChildProcessError (err: any, ipc: ProjectConfigIpc, resolved: boolean, reject: (reason?: any) => void) {
debug('plugins process error:', err.stack)
this.cleanupIpc()
err = getError('CONFIG_FILE_UNEXPECTED_ERROR', this.configFile || '(unknown config file)', err)
err.title = 'Config process error'
// this can sometimes trigger before the promise is fulfilled and
// sometimes after, so we need to handle each case differently
if (resolved) {
this.onError(err)
} else {
reject(err)
}
}
cleanupIpc () {
this.killChildProcess()
this.removeAllListeners()
}
private killChildProcess () {
this._childProcess.kill()
this._childProcess.stdout?.removeAllListeners()
this._childProcess.stderr?.removeAllListeners()
this._childProcess.removeAllListeners()
}
}