diff --git a/.changeset/pr-397.md b/.changeset/pr-397.md new file mode 100644 index 00000000..ea6609b5 --- /dev/null +++ b/.changeset/pr-397.md @@ -0,0 +1,5 @@ +--- +"@wdio/browserstack-service": minor +--- + +- The service now records non-sensitive details about how your tests are run (Node version, WebdriverIO package versions, worker and retry settings, whether a debugger is attached) in its debug log and in the usage data it already sends to BrowserStack at the start and end of a run, to help BrowserStack support reproduce issues faster. Credentials, paths, URLs and environment values are never recorded; set `disableAutoCaptureLogs: true` in the service options to turn it off. diff --git a/packages/browserstack-service/src/cli/grpcClient.ts b/packages/browserstack-service/src/cli/grpcClient.ts index 7e56a630..aff1a26f 100644 --- a/packages/browserstack-service/src/cli/grpcClient.ts +++ b/packages/browserstack-service/src/cli/grpcClient.ts @@ -47,6 +47,7 @@ import PerformanceTester from '../instrumentation/performance/performance-tester import { CLI_AUTH_TOKEN_ENV, CLI_AUTH_TOKEN_HEADER } from '../constants.js' import * as PERFORMANCE_SDK_EVENTS from '../instrumentation/performance/constants.js' import { BStackLogger } from './cliLogger.js' +import * as RunContext from './runContext.js' const GRPC_MESSAGE_LIMIT = 20 * 1024 * 1024 // 20 MB in bytes @@ -197,6 +198,7 @@ export class GrpcClient { language: CLIUtils.getSdkLanguage(), testFramework: testFrameworkDetail.name, wdioConfig: wdioConfig, + ...RunContext.startRequestFields(wdioConfig), }) // Add clientWorkerId and platformIndex to request (proto fields 500 & 501) ;(request as unknown as Record).clientWorkerId = clientWorkerId diff --git a/packages/browserstack-service/src/cli/index.ts b/packages/browserstack-service/src/cli/index.ts index 8ecfee39..696ee767 100644 --- a/packages/browserstack-service/src/cli/index.ts +++ b/packages/browserstack-service/src/cli/index.ts @@ -29,6 +29,7 @@ import type { BrowserstackConfig, BrowserstackOptions, LaunchResponse } from '.. import CrashReporter from '../crash-reporter.js' import PercyModule from './modules/percyModule.js' import APIUtils from './apiUtils.js' +import * as RunContext from './runContext.js' /** * BrowserstackCLI - Singleton class for managing CLI operations @@ -127,6 +128,7 @@ export class BrowserstackCLI { BStackLogger.warn(ACCESSIBILITY_BUILD_START_FAILED_WARNING) } this.isMainConnected = true + RunContext.configure('launcher', this.config, this.options, this.browserstackConfig) } /** @@ -497,6 +499,7 @@ export class BrowserstackCLI { this.logger.info(`Connected to bin session: ${JSON.stringify(redactedResponse)}`) this.loadModules(response) this.isChildConnected = true + RunContext.configure('child', this.config, this.options, this.browserstackConfig) PerformanceTester.end(PerformanceEvents.SDK_CONNECT_BIN_SESSION) } catch (error) { PerformanceTester.end(PerformanceEvents.SDK_CONNECT_BIN_SESSION, false, util.format(error)) diff --git a/packages/browserstack-service/src/cli/runContext.ts b/packages/browserstack-service/src/cli/runContext.ts new file mode 100644 index 00000000..5ec48421 --- /dev/null +++ b/packages/browserstack-service/src/cli/runContext.ts @@ -0,0 +1,433 @@ +import fs from 'node:fs' +import path from 'node:path' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' + +import { BStackLogger } from './cliLogger.js' +import { BROWSERSTACK_DISABLE_AUTO_CAPTURE_LOGS, BSTACK_SERVICE_VERSION, RUN_CONTEXT } from '../constants.js' + +type Fields = Record +type Role = 'launcher' | 'child' + +interface Budget { + deadline: number + exceeded: boolean +} + +interface RunContextState { + enabled: boolean | null + role: Role | null + pending: Array + processWritten: boolean + skippedSites: Set + optOut?: unknown + launcherFacts?: Fields + runner?: Fields +} + +const { + SCHEMA_VERSION, MAX_LIST, MAX_PENDING, MAX_LINE_BYTES, MAX_MANIFEST_BYTES, MAX_WALK_LEVELS, START_BUDGET_MS, + MAX_WORKERS_PER_CAPABILITY, LINE_PREFIX, SERVICE_PACKAGE, RUNNER_PACKAGES, FRAMEWORK_PACKAGES, FRAMEWORK_RETRIES, + NODE_FLAGS, TS_LOADERS, VERSION_RE, CID_RE, REASON_RE +} = RUN_CONTEXT +const STATE_KEY = Symbol.for(`browserstack.wdio.runContext.v${SCHEMA_VERSION}`) + +const localRequire = createRequire(import.meta.url) + +// Kept on `process` so a second copy of this module in the same process shares the dedupe. +const state = (): RunContextState => { + const holder = process as unknown as Record + if (!holder[STATE_KEY]) { + Object.defineProperty(process, STATE_KEY, { + value: { enabled: null, role: null, pending: [], processWritten: false, skippedSites: new Set() }, + configurable: true + }) + } + return holder[STATE_KEY] as RunContextState +} + +const isRecord = (value: unknown): value is Fields => Boolean(value) && typeof value === 'object' && !Array.isArray(value) + +const attempt = (fn: () => T): T | undefined => { + try { + return fn() + } catch { + return undefined + } +} + +const toVersion = (value: unknown): string => { + const match = typeof value === 'string' ? value.trim().match(VERSION_RE) : null + return match ? match[1] : 'unknown' +} + +const toCount = (value: unknown): number | string => { + if (value === undefined || value === null) { + return 'unset' + } + if (typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 9999) { + return value + } + return typeof value === 'string' && /^\d{1,4}$/.test(value.trim()) ? parseInt(value, 10) : 'unknown' +} + +const isTruthyOptOut = (value: unknown) => Boolean(value) && String(value).toLowerCase() !== 'false' + +// The env half of configCapture's isAutoCaptureLogsDisabled; importing it would load util.ts into the gRPC client. +const isEnvOptOut = () => String(process.env[BROWSERSTACK_DISABLE_AUTO_CAPTURE_LOGS] || '').toLowerCase() === 'true' + +const reason = (err: unknown): string => { + const tag = isRecord(err) ? err.code || err.name : undefined + return typeof tag === 'string' && REASON_RE.test(tag) ? tag : 'error' +} + +const halveLists = (value: unknown): unknown => { + if (Array.isArray(value)) { + return value.slice(0, Math.floor(value.length / 2)) + } + if (isRecord(value)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, halveLists(item)])) + } + return value +} + +const fit = (record: Fields, maxBytes: number): { record: Fields, text: string } => { + let current = record + for (let pass = 0; pass <= 5; pass++) { + const text = JSON.stringify(current) + if (Buffer.byteLength(text) <= maxBytes) { + return { record: current, text } + } + current = { ...(halveLists(current) as Fields), trimmed: true } + } + const truncated = { v: SCHEMA_VERSION, at: record.at, truncated: true } + return { record: truncated, text: JSON.stringify(truncated) } +} + +const write = (record: Fields | string) => { + try { + if (typeof record === 'string') { + BStackLogger.logToFile(record, 'debug') + return + } + const current = state() + const identity: Fields = { role: current.role, pid: process.pid } + const cid = process.env.WDIO_WORKER_ID + if (current.role === 'child' && typeof cid === 'string' && CID_RE.test(cid)) { + identity.cid = cid + } + const { text } = fit({ ...record, ...identity }, MAX_LINE_BYTES - LINE_PREFIX.length) + BStackLogger.logToFile(`${LINE_PREFIX}${text}`, 'debug') + } catch { + return + } +} + +const emit = (record: Fields | string) => { + const current = state() + if (current.enabled === true) { + write(record) + } else if (current.enabled === null && current.pending.length < MAX_PENDING) { + current.pending.push(record) + } +} + +const skipped = (site: string, err: unknown) => { + try { + const current = state() + if (current.enabled === false || current.skippedSites.has(site)) { + return + } + current.skippedSites.add(site) + emit(`${LINE_PREFIX}skipped at=${site} reason=${reason(err)}`) + } catch { + return + } +} + +const splitArgs = (value: unknown): string[] => typeof value === 'string' + ? value.split(/\s+/).map((token) => token.replace(/^['"]+|['"]+$/g, '')).filter(Boolean) + : [] + +const flagNames = (tokens: unknown[]) => { + const flags: string[] = [] + let other = 0 + for (const token of tokens) { + if (typeof token !== 'string' || !token.startsWith('-')) { + continue + } + const name = token.split('=')[0] + if (!NODE_FLAGS.has(name)) { + other += 1 + } else if (!flags.includes(name) && flags.length < MAX_LIST) { + flags.push(name) + } + } + return { flags, other: Math.min(other, 9999) } +} + +const tsRunner = (tokens: string[]): string => { + if ((process as unknown as Record)[Symbol.for('ts-node.register.instance')]) { + return 'ts-node' + } + const joined = tokens.join(' ') + const loader = TS_LOADERS.find(([, pattern]) => pattern.test(joined)) + if (loader) { + return loader[0] + } + return localRequire.extensions?.['.ts'] ? 'require_hook' : 'none' +} + +const debuggerState = () => { + try { + const inspector = localRequire('node:inspector') as { url: () => string | undefined } + return { attached: Boolean(inspector.url()), source: 'inspector' } + } catch { + return { attached: 'unknown', source: 'inspector' } + } +} + +const processFacts = (): Fields => { + const execArgv = Array.isArray(process.execArgv) ? process.execArgv : [] + const nodeOptions = splitArgs(process.env.NODE_OPTIONS) + return { + exec_argv: flagNames(execArgv), + node_options: flagNames(nodeOptions), + ts_runner: tsRunner(execArgv.concat(nodeOptions)), + debugger: debuggerState() + } +} + +// The same lookup Node does for a bare import from `start`, without honouring `exports`. +const findManifest = (start: string, pkg: string, budget: Budget): string | undefined => { + let dir = start + for (let level = 0; level < MAX_WALK_LEVELS; level++) { + if (Date.now() > budget.deadline) { + budget.exceeded = true + return undefined + } + if (path.basename(dir) !== 'node_modules') { + const manifest = path.join(dir, 'node_modules', pkg, 'package.json') + if (fs.existsSync(manifest)) { + return manifest + } + } + const parent = path.dirname(dir) + if (parent === dir) { + return undefined + } + dir = parent + } + return undefined +} + +const readVersion = (manifest: string, pkg: string): string => { + const stat = attempt(() => fs.statSync(manifest)) + if (!stat || stat.size > MAX_MANIFEST_BYTES) { + return 'unknown' + } + const parsed = attempt(() => JSON.parse(fs.readFileSync(manifest, 'utf8')) as unknown) + return isRecord(parsed) && parsed.name === pkg ? toVersion(parsed.version) : 'unknown' +} + +const packageFacts = (framework: unknown, budget: Budget): Fields | undefined => { + const entry = process.argv[1] + const anchors: Array<[string, string | undefined]> = [ + ['entry', typeof entry === 'string' && entry ? attempt(() => path.dirname(fs.realpathSync(entry))) : undefined], + ['service', attempt(() => path.dirname(fileURLToPath(import.meta.url)))], + ['cwd', attempt(() => process.cwd())] + ] + const adapter = typeof framework === 'string' ? FRAMEWORK_PACKAGES.get(framework) : undefined + const names = adapter ? [...RUNNER_PACKAGES, adapter] : RUNNER_PACKAGES + const packages: Fields = { [SERVICE_PACKAGE]: { version: toVersion(BSTACK_SERVICE_VERSION), found_at: 'self' } } + for (const pkg of names) { + let found: Fields = { found_at: 'none' } + for (const [foundAt, dir] of anchors) { + const manifest = dir ? findManifest(dir, pkg, budget) : undefined + if (budget.exceeded) { + return undefined + } + if (manifest) { + found = { version: readVersion(manifest, pkg), found_at: foundAt } + break + } + } + packages[pkg] = found + } + return packages +} + +// WDIO starts one worker per spec file per capability and numbers them `-` from 0 +// (a spec-file retry keeps its cid), so only the first workers of each capability are written. +const isSampledWorker = (): boolean => { + const match = String(process.env.WDIO_WORKER_ID || '').match(CID_RE) + return match !== null && parseInt(match[1], 10) < MAX_WORKERS_PER_CAPABILITY +} + +const collectProcess = (role: Role, testrunnerConfig: unknown): Fields => { + if (role === 'child') { + return processFacts() + } + const budget = { deadline: Date.now() + START_BUDGET_MS, exceeded: false } + const facts: Fields = { node: toVersion(process.version), ...processFacts() } + const packages = packageFacts(isRecord(testrunnerConfig) ? testrunnerConfig.framework : undefined, budget) + if (packages) { + facts.packages = packages + } + if (budget.exceeded) { + facts.budget_exceeded = true + } + return facts +} + +const isCaptureOff = (resolvedConfig: unknown, options: unknown): boolean => { + if (!isRecord(resolvedConfig) || resolvedConfig.disableAutoCaptureLogs === undefined) { + return true + } + return Boolean(resolvedConfig.disableAutoCaptureLogs) + || (isRecord(options) && isTruthyOptOut(options.disableAutoCaptureLogs)) + || isEnvOptOut() +} + +/** + * `language_version` for StartBinSessionRequest, gated on the opt-out in the service options the + * request carries (`wdioConfig`, the document the CLI resolves its config from). + */ +export const startRequestFields = (wdioConfig: unknown): { languageVersion?: string } => { + try { + if (isEnvOptOut()) { + return {} + } + const sent = typeof wdioConfig === 'string' ? JSON.parse(wdioConfig) as unknown : undefined + if (!isRecord(sent) || isTruthyOptOut(sent.disableAutoCaptureLogs)) { + return {} + } + return { languageVersion: process.version } + } catch (err) { + skipped('language_version', err) + return {} + } +} + +export const configure = (role: Role, resolvedConfig: unknown, options: unknown, testrunnerConfig: unknown): void => { + let current: RunContextState | undefined + let pending: Array = [] + try { + current = state() + if (current.enabled !== null) { + return + } + current.role = role + current.optOut = isRecord(options) ? options.disableAutoCaptureLogs : undefined + current.enabled = !isCaptureOff(resolvedConfig, options) && (role === 'launcher' || isSampledWorker()) + pending = current.pending + current.pending = [] + } catch { + if (current) { + current.enabled = false + } + return + } + if (!current.enabled) { + return + } + try { + if (!current.processWritten) { + current.processWritten = true + const facts = collectProcess(role, testrunnerConfig) + if (role === 'launcher') { + current.launcherFacts = facts + } + write({ v: SCHEMA_VERSION, at: 'process', ...facts }) + } + pending.forEach(write) + } catch (err) { + skipped('configure', err) + } +} + +export const runnerSettings = (config: unknown, capabilities: unknown): Fields | undefined => { + try { + if (!isRecord(config)) { + return undefined + } + const caps = Array.isArray(capabilities) ? capabilities.filter(isRecord) : [] + return { + max_instances: toCount(config.maxInstances), + per_capability: caps.slice(0, MAX_LIST).map((cap) => toCount(cap['wdio:maxInstances'] ?? cap.maxInstances)), + capabilities: Math.min(caps.length, 9999), + per_capability_limit: toCount(config.maxInstancesPerCapability), + spec_file_retries: toCount(config.specFileRetries) + } + } catch (err) { + skipped('workers', err) + return undefined + } +} + +const frameworkRetries = (config: Fields, framework: string): Fields => { + const keys = FRAMEWORK_RETRIES.get(framework) + if (!keys) { + return { requested: 'unknown', source: 'unknown' } + } + const [optionsKey, retriesKey, source] = keys + const options = config[optionsKey] + const value = isRecord(options) ? options[retriesKey] : undefined + return value === undefined || value === null + ? { requested: 0, source: 'default' } + : { requested: toCount(value), source } +} + +export const noteRunner = (requested: Fields | undefined, config: unknown, capabilities: unknown): void => { + try { + const set = runnerSettings(config, capabilities) + if (!requested || !set || !isRecord(config) || state().enabled === false) { + return + } + const framework = typeof config.framework === 'string' && FRAMEWORK_PACKAGES.has(config.framework) ? config.framework : 'other' + const changed = requested.max_instances !== set.max_instances + || JSON.stringify(requested.per_capability) !== JSON.stringify(set.per_capability) + const runner = { + framework, + workers: { + requested: requested.max_instances, + source: requested.max_instances === 'unset' ? 'unset' : 'wdio_config', + set: set.max_instances, + per_capability: { requested: requested.per_capability, set: set.per_capability }, + per_capability_limit: set.per_capability_limit, + capabilities: set.capabilities, + override: changed ? 'server_config' : 'none' + }, + retries: { + requested: requested.spec_file_retries, + source: requested.spec_file_retries === 'unset' ? 'unset' : 'wdio_config', + set: set.spec_file_retries, + framework: frameworkRetries(config, framework) + } + } + state().runner = runner + emit({ v: SCHEMA_VERSION, at: 'workers', ...runner }) + } catch (err) { + skipped('workers', err) + } +} + +export const endProperties = (): { runContext?: Fields } => { + try { + const current = state() + if (current.enabled !== true || current.role !== 'launcher' || isTruthyOptOut(current.optOut) || isEnvOptOut()) { + return {} + } + const facts = current.launcherFacts || {} + const record: Fields = { v: SCHEMA_VERSION } + for (const key of ['exec_argv', 'node_options', 'ts_runner', 'debugger', 'packages', 'budget_exceeded']) { + if (facts[key] !== undefined) { + record[key] = facts[key] + } + } + return { runContext: fit({ ...record, ...(current.runner || {}) }, MAX_LINE_BYTES).record } + } catch (err) { + skipped('end_properties', err) + return {} + } +} diff --git a/packages/browserstack-service/src/constants.ts b/packages/browserstack-service/src/constants.ts index 329b8b73..5beba064 100644 --- a/packages/browserstack-service/src/constants.ts +++ b/packages/browserstack-service/src/constants.ts @@ -298,3 +298,51 @@ export const MODULE_HOOK_EVENTS = { APPAUTOMATE_ON_START: 'MODULE_APPAUTOMATE_ON_START', APPAUTOMATE_ON_DRIVER_INIT: 'MODULE_APPAUTOMATE_ON_DRIVER_INIT', } as const + +export const RUN_CONTEXT = { + SCHEMA_VERSION: 1, + MAX_LIST: 20, + MAX_PENDING: 20, + MAX_LINE_BYTES: 2048, + MAX_MANIFEST_BYTES: 64 * 1024, + MAX_WALK_LEVELS: 32, + START_BUDGET_MS: 250, + MAX_WORKERS_PER_CAPABILITY: 10, + LINE_PREFIX: '[run-context] ', + SERVICE_PACKAGE: '@wdio/browserstack-service', + RUNNER_PACKAGES: ['webdriverio', '@wdio/cli', '@wdio/local-runner'], + FRAMEWORK_PACKAGES: new Map([ + ['mocha', '@wdio/mocha-framework'], + ['jasmine', '@wdio/jasmine-framework'], + ['cucumber', '@wdio/cucumber-framework'] + ]), + FRAMEWORK_RETRIES: new Map([ + ['mocha', ['mochaOpts', 'retries', 'mocha_opts']], + ['cucumber', ['cucumberOpts', 'retry', 'cucumber_opts']] + ]), + NODE_FLAGS: new Set([ + '--require', '-r', '--import', '--loader', '--experimental-loader', + '--experimental-vm-modules', '--experimental-specifier-resolution', '--experimental-default-type', '--input-type', + '--experimental-strip-types', '--no-experimental-strip-types', '--experimental-transform-types', + '--experimental-require-module', '--no-experimental-require-module', '--conditions', '-C', + '--enable-source-maps', '--preserve-symlinks', '--preserve-symlinks-main', + '--inspect', '--inspect-brk', '--inspect-wait', '--inspect-port', + '--max-old-space-size', '--max-semi-space-size', '--stack-size', '--expose-gc', + '--no-warnings', '--no-deprecation', '--trace-warnings', '--trace-deprecation', '--trace-uncaught', '--disable-warning', + '--unhandled-rejections', '--abort-on-uncaught-exception', + '--openssl-legacy-provider', '--use-openssl-ca', '--use-bundled-ca', '--use-system-ca', '--dns-result-order', + '--tls-min-v1.0', '--tls-min-v1.2', '--tls-max-v1.2', '--insecure-http-parser', + '--experimental-fetch', '--no-experimental-fetch', '--experimental-global-webcrypto', + '--env-file', '--env-file-if-exists', '--watch', '--test' + ]), + TS_LOADERS: [ + ['ts-node', /ts-node/], + ['tsx', /(^|[\\/@\s'"=])tsx([\\/\s'"]|$)/], + ['swc', /@swc(-node)?\/register/], + ['esbuild-register', /esbuild-register/], + ['babel', /@babel\/register/] + ], + VERSION_RE: /^v?(\d{1,4}\.\d{1,4}\.\d{1,6}(?:[-+][0-9A-Za-z.-]{1,24})?)$/, + CID_RE: /^\d{1,4}-(\d{1,6})$/, + REASON_RE: /^[A-Za-z0-9_]{1,40}$/ +} as const diff --git a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts index 740caedf..cc7f5e20 100644 --- a/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts +++ b/packages/browserstack-service/src/instrumentation/funnelInstrumentation.ts @@ -14,6 +14,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 * as RunContext from '../cli/runContext.js' async function fireFunnelTestEvent(eventType: string, config: BrowserStackConfig, isCLIEnabled = false) { if (!config.userName || !config.accessKey) { @@ -172,6 +173,7 @@ function buildEventData(eventType: string, config: BrowserStackConfig, isCLIEnab if (config.killSignal) { eventProperties.finishedMetadata = { reason: 'user_killed', signal: config.killSignal } } + Object.assign(eventProperties, RunContext.endProperties()) } return { diff --git a/packages/browserstack-service/src/launcher.ts b/packages/browserstack-service/src/launcher.ts index 8aaa1e72..279afa54 100644 --- a/packages/browserstack-service/src/launcher.ts +++ b/packages/browserstack-service/src/launcher.ts @@ -70,6 +70,7 @@ import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants import UploadAttachmentModule from './cli/modules/uploadAttachmentModule.js' import { BrowserstackCLI } from './cli/index.js' import { CLIUtils } from './cli/cliUtils.js' +import * as RunContext from './cli/runContext.js' import accessibilityScripts from './scripts/accessibility-scripts.js' import { _fetch as fetch } from './fetchWrapper.js' @@ -415,7 +416,9 @@ export default class BrowserstackLauncherService implements Services.ServiceInst CLIUtils.setFrameworkDetail(WDIO_NAMING_PREFIX + config.framework, 'WebdriverIO') const binconfig = CLIUtils.getBinConfig(config, capabilities as Capabilities.RequestedStandaloneCapabilities | Capabilities.RequestedStandaloneCapabilities[], this._options, this._buildTag) await BrowserstackCLI.getInstance().bootstrap(this._options, config, binconfig) + const requestedRunner = RunContext.runnerSettings(config, capabilities) this._applyServerConfigToRunner(config, capabilities as WebdriverIO.Capabilities[]) + RunContext.noteRunner(requestedRunner, config, capabilities) BStackLogger.debug(`Is CLI running ${BrowserstackCLI.getInstance().isRunning()}`) PerformanceTester.end(PERFORMANCE_SDK_EVENTS.FRAMEWORK_EVENTS.START) }