Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/pr-405.md
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 8 additions & 0 deletions packages/browserstack-service/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ 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

// Env variables - Define all the env variable constants over here

// To store the JWT token returned the session launch
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function formatCreatedDay(date = new Date()) {
return `${date.toISOString().slice(0, 23)}000 UTC`
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,25 @@ import UsageStats from '../testOps/usageStats.js'
import TestOpsConfig from '../testOps/testOpsConfig.js'
import { BStackLogger } from '../bstackLogger.js'
import type BrowserStackConfig from '../config.js'
import { BSTACK_A11Y_POLLING_TIMEOUT, BSTACK_SERVICE_VERSION, WDIO_NAMING_PREFIX } from '../constants.js'
import {
BSTACK_A11Y_POLLING_TIMEOUT,
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
} from '../constants.js'
import { getDataFromWorkers, removeWorkersDataDir } from '../data-store.js'
import { getProductMap } from '../testHub/utils.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) {
Expand Down Expand Up @@ -188,3 +201,154 @@ function getReferrer(framework?: string) {
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
}
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<string>()
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(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
}
}
}
}

export async function sendDriverInitFailure(details: DriverInitFailureDetails): Promise<void> {
try {
if (!details.userName || !details.accessKey) {
return
}
const payload = buildDriverInitFailurePayload(details)
BStackLogger.debug(`${DRIVER_INIT_FAILURE_EVENT} payload ${JSON.stringify(payload.data.event_json)}`)

// 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
let attempts = 0
while (attempts < DRIVER_INIT_FAILURE_MAX_ATTEMPTS) {
const remaining = deadline - Date.now()
if (remaining <= 0) {
break
}
attempts++
const { statusCode } = await got.post(`${APIUtils.EDS_URL}/send_sdk_events`, {
headers: {
'content-type': 'application/json'
},
username: details.userName,
password: details.accessKey,
json: payload,
timeout: { request: Math.min(DRIVER_INIT_FAILURE_SEND_TIMEOUT_MS, remaining) },
retry: { limit: 0 },
throwHttpErrors: false
})
if (statusCode !== 429 && statusCode !== 503) {
BStackLogger.debug(`Sent EDS event ${DRIVER_INIT_FAILURE_EVENT} | Status ${statusCode}`)
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'}`)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,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'

// Telemetry must never throw into business logic. Node 18's perf_hooks rejects
// negative timestamps (e.g. performance.now() under faked timers, or any other
Expand Down Expand Up @@ -390,25 +391,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 = {
Expand Down
28 changes: 28 additions & 0 deletions packages/browserstack-service/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,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 { TestFrameworkState } from './cli/states/testFrameworkState.js'
import { HookState } from './cli/states/hookState.js'
Expand Down Expand Up @@ -75,6 +76,9 @@ export default class BrowserstackService implements Services.ServiceInstance {
private _percyCaptureMode: string | undefined = undefined
private _percyHandler?: PercyHandler
private _turboScale
private _sessionInitAttempted: boolean = false
private _sessionCreated: boolean = false
private _driverInitFailureReported: boolean = false

constructor (
options: BrowserstackConfig & Options.Testrunner,
Expand Down Expand Up @@ -128,6 +132,7 @@ export default class BrowserstackService implements Services.ServiceInstance {

@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'beforeSession' })
async beforeSession (config: Omit<Options.Testrunner, 'capabilities'>, 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
Expand Down Expand Up @@ -189,6 +194,7 @@ export default class BrowserstackService implements Services.ServiceInstance {

@PerformanceTester.Measure(PERFORMANCE_SDK_EVENTS.EVENTS.SDK_HOOK, { hookType: 'before' })
async before(caps: Capabilities.RemoteCapability, 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')
Expand Down Expand Up @@ -542,6 +548,10 @@ export default class BrowserstackService implements Services.ServiceInstance {
}

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()
}
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.HOOK_EVENTS.AFTER)
PerformanceTester.start(PERFORMANCE_SDK_EVENTS.DRIVER_EVENT.QUIT)

Expand Down Expand Up @@ -916,6 +926,24 @@ export default class BrowserstackService implements Services.ServiceInstance {
this._cliCucumberFramework()?.onStepEnd(step, result)
}

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) {
Expand Down
Loading
Loading