diff --git a/.changeset/pr-404.md b/.changeset/pr-404.md new file mode 100644 index 00000000..22f397f1 --- /dev/null +++ b/.changeset/pr-404.md @@ -0,0 +1,6 @@ +--- +"@wdio/browserstack-service": minor +--- + +- 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. diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index 329b8b73..69750e7d 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -164,6 +164,17 @@ 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 +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' export const SMART_SELECTION_MODE_RELEVANT_ONLY = 'relevantOnly' 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/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 740caedf..bdacaa00 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -5,15 +5,30 @@ 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, + 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' -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' 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) { @@ -198,3 +213,182 @@ 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 + 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) { + const buf = Buffer.from(value, 'utf8') + if (buf.length <= maxBytes) { + return value + } + let end = maxBytes + while (end > 0 && (buf[end] & 0xc0) === 0x80) { + end-- + } + return buf.subarray(0, end).toString('utf8') +} + +const SCRUB_INPUT_MAX_BYTES = MAX_DRIVER_INIT_ERROR_BYTES * 4 +const MIN_MASKED_USERNAME_LENGTH = 4 + +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) { + 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 = maskWholeToken(scrubbed, userName) + } + 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 = resolveTesthubUuid() + 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] ${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, + timestamp: Date.now(), + worker: workerId || String(process.pid), + platform: platformIndex, + sdkRunId: testhubUuid + } + } + } +} + +async function postDriverInitFailure(body: string, encodedAuth: string, timeoutMs: number) { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(), timeoutMs) + 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 + 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() + 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 (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 ${attempts} attempts`) + } catch (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/src/instrumentation/performance/performance-tester.ts b/packages/browserstack-service/src/instrumentation/performance/performance-tester.ts index cab42641..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,25 +406,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 = formatCreatedDay() this.end(EVENTS.SDK_KEY_METRICS_PREPARATION, true) const payload = { diff --git a/packages/browserstack-service/src/service.ts b/packages/browserstack-service/src/service.ts index f00e434a..e25bd093 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,6 +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 { 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' @@ -88,6 +90,9 @@ export default class BrowserstackService implements Services.ServiceInstance { * on it would report tests as skipped that are about to execute. */ private _mochaBail: boolean = false + private _sessionInitAttempted: boolean = false + private _sessionCreated: boolean = false + private _driverInitFailureReported: boolean = false constructor ( options: BrowserstackConfig & Options.Testrunner, @@ -114,6 +119,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' @@ -144,6 +152,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 @@ -210,6 +219,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') @@ -652,6 +662,16 @@ 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 && !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) PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.QUIT) @@ -1058,6 +1078,22 @@ export default class BrowserstackService implements Services.ServiceInstance { return Boolean(isBrowserstackSession(this._browser)) && BrowserstackCLI.getInstance().isRunning() } + 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: 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)}`) + } + } + @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/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 5e143d87..123fa7ba 100644 --- a/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts +++ b/packages/browserstack-service/tests/instrumentation/funnelInstrumentation.test.ts @@ -4,6 +4,8 @@ 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' +import TestOpsConfig from '../../src/testOps/testOpsConfig.js' vi.mock('fetch') const mockedFetch = vi.mocked(fetch) @@ -125,3 +127,436 @@ 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{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', + framework: 'WebdriverIO-mocha', + driverType: 'webdriverio', + event: 'sdk:driver:init:failure', + timestamp: expect.any(Number), + worker: '2-1', + platform: 2, + sdkRunId: 'testhub-uuid-1' + }) + }) + + it('formats created_day as UTC ISO with microseconds and a UTC suffix', () => { + 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', () => { + 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') + }) + + 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) }) + + 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}`) + }) + + 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('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' } } }) + 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' }) + + 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) + }) + + 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 + } + + let randomSpy: ReturnType | undefined + + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + randomSpy?.mockRestore() + randomSpy = undefined + vi.useRealTimers() + }) + + it('skips a backoff that would overrun the deadline', async () => { + randomSpy = 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 () => { + randomSpy = 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' }) + + 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() + }) +}) + +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/performance-tester.test.ts b/packages/browserstack-service/tests/performance-tester.test.ts index 3b41cb3b..0c2c9b51 100644 --- a/packages/browserstack-service/tests/performance-tester.test.ts +++ b/packages/browserstack-service/tests/performance-tester.test.ts @@ -214,4 +214,26 @@ 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.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') + }) + }) }) diff --git a/packages/browserstack-service/tests/service.test.ts b/packages/browserstack-service/tests/service.test.ts index 349f0e54..d0e92f18 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' @@ -3235,3 +3238,226 @@ describe('service.after() — skip drain must precede the deferred-finish flush expect(flushPendingTestFinishEvent).toHaveBeenCalledTimes(1) }) }) + +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) + }) + + 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) + }) + }) +})