-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathStudioLifecycleManager.ts
More file actions
389 lines (322 loc) · 11.7 KB
/
Copy pathStudioLifecycleManager.ts
File metadata and controls
389 lines (322 loc) · 11.7 KB
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
import { StudioManager } from './studio'
import { ProtocolManager } from '../protocol'
import Debug from 'debug'
import type { CloudDataSource } from '@packages/data-context/src/sources'
import type { Cfg } from '../../project-base'
import _ from 'lodash'
import type { DataContext } from '@packages/data-context'
import api from '../api'
import { reportStudioError } from '../api/studio/report_studio_error'
import { CloudRequest } from '../api/cloud_request'
import { isRetryableError } from '../network/is_retryable_error'
import { asyncRetry } from '../../util/async_retry'
import { postStudioSession } from '../api/studio/post_studio_session'
import type { StudioStatus } from '@packages/types'
import path from 'path'
import os from 'os'
import { ensureStudioBundle } from './ensure_studio_bundle'
import chokidar from 'chokidar'
import { readFile } from 'fs/promises'
import { getCloudMetadata } from '../get_cloud_metadata'
import { initializeTelemetryReporter, reportTelemetry } from './telemetry/TelemetryReporter'
import { telemetryManager } from './telemetry/TelemetryManager'
import { BUNDLE_LIFECYCLE_MARK_NAMES, BUNDLE_LIFECYCLE_TELEMETRY_GROUP_NAMES } from './telemetry/constants/bundle-lifecycle'
import { INITIALIZATION_TELEMETRY_GROUP_NAMES } from './telemetry/constants/initialization'
import crypto from 'crypto'
const debug = Debug('cypress:server:studio-lifecycle-manager')
const routes = require('../routes')
export class StudioLifecycleManager {
private static hashLoadingMap: Map<string, Promise<Record<string, string>>> = new Map()
private static watcher: chokidar.FSWatcher | null = null
private studioManagerPromise?: Promise<StudioManager | null>
private studioManager?: StudioManager
private listeners: ((studioManager: StudioManager) => void)[] = []
private ctx?: DataContext
private lastStatus?: StudioStatus
public get cloudStudioRequested () {
return !!(process.env.CYPRESS_ENABLE_CLOUD_STUDIO || process.env.CYPRESS_LOCAL_STUDIO_PATH)
}
/**
* Initialize the studio manager and possibly set up protocol.
* Also registers this instance in the data context.
* @param projectId The project ID
* @param cloudDataSource The cloud data source
* @param cfg The project configuration
* @param debugData Debug data for the configuration
* @param ctx Data context to register this instance with
*/
initializeStudioManager ({
projectId,
cloudDataSource,
cfg,
debugData,
ctx,
}: {
projectId?: string
cloudDataSource: CloudDataSource
cfg: Cfg
debugData: any
ctx: DataContext
}): void {
debug('Initializing studio manager')
// Register this instance in the data context
ctx.update((data) => {
data.studioLifecycleManager = this
})
this.ctx = ctx
this.updateStatus('INITIALIZING')
const studioManagerPromise = this.createStudioManager({
projectId,
cloudDataSource,
cfg,
debugData,
}).catch(async (error) => {
debug('Error during studio manager setup: %o', error)
const { cloudUrl, cloudHeaders } = await getCloudMetadata(cloudDataSource)
reportStudioError({
cloudApi: {
cloudUrl,
cloudHeaders,
CloudRequest,
isRetryableError,
asyncRetry,
},
studioHash: projectId,
projectSlug: cfg.projectId,
error,
studioMethod: 'initializeStudioManager',
studioMethodArgs: [],
})
this.updateStatus('IN_ERROR')
// Clean up any registered listeners
this.listeners = []
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.BUNDLE_LIFECYCLE_END)
reportTelemetry(BUNDLE_LIFECYCLE_TELEMETRY_GROUP_NAMES.COMPLETE_BUNDLE_LIFECYCLE, {
success: false,
})
return null
})
this.studioManagerPromise = studioManagerPromise
this.setupWatcher({
projectId,
cloudDataSource,
cfg,
debugData,
})
}
isStudioReady (): boolean {
if (!this.studioManager) {
telemetryManager.addGroupMetadata(INITIALIZATION_TELEMETRY_GROUP_NAMES.INITIALIZE_STUDIO, {
studioRequestedBeforeReady: true,
})
}
return !!this.studioManager
}
async getStudio () {
if (!this.studioManagerPromise) {
throw new Error('Studio manager has not been initialized')
}
const studioManager = await this.studioManagerPromise
if (studioManager) {
this.updateStatus(studioManager.status)
}
return studioManager
}
private async createStudioManager ({
projectId,
cloudDataSource,
cfg,
debugData,
}: {
projectId?: string
cloudDataSource: CloudDataSource
cfg: Cfg
debugData: any
}): Promise<StudioManager> {
let studioPath: string
let studioHash: string
let manifest: Record<string, string>
initializeTelemetryReporter({
projectSlug: projectId,
cloudDataSource,
})
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.BUNDLE_LIFECYCLE_START)
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.POST_STUDIO_SESSION_START)
const studioSession = await postStudioSession({
projectId,
})
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.POST_STUDIO_SESSION_END)
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.ENSURE_STUDIO_BUNDLE_START)
if (!process.env.CYPRESS_LOCAL_STUDIO_PATH) {
// The studio hash is the last part of the studio URL, after the last slash and before the extension
studioHash = studioSession.studioUrl.split('/').pop()?.split('.')[0]
studioPath = path.join(os.tmpdir(), 'cypress', 'studio', studioHash)
let hashLoadingPromise = StudioLifecycleManager.hashLoadingMap.get(studioHash)
if (!hashLoadingPromise) {
hashLoadingPromise = ensureStudioBundle({
studioUrl: studioSession.studioUrl,
studioPath,
projectId,
})
StudioLifecycleManager.hashLoadingMap.set(studioHash, hashLoadingPromise)
}
manifest = await hashLoadingPromise
} else {
studioPath = process.env.CYPRESS_LOCAL_STUDIO_PATH
studioHash = 'local'
manifest = {}
}
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.ENSURE_STUDIO_BUNDLE_END)
const serverFilePath = path.join(studioPath, 'server', 'index.js')
const script = await readFile(serverFilePath, 'utf8')
const expectedHash = manifest[path.join('server', 'index.js')]
// TODO: once the services have deployed, we should remove this check
if (expectedHash) {
const actualHash = crypto.createHash('sha256').update(script).digest('hex')
if (!process.env.CYPRESS_LOCAL_STUDIO_PATH && actualHash !== expectedHash) {
throw new Error('Invalid hash for studio server script')
}
}
const studioManager = new StudioManager()
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_MANAGER_SETUP_START)
const { cloudUrl, cloudHeaders } = await getCloudMetadata(cloudDataSource)
await studioManager.setup({
script,
studioPath,
studioHash,
projectSlug: projectId,
cloudApi: {
cloudUrl,
cloudHeaders,
CloudRequest,
isRetryableError,
asyncRetry,
},
shouldEnableStudio: this.cloudStudioRequested,
manifest,
})
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_MANAGER_SETUP_END)
if (studioManager.status === 'ENABLED') {
debug('Cloud studio is enabled - setting up protocol')
const protocolManager = new ProtocolManager()
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_PROTOCOL_GET_START)
const script = await api.getCaptureProtocolScript(studioSession.protocolUrl)
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_PROTOCOL_GET_END)
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_PROTOCOL_PREPARE_START)
await protocolManager.prepareProtocol(script, {
runId: 'studio',
projectId: cfg.projectId,
testingType: cfg.testingType,
cloudApi: {
url: routes.apiUrl,
retryWithBackoff: api.retryWithBackoff,
requestPromise: api.rp,
},
projectConfig: _.pick(cfg, ['devServerPublicPathRoute', 'port', 'proxyUrl', 'namespace']),
mountVersion: api.runnerCapabilities.protocolMountVersion,
debugData,
mode: 'studio',
})
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.STUDIO_PROTOCOL_PREPARE_END)
studioManager.protocolManager = protocolManager
} else {
debug('Cloud studio is not enabled - skipping protocol setup')
}
debug('Studio is ready')
this.studioManager = studioManager
this.callRegisteredListeners()
this.updateStatus(studioManager.status)
telemetryManager.mark(BUNDLE_LIFECYCLE_MARK_NAMES.BUNDLE_LIFECYCLE_END)
reportTelemetry(BUNDLE_LIFECYCLE_TELEMETRY_GROUP_NAMES.COMPLETE_BUNDLE_LIFECYCLE, {
success: true,
})
return studioManager
}
private callRegisteredListeners () {
if (!this.studioManager) {
throw new Error('Studio manager has not been initialized')
}
const studioManager = this.studioManager
debug('Calling all studio ready listeners')
this.listeners.forEach((listener) => {
listener(studioManager)
})
if (!process.env.CYPRESS_LOCAL_STUDIO_PATH) {
this.listeners = []
}
}
private setupWatcher ({
projectId,
cloudDataSource,
cfg,
debugData,
}: {
projectId?: string
cloudDataSource: CloudDataSource
cfg: Cfg
debugData: any
}) {
// Don't setup a watcher if the studio bundle is NOT local
if (!process.env.CYPRESS_LOCAL_STUDIO_PATH) {
return
}
// Close the watcher if a previous watcher exists
if (StudioLifecycleManager.watcher) {
StudioLifecycleManager.watcher.removeAllListeners()
StudioLifecycleManager.watcher.close().catch(() => {})
}
// Watch for changes to the studio bundle
StudioLifecycleManager.watcher = chokidar.watch(path.join(process.env.CYPRESS_LOCAL_STUDIO_PATH, 'server', 'index.js'), {
awaitWriteFinish: true,
}).on('change', async () => {
await this.studioManager?.destroy()
this.studioManager = undefined
this.studioManagerPromise = this.createStudioManager({
projectId,
cloudDataSource,
cfg,
debugData,
}).then((studioManager) => {
// eslint-disable-next-line no-console
console.log('Studio manager reloaded')
return studioManager
}).catch((error) => {
// eslint-disable-next-line no-console
console.error('Error during reload of studio manager: %o', error)
return null
})
})
}
/**
* Register a listener that will be called when the studio is ready
* @param listener Function to call when studio is ready
*/
registerStudioReadyListener (listener: (studioManager: StudioManager) => void): void {
// if there is already a studio manager, call the listener immediately
if (this.studioManager) {
debug('Studio ready - calling listener immediately')
listener(this.studioManager)
// If the studio bundle is local, we need to register the listener
// so that we can reload the studio when the bundle changes
if (process.env.CYPRESS_LOCAL_STUDIO_PATH) {
this.listeners.push(listener)
}
} else {
debug('Studio not ready - registering studio ready listener')
this.listeners.push(listener)
}
}
public updateStatus (status: StudioStatus) {
if (status === this.lastStatus) {
debug('Studio status unchanged: %s', status)
return
}
debug('Studio status changed: %s → %s', this.lastStatus, status)
this.lastStatus = status
if (this.ctx) {
this.ctx?.emitter.studioStatusChange()
} else {
debug('No ctx available, cannot emit studioStatusChange')
}
}
}