import EventEmitter from 'events'; import logger from '@percy/logger'; // Node-side ceiling on a single CDP round trip. Chrome does not always answer: // a renderer that is frozen, starved of CPU, or swapped out keeps its target // attached and simply never replies. In-page deadlines cannot rescue that case // — their timers live in the very renderer that stopped running — so with no // deadline here `send()` never settles and the whole CLI blocks forever with // no error, no log and an unfinalized build. Reproducible by freezing the // renderer (`Page.setWebLifecycleState`) or descheduling it (SIGSTOP), both of // which a small, memory-pressured CI agent can do on its own. export const DEFAULT_CDP_TIMEOUT = 120000; // The longest wait a caller could legitimately be running *inside* the page, // doubled. Keeps the deadline above those so raising one of them can never // turn into a spurious protocol timeout. function inPageCeiling() { return Math.max( parseInt(process.env.PERCY_PAGE_LOAD_TIMEOUT, 10) || 0, parseInt(process.env.PERCY_STORY_RENDER_TIMEOUT, 10) || 0 ) * 2; } // Resolved once per process, and memoized so a mid-run env change cannot make // concurrent sessions disagree. `PERCY_CDP_TIMEOUT=0` disables the deadline. export function cdpTimeout() { if (Session.TIMEOUT !== undefined) return Session.TIMEOUT; let configured = parseInt(process.env.PERCY_CDP_TIMEOUT, 10); Session.TIMEOUT = Number.isNaN(configured) ? Math.max(DEFAULT_CDP_TIMEOUT, inPageCeiling()) : Math.max(0, configured); return Session.TIMEOUT; } // Shared by both CDP deadlines - the session-scoped one below and the // browser-scoped one in browser.js. export function cdpTimeoutMessage(method, timeout) { return `Protocol error (${method}): Timed out after ${timeout}ms ` + 'waiting for a response from the browser. The browser stopped responding — a ' + 'renderer or browser process that is frozen, starved of CPU, or swapped out ' + 'never replies and never runs its own timers. Raise PERCY_CDP_TIMEOUT if this ' + 'command is legitimately slower than that, or set it to 0 to disable the deadline.'; } export class Session extends EventEmitter { static TIMEOUT = undefined; #callbacks = new Map(); log = logger('core:session'); children = new Map(); constructor(browser, { params, sessionId: parentId }) { super(); this.browser = browser; this.sessionId = params.sessionId; this.targetId = params.targetInfo.targetId; this.type = params.targetInfo.type; this.isDocument = this.type === 'page' || this.type === 'iframe'; this.parent = browser.sessions.get(parentId); this.parent?.children.set(this.sessionId, this); this.on('Inspector.targetCrashed', this._handleTargetCrashed); } async close() { // Check for the new closeBrowser option if (this.browser?.percy.config.discovery?.launchOptions?.closeBrowser === false) { this.log.debug('Skipping session close due to closeBrowser:false option'); return true; } if (!this.browser || this.closing) return; this.closing = true; await this.browser.send('Target.closeTarget', { targetId: this.targetId }).catch(this._handleClosedError); } async send(method, params) { /* istanbul ignore next: race condition paranoia */ if (this.closedReason) { throw new Error(`Protocol error (${method}): ${this.closedReason}`); } // send a raw message to the browser so we can provide a sessionId let id = await this.browser.send({ sessionId: this.sessionId, method, params }); // will resolve or reject when a matching response is received, or when the // deadline below expires because no response is ever coming return new Promise((resolve, reject) => { let callback = { error: new Error(), resolve, reject, method }; let timeout = cdpTimeout(); if (timeout > 0) { callback.timer = setTimeout(() => { this.#callbacks.delete(id); this.log.debug(`Protocol timeout (${method}) after ${timeout}ms`); reject(Object.assign(callback.error, { message: cdpTimeoutMessage(method, timeout) })); }, timeout); } this.#callbacks.set(id, callback); }); } _handleMessage(data) { if (data.id && this.#callbacks.has(data.id)) { // resolve or reject a pending promise created with #send() let callback = this.#callbacks.get(data.id); this.#callbacks.delete(data.id); clearTimeout(callback.timer); /* istanbul ignore next: races with browser._handleMessage() */ if (data.error) { callback.reject(Object.assign(callback.error, { message: `Protocol error (${callback.method}): ${data.error.message}` + ('data' in data.error ? `: ${data.error.data}` : '') })); } else { callback.resolve(data.result); } } else { // emit the message as an event this.emit(data.method, data.params); } } _handleClose() { this.closedReason ||= 'Session closed.'; // reject any pending callbacks for (let callback of this.#callbacks.values()) { clearTimeout(callback.timer); callback.reject(Object.assign(callback.error, { message: `Protocol error (${callback.method}): ${this.closedReason}` })); } this.#callbacks.clear(); this.parent?.children.delete(this.sessionId); this.browser = null; } _handleTargetCrashed = () => { this.closedReason = 'Session crashed!'; this.close(); } /* istanbul ignore next: encountered during closing races */ _handleClosedError = error => { if (!(error.message ?? error).endsWith(this.closedReason)) { this.log.debug(error, this.meta); } } } export default Session;