Repository navigation
Expand file tree
/
Copy pathtestHubModule.ts
More file actions
434 lines (406 loc) · 25.5 KB
/
Copy pathtestHubModule.ts
File metadata and controls
434 lines (406 loc) · 25.5 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
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
import util from 'node:util'
import BaseModule from './baseModule.js'
import { BStackLogger } from '../cliLogger.js'
import TestFramework from '../frameworks/testFramework.js'
import { TestFrameworkState } from '../states/testFrameworkState.js'
import { HookState } from '../states/hookState.js'
import { CLIUtils } from '../cliUtils.js'
import { TestFrameworkConstants } from '../frameworks/constants/testFrameworkConstants.js'
import { GrpcClient } from '../grpcClient.js'
import type TestFrameworkInstance from '../instances/testFrameworkInstance.js'
// eslint-disable-next-line camelcase
import type { LogCreatedEventRequest, LogCreatedEventRequest_LogEntry, TestFrameworkEventRequest, TestSessionEventRequest, AutomationSession } from '../../grpc/index.js'
import type { Frameworks } from '@wdio/types'
import WdioMochaTestFramework from '../frameworks/wdioMochaTestFramework.js'
import type AutomationFrameworkInstance from '../instances/automationFrameworkInstance.js'
import AutomationFramework from '../frameworks/automationFramework.js'
import { AutomationFrameworkConstants } from '../frameworks/constants/automationFrameworkConstants.js'
import { isLoadTestingSession, getLtsSessionId } from '../../util.js'
/**
* TestHub Module for BrowserStack
*/
export default class TestHubModule extends BaseModule {
logger = BStackLogger
testhubConfig: unknown
name: string
static MODULE_NAME = 'TestHubModule'
/**
* Mocha-only: the TEST/POST (TestRunFinished) send deferred past the after-each hook
* window. WDIO fires `afterTest` (which triggers TEST/POST) BEFORE the user's
* `afterEach` hooks run, so custom tags set in `afterEach` would otherwise miss the
* event. The payload (`eventJson`) is serialized from the instance's live data map at
* SEND time, so deferring the send picks up those late merges; uuid / started_at /
* ended_at are already stamped in the data and do not drift. The stashed
* `args.instance` is the finished test's OWN object — INIT_TEST replaces the tracked
* slot with a fresh instance for the next test — so it stays valid across tests.
* Flushed at the next test's first event (INIT_TEST / TEST PRE) or, for the worker's
* last test, from service.after() via flushPendingTestFinishEvent().
*
* SDK-7493: keyed by test uuid, NOT a single slot. wdio does not await `onTestSkip`, so a
* skip report runs detached and can interleave with a live test — its events land between
* the live test's own, on the same per-worker tracked-instance context. With one slot the
* second stash silently REPLACED the first (the old guard only flushed when the instance
* OBJECT differed, and an interleave can present the same object), so one test's
* TestRunFinished was never sent and TRA left it rendering "In Progress" until the ~60-min
* idle reap. A map cannot evict: every deferred finish is delivered, each under its own uuid.
*
* NOTE ON REDUNDANCY: SDK-7493's queue-and-drain (skipReporter) already stops a skip report
* running while a test is in flight, so on the normal path that collision can no longer be
* triggered and this map is not the primary fix. It is retained deliberately as
* defence-in-depth for a reporting path with a real incident history (SDK-7265, SDK-7493,
* ~60-min reaps): if any future caller reintroduces an interleave, the worst case degrades
* to a late send rather than a silently lost TestRunFinished.
*/
private pendingTestFinishes: Map<string, { args: Record<string, unknown>, uuid: string }> = new Map()
/**
* Create a new TestHubModule
*/
constructor(testhubConfig: unknown) {
super()
this.name = 'TestHubModule'
this.testhubConfig = testhubConfig
TestFramework.registerObserver(TestFrameworkState.TEST, HookState.PRE, this.onBeforeTest.bind(this))
Object.values(TestFrameworkState).forEach(state => {
Object.values(HookState).forEach(hook => {
// Pass the event's own state: observers run one after another, and an earlier
// one that awaits (e.g. the Automate session rename after a mid-test reload) lets
// concurrent LOG events overwrite the instance's current state before this runs.
TestFramework.registerObserver(state, hook, (args: Record<string, unknown>) => this.onAllTestEvents(args, state, hook))
})
})
}
/**
* Get the module name
* @returns {string} The module name
*/
getModuleName() {
return TestHubModule.MODULE_NAME
}
onBeforeTest(args: Record<string, unknown>) {
this.logger.debug('onBeforeTest: Called after test hook from cli configured module!!!')
const autoInstance = AutomationFramework.getTrackedInstance() as AutomationFrameworkInstance
const instances = [autoInstance]
args.autoInstance = instances
this.sendTestSessionEvent(args)
}
onAllTestEvents(args: Record<string, unknown>, dispatchedTestState?: State, dispatchedHookState?: State) {
this.logger.debug('onAllTestEvents: Called after all test events from cli configured module!!!')
const instance = args.instance as TestFrameworkInstance
// The instance's current state is shared and moves with every tracked event, so prefer
// the state this observer was dispatched for. Otherwise a TEST/POST that reaches this
// observer after a LOG/POST landed is handled as a log and its finish is never sent.
const testState = dispatchedTestState ?? instance.getCurrentTestState()
const hookState = dispatchedHookState ?? instance.getCurrentHookState()
const keyTestDeferred = TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_DEFERRED)
// A NEW test is starting (INIT_TEST minted a fresh instance) — the previous test's
// after-each hook window is definitively over, so flush its deferred finish first
// (payload build is synchronous, so gRPC send order is preserved).
if (this.pendingTestFinishes.size > 0 && (testState === TestFrameworkState.INIT_TEST || (testState === TestFrameworkState.TEST && hookState === HookState.PRE))) {
this.flushPendingTestFinishEvent()
}
if (testState === TestFrameworkState.LOG) {
this.logger.debug(`onAllTestEvents: TestFrameworkState.LOG - ${testState}`)
const logEntries = WdioMochaTestFramework.getLogEntries(instance, testState, hookState)
if (logEntries && logEntries.length > 0) {
args.logEntries = logEntries
this.sendLogCreatedEvent(args)
WdioMochaTestFramework.clearLogs(instance, testState, hookState)
// Handle LOG state if needed
}
} else if (
testState === TestFrameworkState.TEST &&
hookState === HookState.POST &&
!TestFramework.hasState(instance, TestFrameworkConstants.KEY_TEST_RESULT_AT)
) {
this.logger.info('onAllTestEvents: dropping due to lack of results')
TestFramework.setState(instance, TestFrameworkConstants.KEY_TEST_DEFERRED, true)
} else if (
keyTestDeferred &&
testState === TestFrameworkState.LOG_REPORT &&
hookState === HookState.POST &&
TestFramework.hasState(instance, TestFrameworkConstants.KEY_TEST_RESULT_AT)
) {
// Create a modified args object with updated test framework state
instance.setCurrentTestState(TestFrameworkState.TEST)
this.onAllTestEvents(args, TestFrameworkState.TEST, hookState)
}
if (testState === TestFrameworkState.TEST || CLIUtils.matchHookRegex(testState.toString().split('.')[1])) {
const frameworkName = String(TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) || '')
if (testState === TestFrameworkState.TEST && hookState === HookState.POST && args.holdFinishUntilHooksEnd === true && !frameworkName.toLowerCase().includes('mocha')) {
// The framework stamps ended_at once every TEST/POST observer has run (the a11y
// pre-save scan and save among them) and then calls releaseHeldFinish, so the
// finish never predates work done for this test.
const holdUuid = String(
TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_UUID) || instance.getRef()
)
this.pendingTestFinishes.set(holdUuid, { args, uuid: holdUuid })
args.releaseHeldFinish = () => this.flushTestFinish(holdUuid)
} else if (testState === TestFrameworkState.TEST && hookState === HookState.POST && frameworkName.toLowerCase().includes('mocha')) {
// Defer the TestRunFinished send past the Mocha after-each hook window so
// custom tags set in `afterEach` still make the payload (see field docs).
// SDK-7493: key the stash by the test's uuid, captured NOW. Two different tests
// can present the same tracked instance when a detached skip report interleaves
// with a live test, so keying on the instance object silently dropped one of the
// two finishes. Re-stashing the SAME uuid (e.g. the LOG_REPORT/POST recovery
// re-entry below) correctly replaces only that test's own entry.
const deferUuid = String(
TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_UUID) || instance.getRef()
)
this.pendingTestFinishes.set(deferUuid, { args, uuid: deferUuid })
this.logger.debug(`onAllTestEvents: deferred TEST/POST send past the after-each hook window (uuid=${deferUuid}, pending=${this.pendingTestFinishes.size})`)
} else {
this.sendTestFrameworkEvent(args, {
testFrameworkState: testState.toString().split('.')[1],
testHookState: hookState.toString().split('.')[1]
})
}
}
}
/**
* Send a deferred TEST/POST (TestRunFinished) event, if one is pending. The instance's
* CURRENT state may have moved on (e.g. LOG events during afterEach), so the send uses
* an explicit TEST/POST state override; the payload data itself is read fresh from the
* instance so late custom-tag merges are included. Called from onAllTestEvents at the
* next test's boundary and from service.after() at worker end.
*/
flushPendingTestFinishEvent(): Promise<void> | undefined {
if (this.pendingTestFinishes.size === 0) {
return undefined
}
// Drain every pending finish, not just the newest. Take and clear the whole batch up
// front so a concurrent stash (the detached skip chain) starts a fresh entry rather
// than being swallowed by this in-flight drain.
const batch = [...this.pendingTestFinishes.values()]
this.pendingTestFinishes.clear()
this.logger.debug(`flushPendingTestFinishEvent: sending ${batch.length} deferred TEST/POST event(s)`)
// SDK-7265: this is the only send of a mocha test's TestRunFinished, and the worker's last
// test relies on this single flush from service.after(). A dropped send orphans the test →
// Test Hub reaps it at its ~60-min idle timeout → the passing build is stamped `timeout`.
// Retry with backoff. Each entry is captured locally, so concurrent flushes can't clobber
// one another.
return Promise.all(batch.map((entry) => this.sendDeferredFinish(entry))).then(() => undefined)
}
/**
* Send one held TEST/POST now, if it is still pending. A no-op when an earlier flush (next
* test boundary, worker end) already sent it.
*/
flushTestFinish(uuid: string): Promise<void> {
const entry = this.pendingTestFinishes.get(uuid)
if (!entry) {
return Promise.resolve()
}
this.pendingTestFinishes.delete(uuid)
return this.sendDeferredFinish(entry)
}
private sendDeferredFinish({ args, uuid }: { args: Record<string, unknown>, uuid: string }): Promise<void> {
const maxAttempts = 3
// SDK-7493: pin the uuid captured at DEFER time. The payload is otherwise serialized
// from the instance's live data at send time, and an interleaved skip report can have
// rewritten the uuid on that instance since — which would close the wrong test_run and
// leave this one open forever.
const attempt = (n: number): Promise<void> =>
this.sendTestFrameworkEvent(args, { testFrameworkState: 'TEST', testHookState: 'POST', uuid }).then((sent) => {
if (sent) {
return
}
this.logger.debug(`flushPendingTestFinishEvent: uuid=${uuid} attempt ${n}/${maxAttempts} failed`)
if (n >= maxAttempts) {
this.logger.error(`flushPendingTestFinishEvent: deferred TEST/POST send failed after all retries (uuid=${uuid})`)
return
}
return new Promise<void>((resolve) => setTimeout(resolve, 200 * n)).then(() => attempt(n + 1))
})
return attempt(1)
}
async sendTestFrameworkEvent(args: Record<string, unknown>, stateOverride?: { testFrameworkState: string, testHookState: string, uuid?: string }): Promise<boolean> {
try {
const testArgs = args as { test: Frameworks.Test, instance: TestFrameworkInstance }
const instance = testArgs.instance as TestFrameworkInstance
const trackedContext = instance.getContext()
const testData = instance.getAllData()
const testFrameworkName = testData.get(TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) || ''
const testFrameworkVersion = testData.get(TestFrameworkConstants.KEY_TEST_FRAMEWORK_VERSION) || ''
const startedAt = testData.get(TestFrameworkConstants.KEY_TEST_STARTED_AT) || ''
const endedAt = testData.get(TestFrameworkConstants.KEY_TEST_ENDED_AT) || ''
const testFrameworkState = stateOverride?.testFrameworkState || instance.getCurrentTestState().toString().split('.')[1]
const testHookState = stateOverride?.testHookState || instance.getCurrentHookState().toString().split('.')[1]
this.logger.debug(`sendTestFrameworkEvent for testState: ${testFrameworkState} hookState: ${testHookState}`)
const platformIndex = process.env.WDIO_WORKER_ID ? parseInt(process.env.WDIO_WORKER_ID.split('-')[0]) : 0
// SDK-7493: a deferred flush pins the uuid captured when the finish was stashed;
// reading it live here can pick up another test's uuid if an interleaved skip
// report rewrote it on this instance in the meantime.
const uuid = stateOverride?.uuid || TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_UUID) || instance.getRef()
// Nested values such as test_hooks_started/test_hooks_finished are JS Maps, which
// JSON.stringify would serialise to `{}` and strip the hook data. Convert any Map to
// a plain object so the binary receives populated hook maps.
// SDK-7493: the pinned uuid must go INSIDE event_json too, not just the top-level
// field. The binary routes a mocha test_run on the uuid it parses out of this blob —
// `webdriverio/index.js` does `const event = JSON.parse(eventJson)` and the mocha
// handler builds the test run with `uuid: event.test_uuid` — so a stale `test_uuid`
// here would close the wrong run and leave the deferred one open, which is the very
// failure the pin exists to prevent. Overriding a copy keeps the instance untouched.
const eventData = Object.fromEntries(testData)
if (stateOverride?.uuid) {
eventData[TestFrameworkConstants.KEY_TEST_UUID] = stateOverride.uuid
}
const eventJson = Buffer.from(JSON.stringify(eventData, (_key, value) => value instanceof Map ? Object.fromEntries(value) : value))
const executionContext = { hash: trackedContext.getId(), threadId: trackedContext.getThreadId().toString(), processId: trackedContext.getProcessId().toString() }
const payload: Omit<TestFrameworkEventRequest, 'binSessionId'> = {
platformIndex,
testFrameworkName,
testFrameworkVersion,
testFrameworkState,
testHookState,
startedAt,
endedAt,
uuid,
eventJson,
executionContext
}
this.logger.debug(`sendTestFrameworkEvent payload: ${JSON.stringify(payload)}`)
await GrpcClient.getInstance().testFrameworkEvent(payload)
this.logger.debug(`sendTestFrameworkEvent complete for testState: ${testFrameworkState} hookState: ${testHookState}`)
return true
} catch (error) {
this.logger.error(`Error in sendTestFrameworkEvent: ${util.format(error)}`)
return false
}
}
/**
* Send test session event to the service
* @param args containing test session data
*/
async sendTestSessionEvent(args: Record<string, unknown>): Promise<void> {
this.logger.debug('sendTestSessionEvent: Called')
try {
const instance = args.instance as TestFrameworkInstance
const autoInstances = (args.autoInstance as AutomationFrameworkInstance[]) || []
const trackedContext = instance.getContext()
const testFWName = TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) as string
const testFWVersion = TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_FRAMEWORK_VERSION) as string
const testState = instance.getCurrentTestState().toString().split('.')[1]
const hookState = instance.getCurrentHookState().toString().split('.')[1]
this.logger.debug('sendTestSessionEvent: setup')
const executionContext = {
threadId: trackedContext.getThreadId().toString(),
processId: trackedContext.getProcessId().toString()
}
const payload: Omit<TestSessionEventRequest, 'binSessionId'> = {
testFrameworkName: testFWName,
testFrameworkVersion: testFWVersion,
testFrameworkState: testState.toString(),
testHookState: hookState.toString(),
testUuid: TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_UUID).toString(),
executionContext,
automationSessions: [],
platformIndex: process.env.WDIO_WORKER_ID ? parseInt(process.env.WDIO_WORKER_ID.split('-')[0]) : 0,
capabilities: new Uint8Array()
}
// Try to get capabilities from the first driver
try {
if (autoInstances.length > 0) {
const driver = AutomationFramework.getDriver(autoInstances[0]) as WebdriverIO.Browser // RemoteWebDriver equivalent
const userCaps = JSON.stringify(driver.capabilities)
if (userCaps) {
payload.capabilities = new TextEncoder().encode(userCaps)
}
}
} catch (error) {
this.logger.debug(`Error while getting capabilities from driver: ${error}`)
}
this.logger.debug(`sendTestSessionEvent: instance iteration ${JSON.stringify(autoInstances)}`)
// LTS: BLU runner pods route through a local Selenium hub
// so KEY_IS_BROWSERSTACK_HUB resolves to false — without
// this gate the AutomationSession lands with provider=
// unknown_grid and TestHub's o11y classifier sets
// test_run.origin=UnknownGrid. Mirrors py-sdk 3af3bba6
// (force provider='browserstack' + product='loadTesting'
// under LTS) and 0efca1ae (override frameworkSessionId
// with the LTS pod-iteration env id).
// Hoisted above the loop — env vars are stable for the
// process lifetime, no need to re-read per iteration.
const ltsActive = isLoadTestingSession()
const ltsSessionId = ltsActive ? getLtsSessionId() : ''
// Process automation instances
for (const autoInstance of autoInstances) {
const sessionProvider = ltsActive
? 'browserstack'
: (AutomationFramework.getState(autoInstance, AutomationFrameworkConstants.KEY_IS_BROWSERSTACK_HUB) as boolean
? 'browserstack'
: 'unknown_grid')
// Null-safe: under LTS the local-Selenium AutomationFrameworkInstance
// may not have KEY_FRAMEWORK_SESSION_ID populated yet (the binary's
// hub assigns sessionId later than KEY_IS_BROWSERSTACK_HUB). Without
// the guard, AutomationFramework.getState returns undefined and the
// chained .toString() throws TypeError before the (ltsActive &&
// ltsSessionId) ternary on line 215 has a chance to fall through to
// ltsSessionId. Default to '' so the ternary path stays untouched
// and the non-LTS fall-through is still safe.
const driverFrameworkSessionId = (
AutomationFramework.getState(
autoInstance,
AutomationFrameworkConstants.KEY_FRAMEWORK_SESSION_ID,
)?.toString() ?? ''
)
const automationSession: AutomationSession = {
provider: sessionProvider,
ref: autoInstance.getRef(),
hubUrl: this.config.hubUrl as string,
frameworkSessionId: (ltsActive && ltsSessionId) ? ltsSessionId : driverFrameworkSessionId,
frameworkName: autoInstance.frameworkName,
frameworkVersion: autoInstance.frameworkVersion,
...(ltsActive ? { product: 'loadTesting' } : {})
}
this.logger.debug(`sendTestSessionEvent: automationSession: ${JSON.stringify(automationSession)}`)
payload.platformIndex = process.env.WDIO_WORKER_ID ? parseInt(process.env.WDIO_WORKER_ID.split('-')[0]) : 0
payload.automationSessions.push(automationSession)
}
this.logger.debug(`sendTestSessionEvent payload: ${JSON.stringify(payload)}`)
await GrpcClient.getInstance().testSessionEvent(payload)
this.logger.debug(`sendTestSessionEvent complete for testState: ${testState} hookState: ${hookState}`)
} catch (error) {
this.logger.error(`sendTestSessionEvent: Error sending grpc call: event=${JSON.stringify(args)}, error=${error}`)
throw new Error(`Failed to send test session event: ${error}`)
}
}
async sendLogCreatedEvent(args: Record<string, unknown>) {
try {
const testArgs = args as { test: Frameworks.Test, instance: TestFrameworkInstance }
const logEntries = args.logEntries as Array<Record<string, unknown>>
const instance = testArgs.instance as TestFrameworkInstance
const trackedContext = instance.getContext()
const testData = instance.getAllData()
const testFrameworkName = testData.get(TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) || ''
const testFrameworkVersion = testData.get(TestFrameworkConstants.KEY_TEST_FRAMEWORK_VERSION) || ''
const testFrameworkState = instance.getCurrentTestState().toString().split('.')[1]
const testHookState = instance.getCurrentHookState().toString().split('.')[1]
this.logger.debug(`sendLogCreatedEvent testId: testFrameworkState: ${testFrameworkState} testHookState: ${testHookState}`)
const platformIndex = process.env.WDIO_WORKER_ID ? parseInt(process.env.WDIO_WORKER_ID.split('-')[0]) : 0
const executionContext = { hash: trackedContext.getId(), threadId: trackedContext.getThreadId().toString(), processId: trackedContext.getProcessId().toString() }
const payload: Omit<LogCreatedEventRequest, 'binSessionId'> = {
platformIndex,
logs: [],
executionContext
}
for (const logEntry of logEntries) {
// eslint-disable-next-line camelcase
const logData: LogCreatedEventRequest_LogEntry = {
testFrameworkName,
testFrameworkVersion,
testFrameworkState,
uuid: logEntry[TestFrameworkConstants.KEY_HOOK_ID] || TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_UUID),
kind: logEntry.kind as string,
message: logEntry.message as Uint8Array,
timestamp: logEntry.timestamp as string,
level: logEntry.level as string,
}
payload.logs.push(logData)
}
this.logger.debug(`sendLogCreatedEvent payload: ${JSON.stringify(payload)}`)
await GrpcClient.getInstance().logCreatedEvent(payload)
this.logger.debug(`sendLogCreatedEvent complete for testState: ${testFrameworkState} hookState: ${testHookState}`)
} catch (error) {
this.logger.error(`Error in sendLogCreatedEvent: ${util.format(error)}`)
}
}
}