From 009d0dbf253ba2d44d1d6da4c98760cdc2ab36e8 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Tue, 1 Dec 2026 15:15:43 +0530 Subject: [PATCH 01/13] feat: report DriverInitFailure when a worker cannot create its session When the WebDriver new-session request fails or hits connectionRetryTimeout, the WDIO runner calls the service's `after` hook without ever calling `before`. Detect that in the worker (same path for the CLI and direct flows, since only the client sees the outcome) and send one `DriverInitFailure` sdk_events record to EDS, keyed by the TestHub build uuid, with the same payload shape as the Node SDK. The send is bounded, resent only when EDS sheds it with 429/503, and never throws into the run. Co-Authored-By: Claude Opus 5.5 --- .changeset/driver-init-failure-event.md | 5 + .../browserstack-service/src/constants.ts | 7 + .../instrumentation/funnelInstrumentation.ts | 127 +++++++++++++++++- packages/browserstack-service/src/service.ts | 28 ++++ .../funnelInstrumentation.test.ts | 105 +++++++++++++++ .../tests/service.test.ts | 76 +++++++++++ 6 files changed, 346 insertions(+), 2 deletions(-) create mode 100644 .changeset/driver-init-failure-event.md diff --git a/.changeset/driver-init-failure-event.md b/.changeset/driver-init-failure-event.md new file mode 100644 index 00000000..74ed5ccc --- /dev/null +++ b/.changeset/driver-init-failure-event.md @@ -0,0 +1,5 @@ +--- +"@wdio/browserstack-service": patch +--- + +Report an SDK diagnostic event when a worker cannot create its WebDriver session (for example a new-session error or a `connectionRetryTimeout` hit while the session is starting), so failed session starts are visible in BrowserStack build diagnostics. Sending the event never affects the test run. diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index 1353ca4b..847e84fa 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -165,6 +165,13 @@ export const FUNNEL_INSTRUMENTATION_URL = 'https://api.browserstack.com/sdk/v1/e export const EDS_URL = 'https://eds.browserstack.com' +export const DRIVER_INIT_FAILURE_EVENT = 'DriverInitFailure' +export const DRIVER_INIT_FAILURE_EVENT_TAG = 'sdk:driver:init:failure' +export const MAX_DRIVER_INIT_ERROR_BYTES = 8000 +export const DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS = 5000 +export const DRIVER_INIT_FAILURE_MAX_ATTEMPTS = 4 +export const DRIVER_INIT_FAILURE_RETRY_BASE_MS = 500 + // Smart Selection Mode Constants export const SMART_SELECTION_MODE_RELEVANT_FIRST = 'relevantFirst' export const SMART_SELECTION_MODE_RELEVANT_ONLY = 'relevantOnly' diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 740caedf..37014b45 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -5,10 +5,20 @@ import fs from 'node:fs' import UsageStats, { type UsageStat } from '../testOps/usageStats.js' import { BStackLogger } from '../bstackLogger.js' import type BrowserStackConfig from '../config.js' -import { BSTACK_SERVICE_VERSION, WDIO_NAMING_PREFIX } from '../constants.js' +import { + BSTACK_SERVICE_VERSION, + WDIO_NAMING_PREFIX, + BROWSERSTACK_TESTHUB_UUID, + DRIVER_INIT_FAILURE_EVENT, + DRIVER_INIT_FAILURE_EVENT_TAG, + MAX_DRIVER_INIT_ERROR_BYTES, + DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, + DRIVER_INIT_FAILURE_MAX_ATTEMPTS, + DRIVER_INIT_FAILURE_RETRY_BASE_MS +} from '../constants.js' import { getDataFromWorkers } from '../data-store.js' import { getProductMap } from '../testHub/utils.js' -import fetchWrap from '../fetchWrapper.js' +import fetchWrap, { _fetch } from '../fetchWrapper.js' import type { FunnelData, EventProperties } from '../types.js' import TestOpsConfig from '../testOps/testOpsConfig.js' import APIUtils from '../cli/apiUtils.js' @@ -198,3 +208,116 @@ function getReferrer(framework?: string) { const fullName = framework ? WDIO_NAMING_PREFIX + framework : 'WebdriverIO' return `${fullName}/${BSTACK_SERVICE_VERSION}` } + +export interface DriverInitFailureDetails { + userName?: string + accessKey?: string + framework?: string + errorMessage: string +} + +function truncateToBytes(value: string, maxBytes: number) { + const buf = Buffer.from(value, 'utf8') + if (buf.length <= maxBytes) { + return value + } + return new TextDecoder('utf-8', { fatal: false }).decode(buf.subarray(0, maxBytes)) +} + +function formatCreatedDay(date = new Date()) { + return new Intl.DateTimeFormat('en-GB', { + timeZone: 'UTC', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + fractionalSecondDigits: 3, + hour12: false + }) + .formatToParts(date) + .map(({ type, value }) => type === 'timeZoneName' ? 'Z' : value) + .join('') + .replace(',', 'T') +} + +export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { + const testhubUuid = process.env[BROWSERSTACK_TESTHUB_UUID] || null + const workerId = process.env.WDIO_WORKER_ID + const platformIndex = workerId ? parseInt(workerId.split('-')[0], 10) || 0 : 0 + return { + event_type: 'sdk_events', + data: { + testhub_uuid: testhubUuid, + created_day: formatCreatedDay(), + event_name: DRIVER_INIT_FAILURE_EVENT, + user_data: details.userName || null, + host_info: { + hostname: os.hostname(), + platform: os.platform(), + type: os.type(), + version: os.version(), + arch: os.arch() + }, + event_json: { + errorMessage: truncateToBytes(`[DriverInitError] ${details.errorMessage}`, MAX_DRIVER_INIT_ERROR_BYTES), + framework: details.framework ? WDIO_NAMING_PREFIX + details.framework : 'unknown', + driverType: 'webdriverio', + event: DRIVER_INIT_FAILURE_EVENT_TAG, + timestamp: Date.now(), + worker: workerId || String(process.pid), + platform: platformIndex, + sdkRunId: testhubUuid + } + } + } +} + +async function postDriverInitFailure(body: string, encodedAuth: string) { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS) + timer.unref?.() + try { + return await _fetch(`${APIUtils.EDS_URL}/send_sdk_events`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + Authorization: `Basic ${encodedAuth}` + }, + body, + signal: controller.signal + }) + } finally { + clearTimeout(timer) + } +} + +export async function sendDriverInitFailure(details: DriverInitFailureDetails): Promise { + try { + if (!details.userName || !details.accessKey) { + return + } + const payload = buildDriverInitFailurePayload(details) + BStackLogger.debug(`${DRIVER_INIT_FAILURE_EVENT} payload ${JSON.stringify(payload.data.event_json)}`) + const body = JSON.stringify(payload) + const encodedAuth = Buffer.from(`${details.userName}:${details.accessKey}`, 'utf8').toString('base64') + + // workers whose sessions fail together post at the same instant and EDS sheds the burst + // with 429/503 before processing it; anything else may have landed, so it is not resent + for (let attempt = 1; attempt <= DRIVER_INIT_FAILURE_MAX_ATTEMPTS; attempt++) { + const { status } = await postDriverInitFailure(body, encodedAuth) + if (status !== 429 && status !== 503) { + BStackLogger.debug(`Sent EDS event ${DRIVER_INIT_FAILURE_EVENT} | Status ${status}`) + return + } + if (attempt < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { + const delay = DRIVER_INIT_FAILURE_RETRY_BASE_MS * attempt * (1 + Math.random() * 2) + await new Promise((resolve) => setTimeout(resolve, delay)) + } + } + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT} after ${DRIVER_INIT_FAILURE_MAX_ATTEMPTS} attempts`) + } catch (error) { + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT}: ${format(error)}`) + } +} diff --git a/packages/browserstack-service/src/service.ts b/packages/browserstack-service/src/service.ts index 055ffd30..7e899fff 100644 --- a/packages/browserstack-service/src/service.ts +++ b/packages/browserstack-service/src/service.ts @@ -35,6 +35,7 @@ import { shouldProcessEventForTesthub } from './testHub/utils.js' import PerformanceTester from './instrumentation/performance/performance-tester.js' import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants.js' import { EVENTS } from './instrumentation/performance/constants.js' +import { sendDriverInitFailure } from './instrumentation/funnelInstrumentation.js' import { BrowserstackCLI } from './cli/index.js' import { drainSkipReports, markTestStarted, reportSuiteSkipped } from './cli/skipReporter.js' import { CLIUtils } from './cli/cliUtils.js' @@ -91,6 +92,9 @@ export default class BrowserstackService implements Services.ServiceInstance { // @wdio/mocha-framework 10 defaults mocha's `failHookAffectedTests` on: tests behind a // failed before/beforeEach hook are failed rather than dropped private _mochaFailHookAffectedTests: boolean = false + private _sessionInitAttempted: boolean = false + private _sessionCreated: boolean = false + private _driverInitFailureReported: boolean = false constructor ( options: BrowserstackConfig & Options.Testrunner, @@ -150,6 +154,7 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'beforeSession' }) async beforeSession(config: Omit, capabilities: WebdriverIO.Capabilities) { + this._sessionInitAttempted = true PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.INIT) // if no user and key is specified even though a browserstack service was @@ -216,6 +221,7 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'before' }) async before(caps: Capabilities.ResolvedTestrunnerCapabilities, specs: string[], browser: WebdriverIO.Browser) { + this._sessionCreated = true // End device allocation tracking - remote session is now created and browser object is available PerformanceTester.end(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_DEVICE_ALLOCATION, true, 'Device allocated and session created') BStackLogger.debug('Device allocation tracking ended - remote session created successfully') @@ -672,6 +678,10 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'after' }) async after (result: number) { + // wdio calls `after` without `before` only when the worker could not create its session + if (this._sessionInitAttempted && !this._sessionCreated) { + await this._reportDriverInitFailure() + } try { PerformanceTester.start(PERFORMANCE_SDK_EVENTS.HOOK_EVENTS.AFTER) PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.QUIT) @@ -1078,6 +1088,24 @@ export default class BrowserstackService implements Services.ServiceInstance { return Boolean(isBrowserstackSession(this._browser)) && BrowserstackCLI.getInstance().isRunning() } + async _reportDriverInitFailure() { + if (this._driverInitFailureReported) { + return + } + this._driverInitFailureReported = true + try { + const { hostname, connectionRetryTimeout, connectionRetryCount } = this._config + await sendDriverInitFailure({ + userName: this._config.user, + accessKey: this._config.key, + framework: this._config.framework, + errorMessage: `WebdriverIO session could not be created (hostname=${hostname}, connectionRetryTimeout=${connectionRetryTimeout}ms, connectionRetryCount=${connectionRetryCount})` + }) + } catch (err) { + BStackLogger.debug(`Exception reporting driver init failure: ${util.format(err)}`) + } + } + @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'onReload' }) async onReload(oldSessionId: string, newSessionId: string) { if (!this._browser) { diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index 5e143d87..a3d7adfd 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -125,3 +125,108 @@ describe('funnelInstrumentation', () => { })) }) }) + +describe('DriverInitFailure', () => { + beforeEach(() => { + process.env.BROWSERSTACK_TESTHUB_UUID = 'testhub-uuid-1' + process.env.WDIO_WORKER_ID = '2-1' + vi.mocked(fetch).mockReturnValue(Promise.resolve(Response.json({}))) + }) + + afterEach(() => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + delete process.env.WDIO_WORKER_ID + vi.mocked(fetch).mockReset() + }) + + it('builds the sdk_events payload keyed by the TestHub build uuid', () => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ userName: 'user', accessKey: 'key', framework: 'mocha', errorMessage: 'boom' }) + + expect(payload.event_type).toBe('sdk_events') + expect(Object.keys(payload.data)).toEqual(['testhub_uuid', 'created_day', 'event_name', 'user_data', 'host_info', 'event_json']) + expect(payload.data).toMatchObject({ testhub_uuid: 'testhub-uuid-1', event_name: 'DriverInitFailure', user_data: 'user' }) + expect(payload.data.created_day).toMatch(/^\d{2}\/\d{2}\/\d{4}T \d{2}:\d{2}:\d{2}\.\d{3}$/) + expect(Object.keys(payload.data.host_info)).toEqual(['hostname', 'platform', 'type', 'version', 'arch']) + expect(payload.data.event_json).toEqual({ + errorMessage: '[DriverInitError] boom', + framework: 'WebdriverIO-mocha', + driverType: 'webdriverio', + event: 'sdk:driver:init:failure', + timestamp: expect.any(Number), + worker: '2-1', + platform: 2, + sdkRunId: 'testhub-uuid-1' + }) + }) + + it('sends null testhub_uuid when the build uuid is not known', () => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBeNull() + expect(payload.data.event_json.framework).toBe('unknown') + }) + + it('caps the error message at 8000 bytes', () => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'é'.repeat(10000) }) + + expect(Buffer.byteLength(payload.data.event_json.errorMessage, 'utf8')).toBeLessThanOrEqual(8000) + }) + + it('posts to the EDS send_sdk_events endpoint with basic auth', async () => { + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', framework: 'mocha', errorMessage: 'boom' }) + + expect(fetch).toHaveBeenCalledTimes(1) + const [url, init] = vi.mocked(fetch).mock.calls[0] + expect(url).toBe('https://eds.browserstack.com/send_sdk_events') + expect(init).toMatchObject({ + method: 'POST', + headers: { 'content-type': 'application/json', Authorization: `Basic ${Buffer.from('user:key').toString('base64')}` } + }) + expect(JSON.parse(init!.body as string).data.event_name).toBe('DriverInitFailure') + }) + + it('sends nothing without credentials', async () => { + await FunnelTestEvent.sendDriverInitFailure({ framework: 'mocha', errorMessage: 'boom' }) + + expect(fetch).not.toHaveBeenCalled() + }) + + it('resends only while EDS sheds the request with 429/503', async () => { + vi.useFakeTimers() + vi.mocked(fetch) + .mockReturnValueOnce(Promise.resolve(new Response('', { status: 503 }))) + .mockReturnValueOnce(Promise.resolve(new Response('', { status: 429 }))) + .mockReturnValueOnce(Promise.resolve(Response.json({}))) + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + vi.useRealTimers() + + expect(fetch).toHaveBeenCalledTimes(3) + }) + + it('gives up after four attempts', async () => { + vi.useFakeTimers() + vi.mocked(fetch).mockImplementation(() => Promise.resolve(new Response('', { status: 503 }))) + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + vi.useRealTimers() + + expect(fetch).toHaveBeenCalledTimes(4) + }) + + it('does not resend a request that may have landed', async () => { + vi.mocked(fetch).mockReturnValueOnce(Promise.resolve(new Response('', { status: 500 }))) + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + + expect(fetch).toHaveBeenCalledTimes(1) + }) + + it('never throws when the request fails', async () => { + vi.mocked(fetch).mockReturnValue(Promise.reject(new Error('network down'))) + + await expect(FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' })).resolves.toBeUndefined() + }) +}) diff --git a/packages/browserstack-service/tests/service.test.ts b/packages/browserstack-service/tests/service.test.ts index 323ecd53..7c11091d 100644 --- a/packages/browserstack-service/tests/service.test.ts +++ b/packages/browserstack-service/tests/service.test.ts @@ -3352,3 +3352,79 @@ describe('mocha failHookAffectedTests: tests behind a failed hook', () => { expect(afterHook.mock.calls[1][2]).toBeUndefined() }) }) + +describe('DriverInitFailure when the worker cannot create its session', () => { + const realAfter = BrowserstackService.prototype.after + const edsCalls = () => vi.mocked(fetch).mock.calls + .filter(([url]) => String(url).endsWith('/send_sdk_events')) + .map(([, init]) => JSON.parse((init as RequestInit).body as string)) + const makeService = () => new BrowserstackService( + { testObservability: false } as never, + [] as never, + { user: 'foo', key: 'bar', framework: 'jasmine', hostname: 'hub.browserstack.com', connectionRetryTimeout: 1500, connectionRetryCount: 0 } as never + ) + + beforeEach(() => { + vi.useRealTimers() + process.env.BROWSERSTACK_TESTHUB_UUID = 'testhub-uuid-1' + process.env.WDIO_WORKER_ID = '1-0' + }) + + afterEach(() => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + delete process.env.WDIO_WORKER_ID + vi.useFakeTimers().setSystemTime(new Date('2020-01-01')) + }) + + it('sends exactly one DriverInitFailure when after() runs without before()', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + await realAfter.call(svc, 1) + await realAfter.call(svc, 1) + + const events = edsCalls() + expect(events).toHaveLength(1) + expect(events[0].event_type).toBe('sdk_events') + expect(events[0].data).toMatchObject({ + testhub_uuid: 'testhub-uuid-1', + event_name: 'DriverInitFailure', + user_data: 'foo' + }) + expect(events[0].data.event_json).toMatchObject({ + framework: 'WebdriverIO-jasmine', + driverType: 'webdriverio', + event: 'sdk:driver:init:failure', + worker: '1-0', + platform: 1, + sdkRunId: 'testhub-uuid-1' + }) + expect(events[0].data.event_json.errorMessage).toContain('[DriverInitError] WebdriverIO session could not be created') + expect(events[0].data.event_json.errorMessage).toContain('connectionRetryTimeout=1500ms') + }) + + it('sends nothing when the session was created', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + await svc.before({} as never, [], browser as WebdriverIO.Browser) + await realAfter.call(svc, 0) + + expect(edsCalls()).toHaveLength(0) + }) + + it('sends nothing when no session was attempted', async () => { + await realAfter.call(makeService(), 1) + + expect(edsCalls()).toHaveLength(0) + }) + + it('does not fail after() when the event cannot be sent', async () => { + const svc = makeService() + await svc.beforeSession({ user: 'foo', key: 'bar' } as never, {} as never) + vi.mocked(fetch).mockImplementation((url) => String(url).endsWith('/send_sdk_events') + ? Promise.reject(new Error('network down')) + : Promise.resolve(Response.json({}))) + + await expect(realAfter.call(svc, 1)).resolves.not.toThrow() + expect(edsCalls()).toHaveLength(1) + }) +}) From 7d545de6cc6e85104b0fb05ccc78b15b77b00c97 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Tue, 1 Dec 2026 16:14:33 +0530 Subject: [PATCH 02/13] fix: send DriverInitFailure created_day in ISO UTC Co-Authored-By: Claude Opus 5.5 --- .../instrumentation/funnelInstrumentation.ts | 18 ++---------------- .../funnelInstrumentation.test.ts | 8 +++++++- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 37014b45..17739900 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -224,22 +224,8 @@ function truncateToBytes(value: string, maxBytes: number) { return new TextDecoder('utf-8', { fatal: false }).decode(buf.subarray(0, maxBytes)) } -function formatCreatedDay(date = new Date()) { - return new Intl.DateTimeFormat('en-GB', { - timeZone: 'UTC', - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - fractionalSecondDigits: 3, - hour12: false - }) - .formatToParts(date) - .map(({ type, value }) => type === 'timeZoneName' ? 'Z' : value) - .join('') - .replace(',', 'T') +export function formatCreatedDay(date = new Date()) { + return `${date.toISOString().slice(0, 23)}000 UTC` } export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index a3d7adfd..db40cbec 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -145,7 +145,7 @@ describe('DriverInitFailure', () => { expect(payload.event_type).toBe('sdk_events') expect(Object.keys(payload.data)).toEqual(['testhub_uuid', 'created_day', 'event_name', 'user_data', 'host_info', 'event_json']) expect(payload.data).toMatchObject({ testhub_uuid: 'testhub-uuid-1', event_name: 'DriverInitFailure', user_data: 'user' }) - expect(payload.data.created_day).toMatch(/^\d{2}\/\d{2}\/\d{4}T \d{2}:\d{2}:\d{2}\.\d{3}$/) + expect(payload.data.created_day).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6} UTC$/) expect(Object.keys(payload.data.host_info)).toEqual(['hostname', 'platform', 'type', 'version', 'arch']) expect(payload.data.event_json).toEqual({ errorMessage: '[DriverInitError] boom', @@ -159,6 +159,12 @@ describe('DriverInitFailure', () => { }) }) + it('formats created_day as UTC ISO with microseconds and a UTC suffix', () => { + expect(FunnelTestEvent.formatCreatedDay(new Date('2026-12-01T09:41:04.106Z'))).toBe('2026-12-01T09:41:04.106000 UTC') + expect(FunnelTestEvent.formatCreatedDay(new Date('2026-03-25T23:59:59.007Z'))).toBe('2026-03-25T23:59:59.007000 UTC') + expect(FunnelTestEvent.formatCreatedDay(new Date('2026-12-01T23:30:00.000-05:00'))).toBe('2026-12-02T04:30:00.000000 UTC') + }) + it('sends null testhub_uuid when the build uuid is not known', () => { delete process.env.BROWSERSTACK_TESTHUB_UUID const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) From e03b3a49c68df9b1b50db00818a40948a551df16 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Tue, 1 Dec 2026 19:03:47 +0530 Subject: [PATCH 03/13] fix: send sdk_events created_day in ISO UTC Co-Authored-By: Claude Opus 5.5 --- .changeset/sdk-events-created-day-iso.md | 5 +++++ .../performance/performance-tester.ts | 20 +------------------ .../tests/performance-tester.test.ts | 20 +++++++++++++++++++ 3 files changed, 26 insertions(+), 19 deletions(-) create mode 100644 .changeset/sdk-events-created-day-iso.md diff --git a/.changeset/sdk-events-created-day-iso.md b/.changeset/sdk-events-created-day-iso.md new file mode 100644 index 00000000..2336fc1a --- /dev/null +++ b/.changeset/sdk-events-created-day-iso.md @@ -0,0 +1,5 @@ +--- +"@wdio/browserstack-service": patch +--- + +Send the `created_day` timestamp of SDK performance events in ISO UTC format (`YYYY-MM-DDTHH:MM:SS.ffffff UTC`), so events sent on the first twelve days of a month are no longer recorded against the wrong date. diff --git a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts index cab42641..e17000e4 100644 --- a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts +++ b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts @@ -405,25 +405,7 @@ export default class PerformanceTester { }) } measures = ensureEpochTimes(measures) - const date = new Date() - // yyyy-MM-dd'T'HH:mm:ss.SSSSSS Z - const options: Intl.DateTimeFormatOptions = { - timeZone: 'UTC', - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - fractionalSecondDigits: 3, // To include microseconds - hour12: false - } - // Format the date and replace the default separator for time zone - const formattedDate = new Intl.DateTimeFormat('en-GB', options) - .formatToParts(date) - .map(({ type, value }) => type === 'timeZoneName' ? 'Z' : value) - .join('') - .replace(',', 'T') + const formattedDate = `${new Date().toISOString().slice(0, 23)}000 UTC` this.end(EVENTS.SDK_KEY_METRICS_PREPARATION, true) const payload = { diff --git a/packages/browserstack-service/tests/performance-tester.test.ts b/packages/browserstack-service/tests/performance-tester.test.ts index 3b41cb3b..3aca38f8 100644 --- a/packages/browserstack-service/tests/performance-tester.test.ts +++ b/packages/browserstack-service/tests/performance-tester.test.ts @@ -214,4 +214,24 @@ describe('PerformanceTester', function () { ) }) }) + describe('uploadEventsData', () => { + afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() + }) + + it('sends created_day as UTC ISO with microseconds and a UTC suffix', async () => { + vi.useFakeTimers({ now: new Date('2026-12-01T09:41:04.106Z'), toFake: ['Date'] }) + ;(fsPromises as any).access = vi.fn().mockRejectedValue(new Error('missing')) + const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 })) + vi.stubGlobal('fetch', fetchMock) + + await PerformanceTester.uploadEventsData() + + expect(fetchMock).toHaveBeenCalledTimes(1) + const body = JSON.parse(fetchMock.mock.calls[0][1].body) + expect(body.data.event_name).toBe('SDKFeaturePerformance') + expect(body.data.created_day).toBe('2026-12-01T09:41:04.106000 UTC') + }) + }) }) From f5d579f5fb3f027c4ee3e6e78792e1af3cbd1d78 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Tue, 1 Dec 2026 22:05:51 +0530 Subject: [PATCH 04/13] chore: drop manual changesets; release notes come from the PR body --- .changeset/driver-init-failure-event.md | 5 ----- .changeset/sdk-events-created-day-iso.md | 5 ----- 2 files changed, 10 deletions(-) delete mode 100644 .changeset/driver-init-failure-event.md delete mode 100644 .changeset/sdk-events-created-day-iso.md diff --git a/.changeset/driver-init-failure-event.md b/.changeset/driver-init-failure-event.md deleted file mode 100644 index 74ed5ccc..00000000 --- a/.changeset/driver-init-failure-event.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@wdio/browserstack-service": patch ---- - -Report an SDK diagnostic event when a worker cannot create its WebDriver session (for example a new-session error or a `connectionRetryTimeout` hit while the session is starting), so failed session starts are visible in BrowserStack build diagnostics. Sending the event never affects the test run. diff --git a/.changeset/sdk-events-created-day-iso.md b/.changeset/sdk-events-created-day-iso.md deleted file mode 100644 index 2336fc1a..00000000 --- a/.changeset/sdk-events-created-day-iso.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"@wdio/browserstack-service": patch ---- - -Send the `created_day` timestamp of SDK performance events in ISO UTC format (`YYYY-MM-DDTHH:MM:SS.ffffff UTC`), so events sent on the first twelve days of a month are no longer recorded against the wrong date. From f6ebfb8f97b81b5e33fdf08605f44322c19d795b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:37:25 +0000 Subject: [PATCH 05/13] chore(changeset): auto-generate from PR template (minor) --- .changeset/pr-403.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/pr-403.md diff --git a/.changeset/pr-403.md b/.changeset/pr-403.md new file mode 100644 index 00000000..6394b167 --- /dev/null +++ b/.changeset/pr-403.md @@ -0,0 +1,5 @@ +--- +"@wdio/browserstack-service": minor +--- + +- Improved diagnostics when a test session fails to start. From 36c3546f5f4beadb5ba2a4113168c9ff768c050b Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Wed, 2 Dec 2026 16:31:44 +0530 Subject: [PATCH 06/13] fix: bound DriverInitFailure send to a 10s deadline and share created_day formatter The awaited send in the worker after hook could hold teardown for about 29s (4 attempts x 5s timeout plus backoff). All attempts now share a 10s deadline: each attempt's timeout is capped at the time remaining, a backoff that would overrun it is skipped, and sending stops once it is spent. Resends stay limited to 429/503 and at most 4 attempts. formatCreatedDay moves to its own module so performance-tester can use it without an import cycle through funnelInstrumentation. Co-Authored-By: Claude Opus 5.5 --- .../browserstack-service/src/constants.ts | 1 + .../src/instrumentation/createdDay.ts | 3 + .../instrumentation/funnelInstrumentation.ts | 35 ++++++---- .../performance/performance-tester.ts | 3 +- .../funnelInstrumentation.test.ts | 70 ++++++++++++++++++- 5 files changed, 95 insertions(+), 17 deletions(-) create mode 100644 packages/browserstack-service/src/instrumentation/createdDay.ts diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index 847e84fa..7b5e9908 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -171,6 +171,7 @@ export const MAX_DRIVER_INIT_ERROR_BYTES = 8000 export const DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS = 5000 export const DRIVER_INIT_FAILURE_MAX_ATTEMPTS = 4 export const DRIVER_INIT_FAILURE_RETRY_BASE_MS = 500 +export const DRIVER_INIT_FAILURE_DEADLINE_MS = 10000 // Smart Selection Mode Constants export const SMART_SELECTION_MODE_RELEVANT_FIRST = 'relevantFirst' diff --git a/packages/browserstack-service/src/instrumentation/createdDay.ts b/packages/browserstack-service/src/instrumentation/createdDay.ts new file mode 100644 index 00000000..65b04ee9 --- /dev/null +++ b/packages/browserstack-service/src/instrumentation/createdDay.ts @@ -0,0 +1,3 @@ +export function formatCreatedDay(date = new Date()) { + return `${date.toISOString().slice(0, 23)}000 UTC` +} diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 17739900..5e258504 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -14,7 +14,8 @@ import { MAX_DRIVER_INIT_ERROR_BYTES, DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, DRIVER_INIT_FAILURE_MAX_ATTEMPTS, - DRIVER_INIT_FAILURE_RETRY_BASE_MS + DRIVER_INIT_FAILURE_RETRY_BASE_MS, + DRIVER_INIT_FAILURE_DEADLINE_MS } from '../constants.js' import { getDataFromWorkers } from '../data-store.js' import { getProductMap } from '../testHub/utils.js' @@ -24,6 +25,7 @@ import TestOpsConfig from '../testOps/testOpsConfig.js' import APIUtils from '../cli/apiUtils.js' import PerformanceTester from './performance/performance-tester.js' import { EVENTS } from './performance/constants.js' +import { formatCreatedDay } from './createdDay.js' async function fireFunnelTestEvent(eventType: string, config: BrowserStackConfig, isCLIEnabled = false) { if (!config.userName || !config.accessKey) { @@ -224,10 +226,6 @@ function truncateToBytes(value: string, maxBytes: number) { return new TextDecoder('utf-8', { fatal: false }).decode(buf.subarray(0, maxBytes)) } -export function formatCreatedDay(date = new Date()) { - return `${date.toISOString().slice(0, 23)}000 UTC` -} - export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { const testhubUuid = process.env[BROWSERSTACK_TESTHUB_UUID] || null const workerId = process.env.WDIO_WORKER_ID @@ -260,9 +258,9 @@ export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) } } -async function postDriverInitFailure(body: string, encodedAuth: string) { +async function postDriverInitFailure(body: string, encodedAuth: string, timeoutMs: number) { const controller = new AbortController() - const timer = setTimeout(() => controller.abort(), DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS) + const timer = setTimeout(() => controller.abort(), timeoutMs) timer.unref?.() try { return await _fetch(`${APIUtils.EDS_URL}/send_sdk_events`, { @@ -291,18 +289,29 @@ export async function sendDriverInitFailure(details: DriverInitFailureDetails): // workers whose sessions fail together post at the same instant and EDS sheds the burst // with 429/503 before processing it; anything else may have landed, so it is not resent - for (let attempt = 1; attempt <= DRIVER_INIT_FAILURE_MAX_ATTEMPTS; attempt++) { - const { status } = await postDriverInitFailure(body, encodedAuth) + const deadline = Date.now() + DRIVER_INIT_FAILURE_DEADLINE_MS + let attempts = 0 + while (attempts < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { + const remaining = deadline - Date.now() + if (remaining <= 0) { + break + } + attempts++ + const { status } = await postDriverInitFailure(body, encodedAuth, Math.min(DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, remaining)) if (status !== 429 && status !== 503) { BStackLogger.debug(`Sent EDS event ${DRIVER_INIT_FAILURE_EVENT} | Status ${status}`) return } - if (attempt < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { - const delay = DRIVER_INIT_FAILURE_RETRY_BASE_MS * attempt * (1 + Math.random() * 2) - await new Promise((resolve) => setTimeout(resolve, delay)) + if (attempts === DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { + break + } + const delay = DRIVER_INIT_FAILURE_RETRY_BASE_MS * attempts * (1 + Math.random() * 2) + if (Date.now() + delay >= deadline) { + break } + await new Promise((resolve) => setTimeout(resolve, delay)) } - BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT} after ${DRIVER_INIT_FAILURE_MAX_ATTEMPTS} attempts`) + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT} after ${attempts} attempts`) } catch (error) { BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT}: ${format(error)}`) } diff --git a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts index e17000e4..7c01a107 100644 --- a/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts +++ b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts @@ -13,6 +13,7 @@ import { PERF_MEASUREMENT_ENV } from '../../constants.js' import APIUtils from '../../cli/apiUtils.js' import { CLIUtils } from '../../cli/cliUtils.js' import { EVENTS } from './constants.js' +import { formatCreatedDay } from '../createdDay.js' import fetchWrap from '../../fetchWrapper.js' import type { CsvWriter } from 'csv-writer/src/lib/csv-writer.js' import type { ObjectMap } from 'csv-writer/src/lib/lang/object.js' @@ -405,7 +406,7 @@ export default class PerformanceTester { }) } measures = ensureEpochTimes(measures) - const formattedDate = `${new Date().toISOString().slice(0, 23)}000 UTC` + const formattedDate = formatCreatedDay() this.end(EVENTS.SDK_KEY_METRICS_PREPARATION, true) const payload = { diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index db40cbec..bf924ab0 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -4,6 +4,7 @@ import { BStackLogger } from '../../src/bstackLogger.js' import fs from 'node:fs' import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { FUNNEL_INSTRUMENTATION_URL } from '../../src/constants.js' +import { formatCreatedDay } from '../../src/instrumentation/createdDay.js' vi.mock('fetch') const mockedFetch = vi.mocked(fetch) @@ -160,9 +161,9 @@ describe('DriverInitFailure', () => { }) it('formats created_day as UTC ISO with microseconds and a UTC suffix', () => { - expect(FunnelTestEvent.formatCreatedDay(new Date('2026-12-01T09:41:04.106Z'))).toBe('2026-12-01T09:41:04.106000 UTC') - expect(FunnelTestEvent.formatCreatedDay(new Date('2026-03-25T23:59:59.007Z'))).toBe('2026-03-25T23:59:59.007000 UTC') - expect(FunnelTestEvent.formatCreatedDay(new Date('2026-12-01T23:30:00.000-05:00'))).toBe('2026-12-02T04:30:00.000000 UTC') + expect(formatCreatedDay(new Date('2026-12-01T09:41:04.106Z'))).toBe('2026-12-01T09:41:04.106000 UTC') + expect(formatCreatedDay(new Date('2026-03-25T23:59:59.007Z'))).toBe('2026-03-25T23:59:59.007000 UTC') + expect(formatCreatedDay(new Date('2026-12-01T23:30:00.000-05:00'))).toBe('2026-12-02T04:30:00.000000 UTC') }) it('sends null testhub_uuid when the build uuid is not known', () => { @@ -223,6 +224,69 @@ describe('DriverInitFailure', () => { expect(fetch).toHaveBeenCalledTimes(4) }) + describe('within the 10s deadline', () => { + const shedAfter = (ms: number) => (_url: unknown, init?: RequestInit) => new Promise((resolve, reject) => { + const timer = setTimeout(() => resolve(new Response('', { status: 503 })), ms) + init!.signal!.addEventListener('abort', () => { + clearTimeout(timer) + reject(new DOMException('aborted', 'AbortError')) + }) + }) + + const timeSend = async () => { + const start = Date.now() + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + await vi.runAllTimersAsync() + await sending + return Date.now() - start + } + + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('skips a backoff that would overrun the deadline', async () => { + vi.spyOn(Math, 'random').mockReturnValue(1) + vi.mocked(fetch).mockImplementation(shedAfter(4000)) + + const elapsed = await timeSend() + + expect(fetch).toHaveBeenCalledTimes(2) + expect(elapsed).toBe(9500) + }) + + it('caps the last attempt at the time remaining', async () => { + vi.spyOn(Math, 'random').mockReturnValue(0) + vi.mocked(fetch).mockImplementation(shedAfter(3000)) + + const elapsed = await timeSend() + + expect(fetch).toHaveBeenCalledTimes(3) + expect(vi.mocked(fetch).mock.calls[2][1]!.signal!.aborted).toBe(true) + expect(elapsed).toBe(10000) + }) + + it('does not resend after an attempt times out', async () => { + vi.mocked(fetch).mockImplementation(shedAfter(60000)) + + const elapsed = await timeSend() + + expect(fetch).toHaveBeenCalledTimes(1) + expect(elapsed).toBe(5000) + }) + + it('never exceeds the deadline while EDS keeps shedding', async () => { + for (const latency of [0, 1000, 2500, 4999]) { + vi.mocked(fetch).mockReset().mockImplementation(shedAfter(latency)) + expect(await timeSend()).toBeLessThanOrEqual(10000) + } + }) + }) + it('does not resend a request that may have landed', async () => { vi.mocked(fetch).mockReturnValueOnce(Promise.resolve(new Response('', { status: 500 }))) await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) From 205e27693f333f4d55de9a5a0a255be670e848fb Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Wed, 2 Dec 2026 16:42:51 +0530 Subject: [PATCH 07/13] test: restore Math.random after DriverInitFailure deadline tests Co-Authored-By: Claude Opus 5.5 --- .../tests/instrumentation/funnelInstrumentation.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index bf924ab0..b70498a2 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -241,16 +241,20 @@ describe('DriverInitFailure', () => { return Date.now() - start } + let randomSpy: ReturnType | undefined + beforeEach(() => { vi.useFakeTimers() }) afterEach(() => { + randomSpy?.mockRestore() + randomSpy = undefined vi.useRealTimers() }) it('skips a backoff that would overrun the deadline', async () => { - vi.spyOn(Math, 'random').mockReturnValue(1) + randomSpy = vi.spyOn(Math, 'random').mockReturnValue(1) vi.mocked(fetch).mockImplementation(shedAfter(4000)) const elapsed = await timeSend() @@ -260,7 +264,7 @@ describe('DriverInitFailure', () => { }) it('caps the last attempt at the time remaining', async () => { - vi.spyOn(Math, 'random').mockReturnValue(0) + randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0) vi.mocked(fetch).mockImplementation(shedAfter(3000)) const elapsed = await timeSend() From 20998c4d13853e23fad0a276d77e04db27550ada Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:29:26 +0000 Subject: [PATCH 08/13] chore(changeset): auto-generate from PR template (minor) --- .changeset/pr-403.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/pr-403.md b/.changeset/pr-403.md index 6394b167..22f397f1 100644 --- a/.changeset/pr-403.md +++ b/.changeset/pr-403.md @@ -3,3 +3,4 @@ --- - Improved diagnostics when a test session fails to start. +- Fixed SDK telemetry events (`SDKFeaturePerformance`, `DriverInitFailure`) being recorded with day and month swapped on days 1–12 of the month. From fb28adc7710e6b570ff4286fb30ab44eae90a20f Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Wed, 2 Dec 2026 19:54:36 +0530 Subject: [PATCH 09/13] fix: scrub credentials from DriverInitFailure errorMessage and keep truncation within the byte cap Truncation now backs off to the last whole code point so the message stays valid UTF-8 and never exceeds 8000 bytes. URL userinfo and the access key and username values are masked before the message is logged or sent, and a failed send logs only the error message. The uploadEventsData test restores fsPromises.access. Co-Authored-By: Claude Opus 5.5 --- .../instrumentation/funnelInstrumentation.ts | 20 ++++++- .../funnelInstrumentation.test.ts | 58 +++++++++++++++++++ .../tests/performance-tester.test.ts | 4 +- 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 5e258504..f52d907a 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -223,7 +223,21 @@ function truncateToBytes(value: string, maxBytes: number) { if (buf.length <= maxBytes) { return value } - return new TextDecoder('utf-8', { fatal: false }).decode(buf.subarray(0, maxBytes)) + let end = maxBytes + while (end > 0 && (buf[end] & 0xc0) === 0x80) { + end-- + } + return buf.subarray(0, end).toString('utf8') +} + +function scrubCredentials(message: string, secrets: Array) { + let scrubbed = message.replace(/([a-z][a-z\d+.-]*:\/\/)[^\s/?#@]+@/gi, '$1***@') + for (const secret of secrets) { + if (secret) { + scrubbed = scrubbed.split(secret).join('***') + } + } + return scrubbed } export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { @@ -245,7 +259,7 @@ export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) arch: os.arch() }, event_json: { - errorMessage: truncateToBytes(`[DriverInitError] ${details.errorMessage}`, MAX_DRIVER_INIT_ERROR_BYTES), + errorMessage: truncateToBytes(`[DriverInitError] ${scrubCredentials(details.errorMessage, [details.accessKey, details.userName])}`, MAX_DRIVER_INIT_ERROR_BYTES), framework: details.framework ? WDIO_NAMING_PREFIX + details.framework : 'unknown', driverType: 'webdriverio', event: DRIVER_INIT_FAILURE_EVENT_TAG, @@ -313,6 +327,6 @@ export async function sendDriverInitFailure(details: DriverInitFailureDetails): } BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT} after ${attempts} attempts`) } catch (error) { - BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT}: ${format(error)}`) + BStackLogger.debug(`Failed to send EDS event ${DRIVER_INIT_FAILURE_EVENT}: ${error instanceof Error ? error.message : 'unknown error'}`) } } diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index b70498a2..915b1b9b 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -180,6 +180,64 @@ describe('DriverInitFailure', () => { expect(Buffer.byteLength(payload.data.event_json.errorMessage, 'utf8')).toBeLessThanOrEqual(8000) }) + it.each([ + ['3-byte', 0, '€'], + ['3-byte', 1, '€'], + ['3-byte', 2, '€'], + ['4-byte', 0, '😀'], + ['4-byte', 1, '😀'], + ['4-byte', 2, '😀'], + ['4-byte', 3, '😀'] + ])('cuts a %s character after %i leading bytes back to a whole code point within 8000 bytes', (_width, pad, char) => { + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'a'.repeat(pad) + char.repeat(5000) }) + const message = payload.data.event_json.errorMessage + + expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(8000) + expect(Buffer.byteLength(message, 'utf8')).toBeGreaterThan(8000 - Buffer.byteLength(char, 'utf8')) + expect(message).not.toContain('\uFFFD') + expect(message.endsWith(char)).toBe(true) + }) + + it('keeps credentials out of the request body and the debug log', async () => { + const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) + await FunnelTestEvent.sendDriverInitFailure({ + userName: 'jane_doe1', + accessKey: 'placeholder-secret', + framework: 'mocha', + errorMessage: 'Failed to create session at https://jane_doe1:placeholder-secret@hub.example.com/wd/hub; rejected placeholder-secret for jane_doe1, proxy http://u:p@proxy.local:8080' + }) + + const body = vi.mocked(fetch).mock.calls[0][1]!.body as string + const logged = debug.mock.calls.map(([line]) => String(line)).join('\n') + for (const text of [body, logged]) { + expect(text).not.toContain('placeholder-secret') + expect(text).not.toContain('u:p@') + } + expect(JSON.stringify(JSON.parse(body).data.event_json)).not.toContain('jane_doe1') + expect(logged).not.toContain('jane_doe1') + expect(JSON.parse(body).data.event_json.errorMessage).toBe( + '[DriverInitError] Failed to create session at https://***@hub.example.com/wd/hub; rejected *** for ***, proxy http://***@proxy.local:8080' + ) + debug.mockRestore() + }) + + it('leaves a message without credentials unchanged', () => { + const errorMessage = 'Failed to create a session on hub-cloud.browserstack.com after 3 retries (connectionRetryTimeout 1500ms): fetch failed' + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ userName: 'user', accessKey: 'key', errorMessage }) + + expect(payload.data.event_json.errorMessage).toBe(`[DriverInitError] ${errorMessage}`) + }) + + it('logs only the error message when the send throws', async () => { + const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) + const error = Object.assign(new Error('socket hang up'), { options: { headers: { Authorization: 'Basic c2VjcmV0' } } }) + vi.mocked(fetch).mockReturnValueOnce(Promise.reject(error)) + await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' }) + + expect(debug).toHaveBeenLastCalledWith('Failed to send EDS event DriverInitFailure: socket hang up') + debug.mockRestore() + }) + it('posts to the EDS send_sdk_events endpoint with basic auth', async () => { await FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', framework: 'mocha', errorMessage: 'boom' }) diff --git a/packages/browserstack-service/tests/performance-tester.test.ts b/packages/browserstack-service/tests/performance-tester.test.ts index 3aca38f8..0c2c9b51 100644 --- a/packages/browserstack-service/tests/performance-tester.test.ts +++ b/packages/browserstack-service/tests/performance-tester.test.ts @@ -215,14 +215,16 @@ describe('PerformanceTester', function () { }) }) describe('uploadEventsData', () => { + const originalAccess = fsPromises.access afterEach(() => { + fsPromises.access = originalAccess vi.useRealTimers() vi.unstubAllGlobals() }) it('sends created_day as UTC ISO with microseconds and a UTC suffix', async () => { vi.useFakeTimers({ now: new Date('2026-12-01T09:41:04.106Z'), toFake: ['Date'] }) - ;(fsPromises as any).access = vi.fn().mockRejectedValue(new Error('missing')) + fsPromises.access = vi.fn().mockRejectedValue(new Error('missing')) const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 })) vi.stubGlobal('fetch', fetchMock) From 6f7e32fa407d282116be350eb11314e981103f45 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Wed, 2 Dec 2026 21:25:08 +0530 Subject: [PATCH 10/13] fix: make the DriverInitFailure credential scrub linear and widen its coverage Cap the message before scrubbing and anchor the userinfo pass on the scheme delimiter so a long input cannot stall the failure path. Also mask Basic/Bearer values, key-style parameters, the base64 and URL-encoded credential forms, and match the username only as a whole token. Co-Authored-By: Claude Opus 5.5 --- .../instrumentation/funnelInstrumentation.ts | 32 ++++++++--- .../funnelInstrumentation.test.ts | 54 +++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index f52d907a..bd43424f 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -230,13 +230,33 @@ function truncateToBytes(value: string, maxBytes: number) { return buf.subarray(0, end).toString('utf8') } -function scrubCredentials(message: string, secrets: Array) { - let scrubbed = message.replace(/([a-z][a-z\d+.-]*:\/\/)[^\s/?#@]+@/gi, '$1***@') - for (const secret of secrets) { - if (secret) { - scrubbed = scrubbed.split(secret).join('***') +const SCRUB_INPUT_MAX_BYTES = MAX_DRIVER_INIT_ERROR_BYTES * 4 +const MIN_MASKED_USERNAME_LENGTH = 4 + +function escapeRegExp(value: string) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +function scrubCredentials(message: string, userName?: string, accessKey?: string) { + let scrubbed = message + const literals = new Set() + if (accessKey) { + literals.add(accessKey) + literals.add(encodeURIComponent(accessKey)) + if (userName) { + literals.add(Buffer.from(`${userName}:${accessKey}`).toString('base64')) } } + for (const literal of [...literals].sort((a, b) => b.length - a.length)) { + scrubbed = scrubbed.split(literal).join('***') + } + scrubbed = scrubbed + .replace(/:\/\/[^\s/?#@]+@/g, '://***@') + .replace(/\b(Basic|Bearer)\s+[A-Za-z0-9._~+/=-]{8,}/g, '$1 ***') + .replace(/\b(access_?key|key|token|password)(\s*=\s*["']?|["']\s*:\s*["']?)[^\s&"',;]+/gi, '$1$2***') + if (userName && userName.length >= MIN_MASKED_USERNAME_LENGTH) { + scrubbed = scrubbed.replace(new RegExp(`(? { expect(payload.data.event_json.errorMessage).toBe(`[DriverInitError] ${errorMessage}`) }) + const scrubbed = (errorMessage: string, userName = 'jane_doe1', accessKey = 'placeholder-secret') => + FunnelTestEvent.buildDriverInitFailurePayload({ userName, accessKey, errorMessage }).data.event_json.errorMessage + + it('scrubs a 100KB run of scheme characters in linear time', () => { + const errorMessage = 'a1+.-'.repeat(20000) + const start = performance.now() + const message = scrubbed(errorMessage) + const elapsed = performance.now() - start + + expect(elapsed).toBeLessThan(200) + expect(Buffer.byteLength(message, 'utf8')).toBeLessThanOrEqual(8000) + }) + + it('masks Basic and Bearer credentials', () => { + expect(scrubbed('header Authorization: Basic dXNlcjpwYXNzd29yZA== rejected')) + .toBe('[DriverInitError] header Authorization: Basic *** rejected') + expect(scrubbed('header Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.e30.sig rejected')) + .toBe('[DriverInitError] header Authorization: Bearer *** rejected') + }) + + it('masks the base64 of userName:accessKey wherever it appears', () => { + const encoded = Buffer.from('jane_doe1:placeholder-secret').toString('base64') + expect(scrubbed(`auth blob ${encoded} rejected`)).toBe('[DriverInitError] auth blob *** rejected') + }) + + it('masks the URL-encoded access key', () => { + const accessKey = 'p@ss/k+y=1' + expect(scrubbed(`GET /status?k=${encodeURIComponent(accessKey)} and raw ${accessKey}`, 'jane_doe1', accessKey)) + .toBe('[DriverInitError] GET /status?k=*** and raw ***') + }) + + it.each([ + ['access_key=abc123', 'access_key=***'], + ['accessKey=abc123', 'accessKey=***'], + ['key=abc123', 'key=***'], + ['token=abc123', 'token=***'], + ['password=abc123', 'password=***'], + ['"accessKey":"abc123"', '"accessKey":"***"'], + ['password = \'abc123\'', 'password = \'***\''] + ])('masks the value of %s', (input, expected) => { + expect(scrubbed(`https://api.example.com/app?x=1&${input}&y=2`)) + .toBe(`[DriverInitError] https://api.example.com/app?x=1&${expected}&y=2`) + }) + + it('does not alter hostnames for a short userName', () => { + expect(scrubbed('Could not reach hub.browserstack.com for ab', 'ab')) + .toBe('[DriverInitError] Could not reach hub.browserstack.com for ab') + }) + + it('masks a userName only as a whole token', () => { + expect(scrubbed('user jane rejected; janet, jane_x and xjane kept', 'jane')) + .toBe('[DriverInitError] user *** rejected; janet, jane_x and xjane kept') + }) + it('logs only the error message when the send throws', async () => { const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) const error = Object.assign(new Error('socket hang up'), { options: { headers: { Authorization: 'Basic c2VjcmV0' } } }) From 9e23cb03997fe37e7f98fb66b6b8f89ed85c3cc5 Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Thu, 3 Dec 2026 17:31:03 +0530 Subject: [PATCH 11/13] fix: mask the userName without building a regex from it --- .../instrumentation/funnelInstrumentation.ts | 23 ++++++++++++++++--- .../funnelInstrumentation.test.ts | 15 ++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index bd43424f..ac1cf60c 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -233,8 +233,25 @@ function truncateToBytes(value: string, maxBytes: number) { const SCRUB_INPUT_MAX_BYTES = MAX_DRIVER_INIT_ERROR_BYTES * 4 const MIN_MASKED_USERNAME_LENGTH = 4 -function escapeRegExp(value: string) { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +function isWordChar(ch: string | undefined) { + return ch !== undefined && /[A-Za-z0-9_]/.test(ch) +} + +function maskWholeToken(text: string, token: string) { + let out = '' + let from = 0 + let at = text.indexOf(token) + while (at !== -1) { + const end = at + token.length + if (!isWordChar(text[at - 1]) && !isWordChar(text[end])) { + out += text.slice(from, at) + '***' + from = end + at = text.indexOf(token, end) + } else { + at = text.indexOf(token, at + 1) + } + } + return out + text.slice(from) } function scrubCredentials(message: string, userName?: string, accessKey?: string) { @@ -255,7 +272,7 @@ function scrubCredentials(message: string, userName?: string, accessKey?: string .replace(/\b(Basic|Bearer)\s+[A-Za-z0-9._~+/=-]{8,}/g, '$1 ***') .replace(/\b(access_?key|key|token|password)(\s*=\s*["']?|["']\s*:\s*["']?)[^\s&"',;]+/gi, '$1$2***') if (userName && userName.length >= MIN_MASKED_USERNAME_LENGTH) { - scrubbed = scrubbed.replace(new RegExp(`(? { .toBe('[DriverInitError] user *** rejected; janet, jane_x and xjane kept') }) + it('masks a whole-token userName that overlaps a rejected match', () => { + expect(scrubbed('abab-ab ababa abab', 'abab')) + .toBe('[DriverInitError] ***-ab ababa ***') + }) + + it('treats regex metacharacters in a userName literally', () => { + expect(scrubbed('user a.b+c(1) rejected; axb+c(1) kept; a.b+c(1)', 'a.b+c(1)')) + .toBe('[DriverInitError] user *** rejected; axb+c(1) kept; ***') + }) + + it('masks every occurrence of a whole-token userName', () => { + expect(scrubbed('jane jane,jane;(jane)', 'jane')) + .toBe('[DriverInitError] *** ***,***;(***)') + }) + it('logs only the error message when the send throws', async () => { const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) const error = Object.assign(new Error('socket hang up'), { options: { headers: { Authorization: 'Basic c2VjcmV0' } } }) From 17b176d768902445567b23b901b77e96826f908e Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Thu, 3 Dec 2026 19:43:34 +0530 Subject: [PATCH 12/13] fix: prefer the owned build id and ignore placeholder env values for DriverInitFailure --- .../instrumentation/funnelInstrumentation.ts | 7 +++- .../funnelInstrumentation.test.ts | 35 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index ac1cf60c..870c2c19 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -277,8 +277,13 @@ function scrubCredentials(message: string, userName?: string, accessKey?: string return scrubbed } +function resolveTesthubUuid() { + const candidates = [TestOpsConfig.getInstance().buildHashedId, process.env[BROWSERSTACK_TESTHUB_UUID]] + return candidates.find((value) => value && value !== 'null' && value !== 'undefined') || null +} + export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) { - const testhubUuid = process.env[BROWSERSTACK_TESTHUB_UUID] || null + const testhubUuid = resolveTesthubUuid() const workerId = process.env.WDIO_WORKER_ID const platformIndex = workerId ? parseInt(workerId.split('-')[0], 10) || 0 : 0 return { diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index bf1e09f1..47ec2dbb 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -5,6 +5,7 @@ import fs from 'node:fs' import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { FUNNEL_INSTRUMENTATION_URL } from '../../src/constants.js' import { formatCreatedDay } from '../../src/instrumentation/createdDay.js' +import TestOpsConfig from '../../src/testOps/testOpsConfig.js' vi.mock('fetch') const mockedFetch = vi.mocked(fetch) @@ -174,6 +175,40 @@ describe('DriverInitFailure', () => { expect(payload.data.event_json.framework).toBe('unknown') }) + describe('testhub_uuid resolution', () => { + const testOpsConfig = TestOpsConfig.getInstance() + let savedBuildHashedId: string | undefined + + beforeEach(() => { + savedBuildHashedId = testOpsConfig.buildHashedId + testOpsConfig.buildHashedId = undefined + }) + + afterEach(() => { + testOpsConfig.buildHashedId = savedBuildHashedId + }) + + it('prefers the build hashed id the process owns', () => { + testOpsConfig.buildHashedId = 'owned-build-uuid' + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBe('owned-build-uuid') + expect(payload.data.event_json.sdkRunId).toBe('owned-build-uuid') + }) + + it('falls back to the inherited env var in a worker', () => { + expect(FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }).data.testhub_uuid).toBe('testhub-uuid-1') + }) + + it.each(['undefined', 'null', ''])('treats an env value of %j as unknown', (value) => { + process.env.BROWSERSTACK_TESTHUB_UUID = value + const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'boom' }) + + expect(payload.data.testhub_uuid).toBeNull() + expect(payload.data.event_json.sdkRunId).toBeNull() + }) + }) + it('caps the error message at 8000 bytes', () => { const payload = FunnelTestEvent.buildDriverInitFailurePayload({ errorMessage: 'é'.repeat(10000) }) From b510279d5c8316ed5a74b2f64387d8299ae0b5ca Mon Sep 17 00:00:00 2001 From: Kamalpreet Kaur Date: Fri, 4 Dec 2026 13:27:20 +0530 Subject: [PATCH 13/13] feat: report the real newSession error in DriverInitFailure wdio exposes the session creation error only on runner:end, after the service's after() hook, so a small always-on reporter now sends the event from onRunnerEnd and holds the reporter sync until it settles. The request webdriver appends to the error, whose capabilities carry the credentials, is cut before the existing scrub. The send deadline follows reporterSyncTimeout. When the reporter is absent or the runner error is empty, the previous synthetic message is sent instead. Co-Authored-By: Claude Opus 5.5 --- .../browserstack-service/src/constants.ts | 3 + .../src/driverInitFailureReporter.ts | 53 +++++++ .../instrumentation/funnelInstrumentation.ts | 26 ++- packages/browserstack-service/src/service.ts | 26 +-- .../tests/driverInitFailureReporter.test.ts | 118 ++++++++++++++ .../funnelInstrumentation.test.ts | 94 +++++++++++ .../tests/service.test.ts | 150 ++++++++++++++++++ 7 files changed, 458 insertions(+), 12 deletions(-) create mode 100644 packages/browserstack-service/src/driverInitFailureReporter.ts create mode 100644 packages/browserstack-service/tests/driverInitFailureReporter.test.ts diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index 7b5e9908..0d102bf1 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -172,6 +172,9 @@ export const DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS = 5000 export const DRIVER_INIT_FAILURE_MAX_ATTEMPTS = 4 export const DRIVER_INIT_FAILURE_RETRY_BASE_MS = 500 export const DRIVER_INIT_FAILURE_DEADLINE_MS = 10000 +export const DRIVER_INIT_FAILURE_MIN_DEADLINE_MS = 1000 +export const DRIVER_INIT_FAILURE_SYNC_MARGIN_MS = 500 +export const DEFAULT_REPORTER_SYNC_TIMEOUT_MS = 5000 // Smart Selection Mode Constants export const SMART_SELECTION_MODE_RELEVANT_FIRST = 'relevantFirst' diff --git a/packages/browserstack-service/src/driverInitFailureReporter.ts b/packages/browserstack-service/src/driverInitFailureReporter.ts new file mode 100644 index 00000000..0e6867cd --- /dev/null +++ b/packages/browserstack-service/src/driverInitFailureReporter.ts @@ -0,0 +1,53 @@ +import WDIOReporter from '@wdio/reporter' +import type { RunnerStats } from '@wdio/reporter' +import type { Reporters } from '@wdio/types' + +export type DriverInitFailureSender = (runnerError?: string) => Promise + +let activeReporter: DriverInitFailureReporter | undefined + +// wdio exposes the newSession error only on `runner:end`; false when no reporter will see it +export function handOffDriverInitFailure(send: DriverInitFailureSender): boolean { + if (!activeReporter) { + return false + } + activeReporter.deferSend(send) + return true +} + +export default class DriverInitFailureReporter extends WDIOReporter { + private _pendingSend?: DriverInitFailureSender + private _synchronised = true + + constructor (options: Partial) { + super({ ...options, outputDir: undefined, logFile: undefined, stdout: true, writeStream: { write: () => true } }) + activeReporter = this + } + + deferSend (send: DriverInitFailureSender) { + this._pendingSend = send + } + + get isSynchronised () { + return this._synchronised + } + + onRunnerEnd (runnerStats: RunnerStats) { + if (activeReporter === this) { + activeReporter = undefined + } + const send = this._pendingSend + this._pendingSend = undefined + if (!send) { + return + } + this._synchronised = false + const runnerError = typeof runnerStats?.error === 'string' ? runnerStats.error : undefined + Promise.resolve() + .then(() => send(runnerError)) + .catch(() => {}) + .finally(() => { + this._synchronised = true + }) + } +} diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 870c2c19..bdacaa00 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -15,7 +15,10 @@ import { DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, DRIVER_INIT_FAILURE_MAX_ATTEMPTS, DRIVER_INIT_FAILURE_RETRY_BASE_MS, - DRIVER_INIT_FAILURE_DEADLINE_MS + DRIVER_INIT_FAILURE_DEADLINE_MS, + DRIVER_INIT_FAILURE_MIN_DEADLINE_MS, + DRIVER_INIT_FAILURE_SYNC_MARGIN_MS, + DEFAULT_REPORTER_SYNC_TIMEOUT_MS } from '../constants.js' import { getDataFromWorkers } from '../data-store.js' import { getProductMap } from '../testHub/utils.js' @@ -216,6 +219,23 @@ export interface DriverInitFailureDetails { accessKey?: string framework?: string errorMessage: string + deadlineMs?: number +} + +const WEBDRIVER_REQUEST_DETAILS = ' when running "' + +// webdriver appends the failed request, whose capabilities carry the user's credentials +export function stripWebDriverRequestDetails(message: string) { + const at = message.indexOf(WEBDRIVER_REQUEST_DETAILS) + return at === -1 ? message : message.slice(0, at) +} + +// a send deferred to `runner:end` must settle before wdio stops waiting for reporters to sync +export function getDriverInitFailureDeadlineMs(reporterSyncTimeout?: unknown) { + const syncTimeout = typeof reporterSyncTimeout === 'number' && Number.isFinite(reporterSyncTimeout) + ? reporterSyncTimeout + : DEFAULT_REPORTER_SYNC_TIMEOUT_MS + return Math.min(DRIVER_INIT_FAILURE_DEADLINE_MS, Math.max(DRIVER_INIT_FAILURE_MIN_DEADLINE_MS, syncTimeout - DRIVER_INIT_FAILURE_SYNC_MARGIN_MS)) } function truncateToBytes(value: string, maxBytes: number) { @@ -301,7 +321,7 @@ export function buildDriverInitFailurePayload(details: DriverInitFailureDetails) arch: os.arch() }, event_json: { - errorMessage: truncateToBytes(`[DriverInitError] ${scrubCredentials(truncateToBytes(details.errorMessage, SCRUB_INPUT_MAX_BYTES), details.userName, details.accessKey)}`, MAX_DRIVER_INIT_ERROR_BYTES), + errorMessage: truncateToBytes(`[DriverInitError] ${scrubCredentials(truncateToBytes(stripWebDriverRequestDetails(details.errorMessage), SCRUB_INPUT_MAX_BYTES), details.userName, details.accessKey)}`, MAX_DRIVER_INIT_ERROR_BYTES), framework: details.framework ? WDIO_NAMING_PREFIX + details.framework : 'unknown', driverType: 'webdriverio', event: DRIVER_INIT_FAILURE_EVENT_TAG, @@ -345,7 +365,7 @@ export async function sendDriverInitFailure(details: DriverInitFailureDetails): // workers whose sessions fail together post at the same instant and EDS sheds the burst // with 429/503 before processing it; anything else may have landed, so it is not resent - const deadline = Date.now() + DRIVER_INIT_FAILURE_DEADLINE_MS + const deadline = Date.now() + Math.min(DRIVER_INIT_FAILURE_DEADLINE_MS, details.deadlineMs ?? DRIVER_INIT_FAILURE_DEADLINE_MS) let attempts = 0 while (attempts < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) { const remaining = deadline - Date.now() diff --git a/packages/browserstack-service/src/service.ts b/packages/browserstack-service/src/service.ts index 7e899fff..3a33b957 100644 --- a/packages/browserstack-service/src/service.ts +++ b/packages/browserstack-service/src/service.ts @@ -19,6 +19,7 @@ import type { BrowserstackConfig, BrowserstackOptions, MultiRemoteAction } from import type { Pickle, Feature, ITestCaseHookParameter, CucumberHook } from './cucumber-types.js' import InsightsHandler from './insights-handler.js' import TestReporter from './reporter.js' +import DriverInitFailureReporter, { handOffDriverInitFailure } from './driverInitFailureReporter.js' import { DEFAULT_OPTIONS, NOT_ALLOWED_KEYS_IN_CAPS, PERF_MEASUREMENT_ENV } from './constants.js' import CrashReporter from './crash-reporter.js' import AccessibilityHandler from './accessibility-handler.js' @@ -35,7 +36,7 @@ import { shouldProcessEventForTesthub } from './testHub/utils.js' import PerformanceTester from './instrumentation/performance/performance-tester.js' import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants.js' import { EVENTS } from './instrumentation/performance/constants.js' -import { sendDriverInitFailure } from './instrumentation/funnelInstrumentation.js' +import { getDriverInitFailureDeadlineMs, sendDriverInitFailure, stripWebDriverRequestDetails } from './instrumentation/funnelInstrumentation.js' import { BrowserstackCLI } from './cli/index.js' import { drainSkipReports, markTestStarted, reportSuiteSkipped } from './cli/skipReporter.js' import { CLIUtils } from './cli/cliUtils.js' @@ -123,6 +124,9 @@ export default class BrowserstackService implements Services.ServiceInstance { if (shouldProcessEventForTesthub('')) { this._config.reporters?.push(TestReporter) } + if (this._config.reporters && !this._config.reporters.includes(DriverInitFailureReporter)) { + this._config.reporters.push(DriverInitFailureReporter) + } if (process.env.BROWSERSTACK_TURBOSCALE) { this._turboScale = process.env.BROWSERSTACK_TURBOSCALE === 'true' @@ -679,8 +683,14 @@ export default class BrowserstackService implements Services.ServiceInstance { @PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'after' }) async after (result: number) { // wdio calls `after` without `before` only when the worker could not create its session - if (this._sessionInitAttempted && !this._sessionCreated) { - await this._reportDriverInitFailure() + if (this._sessionInitAttempted && !this._sessionCreated && !this._driverInitFailureReported) { + this._driverInitFailureReported = true + // the newSession error reaches only reporters, on `runner:end`, after this hook + const deadlineMs = getDriverInitFailureDeadlineMs(this._config.reporterSyncTimeout) + const handedOff = handOffDriverInitFailure((runnerError) => this._reportDriverInitFailure(runnerError, deadlineMs)) + if (!handedOff) { + await this._reportDriverInitFailure() + } } try { PerformanceTester.start(PERFORMANCE_SDK_EVENTS.HOOK_EVENTS.AFTER) @@ -1088,18 +1098,16 @@ export default class BrowserstackService implements Services.ServiceInstance { return Boolean(isBrowserstackSession(this._browser)) && BrowserstackCLI.getInstance().isRunning() } - async _reportDriverInitFailure() { - if (this._driverInitFailureReported) { - return - } - this._driverInitFailureReported = true + async _reportDriverInitFailure(runnerError?: string, deadlineMs?: number) { try { const { hostname, connectionRetryTimeout, connectionRetryCount } = this._config + const newSessionError = runnerError ? stripWebDriverRequestDetails(runnerError).trim() : '' await sendDriverInitFailure({ userName: this._config.user, accessKey: this._config.key, framework: this._config.framework, - errorMessage: `WebdriverIO session could not be created (hostname=${hostname}, connectionRetryTimeout=${connectionRetryTimeout}ms, connectionRetryCount=${connectionRetryCount})` + errorMessage: newSessionError || `WebdriverIO session could not be created (hostname=${hostname}, connectionRetryTimeout=${connectionRetryTimeout}ms, connectionRetryCount=${connectionRetryCount})`, + deadlineMs }) } catch (err) { BStackLogger.debug(`Exception reporting driver init failure: ${util.format(err)}`) diff --git a/packages/browserstack-service/tests/driverInitFailureReporter.test.ts b/packages/browserstack-service/tests/driverInitFailureReporter.test.ts new file mode 100644 index 00000000..108efd0b --- /dev/null +++ b/packages/browserstack-service/tests/driverInitFailureReporter.test.ts @@ -0,0 +1,118 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { describe, expect, it, vi, afterEach } from 'vitest' +import type { RunnerStats } from '@wdio/reporter' + +import DriverInitFailureReporter, { handOffDriverInitFailure } from '../src/driverInitFailureReporter.js' + +const runnerEnd = (reporter: DriverInitFailureReporter, error?: unknown) => + reporter.onRunnerEnd({ error } as unknown as RunnerStats) + +const deferred = () => { + let resolve!: () => void + let reject!: (err: Error) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +const settle = () => new Promise((resolve) => setImmediate(resolve)) + +describe('DriverInitFailureReporter', () => { + let reporter: DriverInitFailureReporter | undefined + + afterEach(() => { + if (reporter) { + runnerEnd(reporter) + reporter = undefined + } + }) + + it('declines a hand-off when no reporter was loaded', () => { + const send = vi.fn() + expect(handOffDriverInitFailure(send)).toBe(false) + expect(send).not.toHaveBeenCalled() + }) + + it('sends the runner error on runner:end and stays unsynchronised until the send settles', async () => { + reporter = new DriverInitFailureReporter({}) + const pending = deferred() + const send = vi.fn().mockReturnValue(pending.promise) + + expect(handOffDriverInitFailure(send)).toBe(true) + expect(send).not.toHaveBeenCalled() + expect(reporter.isSynchronised).toBe(true) + + runnerEnd(reporter, 'WebDriverError: Request timed out!') + expect(reporter.isSynchronised).toBe(false) + await settle() + expect(send).toHaveBeenCalledTimes(1) + expect(send).toHaveBeenCalledWith('WebDriverError: Request timed out!') + expect(reporter.isSynchronised).toBe(false) + + pending.resolve() + await settle() + expect(reporter.isSynchronised).toBe(true) + }) + + it.each([undefined, '', { message: 'not a string' }])('passes no runner error when runner:end carries %j', async (error) => { + reporter = new DriverInitFailureReporter({}) + const send = vi.fn().mockResolvedValue(undefined) + handOffDriverInitFailure(send) + + runnerEnd(reporter, error) + await settle() + + expect(send).toHaveBeenCalledTimes(1) + expect(send.mock.calls[0][0] || undefined).toBeUndefined() + }) + + it('does nothing on runner:end when no failure was handed over', async () => { + reporter = new DriverInitFailureReporter({}) + runnerEnd(reporter, 'unrelated') + await settle() + + expect(reporter.isSynchronised).toBe(true) + }) + + it('sends once and declines hand-offs after runner:end', async () => { + reporter = new DriverInitFailureReporter({}) + const send = vi.fn().mockResolvedValue(undefined) + handOffDriverInitFailure(send) + runnerEnd(reporter, 'boom') + runnerEnd(reporter, 'boom') + await settle() + + expect(send).toHaveBeenCalledTimes(1) + expect(handOffDriverInitFailure(send)).toBe(false) + }) + + it('synchronises even when the send rejects or throws', async () => { + reporter = new DriverInitFailureReporter({}) + handOffDriverInitFailure(() => Promise.reject(new Error('network down'))) + runnerEnd(reporter, 'boom') + await settle() + expect(reporter.isSynchronised).toBe(true) + + const second = new DriverInitFailureReporter({}) + handOffDriverInitFailure(() => { + throw new Error('sync throw') + }) + expect(() => runnerEnd(second, 'boom')).not.toThrow() + await settle() + expect(second.isSynchronised).toBe(true) + }) + + it('never writes to the user output directory or the runner stream', () => { + const outputDir = path.join(os.tmpdir(), `dif-reporter-${process.pid}-${Date.now()}`) + const writeStream = { write: vi.fn() } + reporter = new DriverInitFailureReporter({ outputDir, logFile: path.join(outputDir, 'wdio-0-0-reporter.log'), writeStream }) + + expect(fs.existsSync(outputDir)).toBe(false) + expect(writeStream.write).not.toHaveBeenCalled() + }) +}) diff --git a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts index 47ec2dbb..123fa7ba 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -466,3 +466,97 @@ describe('DriverInitFailure', () => { await expect(FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom' })).resolves.toBeUndefined() }) }) + +describe('DriverInitFailure with the newSession error', () => { + const userName = 'jane_doe1' + const accessKey = 'placeholder-secret' + const caps = JSON.stringify({ + capabilities: { alwaysMatch: { browserName: 'chrome', 'bstack:options': { userName, accessKey, buildName: 'nightly' } } } + }) + const webdriverError = 'WebDriverError: Request timed out! Consider increasing the "connectionRetryTimeout" option.' + const runnerError = `${webdriverError} when running "https://hub.browserstack.com/wd/hub/session" with method "POST" and args "${caps}"` + + beforeEach(() => { + process.env.BROWSERSTACK_TESTHUB_UUID = 'testhub-uuid-1' + vi.mocked(fetch).mockReturnValue(Promise.resolve(Response.json({}))) + }) + + afterEach(() => { + delete process.env.BROWSERSTACK_TESTHUB_UUID + vi.mocked(fetch).mockReset() + }) + + it('cuts the request webdriver appends to its error', () => { + expect(FunnelTestEvent.stripWebDriverRequestDetails(runnerError)).toBe(webdriverError) + expect(FunnelTestEvent.stripWebDriverRequestDetails(webdriverError)).toBe(webdriverError) + expect(FunnelTestEvent.stripWebDriverRequestDetails('a when running "x" b when running "y"')).toBe('a') + }) + + it('keeps the capabilities credentials out of the request body and the debug log', async () => { + const debug = vi.spyOn(BStackLogger, 'debug').mockImplementation(() => {}) + await FunnelTestEvent.sendDriverInitFailure({ userName, accessKey, framework: 'mocha', errorMessage: runnerError }) + + const body = vi.mocked(fetch).mock.calls[0][1]!.body as string + const logged = debug.mock.calls.map(([line]) => String(line)).join('\n') + for (const text of [JSON.stringify(JSON.parse(body).data.event_json), logged]) { + expect(text).not.toContain(accessKey) + expect(text).not.toContain(userName) + expect(text).not.toContain('bstack:options') + } + expect(body).not.toContain(accessKey) + expect(JSON.parse(body).data.event_json.errorMessage).toBe(`[DriverInitError] ${webdriverError}`) + debug.mockRestore() + }) + + it('still scrubs credentials left in front of the cut', () => { + const errorMessage = `proxy https://${userName}:${accessKey}@proxy.local rejected ${accessKey} when running "https://hub/session" with method "POST" and args "${caps}"` + const sent = FunnelTestEvent.buildDriverInitFailurePayload({ userName, accessKey, errorMessage }).data.event_json.errorMessage + + expect(sent).toBe('[DriverInitError] proxy https://***@proxy.local rejected ***') + }) + + it.each([ + [undefined, 4500], + [5000, 4500], + [3000, 2500], + [1200, 1000], + [0, 1000], + [60000, 10000], + [Number.NaN, 4500], + ['3000', 4500] + ])('derives the send deadline from reporterSyncTimeout %j as %i ms', (reporterSyncTimeout, expected) => { + expect(FunnelTestEvent.getDriverInitFailureDeadlineMs(reporterSyncTimeout)).toBe(expected) + }) + + it('stops resending once the given deadline is reached', async () => { + vi.useFakeTimers() + const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0) + vi.mocked(fetch).mockImplementation(() => Promise.resolve(new Response('', { status: 503 }))) + const start = Date.now() + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom', deadlineMs: 1500 }) + await vi.runAllTimersAsync() + await sending + const elapsed = Date.now() - start + randomSpy.mockRestore() + vi.useRealTimers() + + expect(fetch).toHaveBeenCalledTimes(2) + expect(elapsed).toBeLessThanOrEqual(1500) + }) + + it('never extends the deadline beyond 10s', async () => { + vi.useFakeTimers() + const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(1) + vi.mocked(fetch).mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve(new Response('', { status: 503 })), 4000))) + const start = Date.now() + const sending = FunnelTestEvent.sendDriverInitFailure({ userName: 'user', accessKey: 'key', errorMessage: 'boom', deadlineMs: 60000 }) + await vi.runAllTimersAsync() + await sending + const elapsed = Date.now() - start + randomSpy.mockRestore() + vi.useRealTimers() + + expect(fetch).toHaveBeenCalledTimes(2) + expect(elapsed).toBe(9500) + }) +}) diff --git a/packages/browserstack-service/tests/service.test.ts b/packages/browserstack-service/tests/service.test.ts index 7c11091d..d8243b80 100644 --- a/packages/browserstack-service/tests/service.test.ts +++ b/packages/browserstack-service/tests/service.test.ts @@ -5,7 +5,10 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import type { Frameworks } from '@wdio/types' import logger from '@wdio/logger' +import type { RunnerStats } from '@wdio/reporter' + import BrowserstackService from '../src/service.js' +import DriverInitFailureReporter from '../src/driverInitFailureReporter.js' import * as utils from '../src/util.js' import InsightsHandler from '../src/insights-handler.js' import { BrowserstackCLI } from '../src/cli/index.js' @@ -3427,4 +3430,151 @@ describe('DriverInitFailure when the worker cannot create its session', () => { await expect(realAfter.call(svc, 1)).resolves.not.toThrow() expect(edsCalls()).toHaveLength(1) }) + + it('registers its reporter after the user reporters and leaves them untouched', () => { + class UserReporter {} + const userReporters = ['dot', ['spec', { addConsoleLogs: true }], UserReporter] + for (const testObservability of [true, false]) { + const reporters: unknown[] = [...userReporters] + const config = { user: 'foo', key: 'bar', framework: 'mocha', reporters } + new BrowserstackService({ testObservability } as never, [] as never, config as never) + new BrowserstackService({ testObservability } as never, [] as never, config as never) + + expect(reporters.slice(0, userReporters.length)).toEqual(userReporters) + expect(reporters[2]).toBe(UserReporter) + expect(reporters.filter((reporter) => reporter === DriverInitFailureReporter)).toHaveLength(1) + expect(reporters.at(-1)).toBe(DriverInitFailureReporter) + expect(reporters.filter((reporter) => !userReporters.includes(reporter) && reporter !== DriverInitFailureReporter) + .every((reporter) => typeof reporter === 'function')).toBe(true) + } + expect(() => new BrowserstackService({} as never, [] as never, { user: 'foo', key: 'bar' } as never)).not.toThrow() + }) + + describe('with its reporter loaded', () => { + const userName = 'jane_doe1' + const accessKey = 'placeholder-secret' + const webdriverError = 'WebDriverError: Request timed out! Consider increasing the "connectionRetryTimeout" option.' + const caps = JSON.stringify({ capabilities: { alwaysMatch: { 'bstack:options': { userName, accessKey } } } }) + const runnerError = `${webdriverError} when running "https://hub.browserstack.com/wd/hub/session" with method "POST" and args "${caps}"` + let reporter: DriverInitFailureReporter + + const failedService = async (config: Record = {}) => { + const svc = new BrowserstackService( + { testObservability: false } as never, + [] as never, + { user: userName, key: accessKey, framework: 'jasmine', hostname: 'hub.browserstack.com', connectionRetryTimeout: 1500, connectionRetryCount: 0, ...config } as never + ) + await svc.beforeSession({} as never, {} as never) + return svc + } + const runnerEnd = (error?: string) => reporter.onRunnerEnd({ error } as RunnerStats) + const synchronised = () => vi.waitFor(() => expect(reporter.isSynchronised).toBe(true)) + + beforeEach(() => { + reporter = new DriverInitFailureReporter({}) + }) + + afterEach(() => { + runnerEnd() + }) + + it('returns from after() without sending, then sends the real error from runner:end', async () => { + const svc = await failedService() + await realAfter.call(svc, 1) + expect(edsCalls()).toHaveLength(0) + + runnerEnd(runnerError) + expect(reporter.isSynchronised).toBe(false) + await synchronised() + + const events = edsCalls() + expect(events).toHaveLength(1) + expect(events[0].data).toMatchObject({ testhub_uuid: 'testhub-uuid-1', event_name: 'DriverInitFailure' }) + expect(events[0].data.event_json).toMatchObject({ + errorMessage: `[DriverInitError] ${webdriverError}`, + framework: 'WebdriverIO-jasmine', + worker: '1-0' + }) + }) + + it('keeps the credentials in the webdriver error out of the event and the logs', async () => { + const logSpies = (['debug', 'info', 'warn', 'error'] as const) + .map((level) => vi.spyOn(bstackLogger.BStackLogger, level).mockImplementation(() => {})) + const svc = await failedService() + await realAfter.call(svc, 1) + runnerEnd(runnerError) + await synchronised() + + const [, init] = vi.mocked(fetch).mock.calls.find(([url]) => String(url).endsWith('/send_sdk_events'))! + const eventJson = JSON.stringify(JSON.parse((init as RequestInit).body as string).data.event_json) + const logged = [...logSpies, bstackLoggerSpy, vi.mocked(log.info)] + .flatMap((spy) => spy.mock.calls.map((args) => args.map(String).join(' '))) + .join('\n') + for (const text of [eventJson, logged]) { + expect(text).not.toContain(accessKey) + expect(text).not.toContain(userName) + } + expect((init as RequestInit).body).not.toContain(accessKey) + expect(eventJson).not.toContain('when running') + logSpies.forEach((spy) => spy.mockRestore()) + }) + + it.each([undefined, '', ' ', ` when running "https://hub/session" with method "POST" and args "${caps}"`])( + 'falls back to the synthetic message when runner:end carries %j', async (error) => { + const svc = await failedService() + await realAfter.call(svc, 1) + runnerEnd(error) + await synchronised() + + const events = edsCalls() + expect(events).toHaveLength(1) + expect(events[0].data.event_json.errorMessage) + .toBe('[DriverInitError] WebdriverIO session could not be created (hostname=hub.browserstack.com, connectionRetryTimeout=1500ms, connectionRetryCount=0)') + }) + + it('sends exactly once across repeated after() calls and runner:end', async () => { + const svc = await failedService() + await realAfter.call(svc, 1) + await realAfter.call(svc, 1) + runnerEnd(runnerError) + runnerEnd(runnerError) + await synchronised() + await realAfter.call(svc, 1) + + expect(edsCalls()).toHaveLength(1) + }) + + it.each([ + [{ reporterSyncTimeout: 2000 }, 2], + [{ reporterSyncTimeout: 3000 }, 3], + [{}, 4] + ])('bounds the deferred send by %j', async (config, expectedAttempts) => { + const randomSpy = vi.spyOn(Math, 'random').mockReturnValue(0) + const svc = await failedService(config) + await realAfter.call(svc, 1) + vi.useFakeTimers() + vi.mocked(fetch).mockImplementation(() => Promise.resolve(new Response('', { status: 503 }))) + const start = Date.now() + runnerEnd(runnerError) + for (let i = 0; i < 20 && !reporter.isSynchronised; i++) { + await vi.runAllTimersAsync() + } + const elapsed = Date.now() - start + randomSpy.mockRestore() + + expect(reporter.isSynchronised).toBe(true) + expect(edsCalls()).toHaveLength(expectedAttempts) + expect(elapsed).toBeLessThan((config.reporterSyncTimeout ?? 5000) - 500) + }) + + it('holds no reporter sync and sends nothing on a healthy run', async () => { + const svc = await failedService() + await svc.before({} as never, [], browser as WebdriverIO.Browser) + await realAfter.call(svc, 0) + runnerEnd() + + expect(reporter.isSynchronised).toBe(true) + expect(edsCalls()).toHaveLength(0) + }) + }) })