Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
fix(tests): recover from an iframe API frame that never answers
damencho7fc07e7c4e50
diff --git a/tests/helpers/Participant.ts b/tests/helpers/Participant.tsindex 70abb09317..42f0db8b25 100644--- a/tests/helpers/Participant.ts+++ b/tests/helpers/Participant.ts@@ -52,6 +52,18 @@ export const P6 = 'p6';*/const EXECUTE_TIMEOUT = 30_000;+/**+ * How long to give a freshly switched-into iframe context to answer a trivial script. A live context answers in+ * milliseconds even on a loaded grid; one that does not answer this never will (see switchToIFrame()), so there is+ * no point in giving it the full EXECUTE_TIMEOUT before moving on to recovery.+ */+const IFRAME_PROBE_TIMEOUT = 5_000;++/**+ * How many times joinConference() loads the iframe API wrapper page again when the iframe it created is dead.+ */+const MAX_IFRAME_RELOADS = 2;+/*** Participant.*/@@ -91,6 +103,14 @@ export class Participant {*/private _inMainFrame: boolean = true;+ /**+ * Set once switchToIFrame() has given up on this participant's iframe: every attempt landed on a browsing+ * context that does not answer. Later callers (the failure hook in wdio.conf.ts in particular) use it to skip+ * another round of the same 30s-per-attempt wait, which would otherwise push a failed test past its mocha+ * budget and replace the real error with a bare timeout.+ */+ private _iframeUnreachable = false;+/*** The default config to use when joining.*@@ -167,6 +187,21 @@ export class Participant {async execute<ReturnValue, InnerArguments extends any[]>(script: string | ((...innerArgs: InnerArguments) => ReturnValue),...args: InnerArguments): Promise<ReturnValue> {+ return this._executeWithin(EXECUTE_TIMEOUT, script, ...args);+ }++ /**+ * Runs a script with a bound on how long to wait for its result. See execute().+ *+ * @param {number} timeout - How long to wait for the result, in ms.+ * @param {string | Function} script - The script that will be executed.+ * @param {any[]} args - The rest of the arguments.+ * @returns {ReturnValue} - The result of the script.+ */+ private async _executeWithin<ReturnValue, InnerArguments extends any[]>(+ timeout: number,+ script: string | ((...innerArgs: InnerArguments) => ReturnValue),+ ...args: InnerArguments): Promise<ReturnValue> {let timer: ReturnType<typeof setTimeout> | undefined;// @ts-ignore@@ -182,8 +217,8 @@ export class Participant {new Promise<ReturnValue>((_, reject) => {timer = setTimeout(() => reject(new Error(- `Timeout of ${EXECUTE_TIMEOUT}ms executing a script for ${this._name}.`)),- EXECUTE_TIMEOUT);+ `Timeout of ${timeout}ms executing a script for ${this._name}.`)),+ timeout);})]);} catch (error) {@@ -338,7 +373,7 @@ export class Participant {}if (this._iFrameApi) {- await this.switchToIFrame();+ await this._switchToFreshIFrame(url);}if (!options.skipPrejoinButtonClick && !this._loadTest) {@@ -392,6 +427,42 @@ export class Participant {return this;}+ /**+ * Switches into the iframe of a just loaded iframe API wrapper page, loading the page again when the iframe it+ * created is dead.+ *+ * A dead iframe is one whose browsing context Chrome's BiDi mapper never gets an execution context for (see+ * switchToIFrame()): nothing sent into it ever answers, so retrying the switch cannot help and the only way to+ * a working frame is a new one. Loading the wrapper again creates it, and the race that produced the dead one+ * is rare enough that a fresh frame is almost always fine.+ *+ * @param {string} url - The wrapper page URL to load again.+ * @returns {Promise<void>}+ */+ private async _switchToFreshIFrame(url: string): Promise<void> {+ for (let reload = 0; ; reload++) {+ try {+ await this.switchToIFrame();++ return;+ } catch (e) {+ if (!this._iframeUnreachable || reload === MAX_IFRAME_RELOADS) {+ throw e;+ }++ console.log(`The iframe of ${this._name} never answered, loading the page again (${+ reload + 1}/${MAX_IFRAME_RELOADS}).`);+ }++ this._iframeUnreachable = false;++ // Through a blank page, as joinMuc() does, so the same URL is a real load and not a no-op.+ await this.driver.url('about:blank');+ await this.driver.url(url);+ await this.waitForPageToLoad();+ }+ }+/*** Clicks the prejoin Join button and verifies that the click reached the app, retrying a bounded number of* times when it did not.@@ -923,14 +994,19 @@ export class Participant {// error, and waitUntil cannot time out while its first evaluation is still pending. Waiting for the// wrapper's jitsiAPI.test, which it sets from the External API's onload, puts the switch after the app// document has loaded.- await this.driver.waitUntil(- // @ts-ignore- () => this.execute(() => Boolean(window.jitsiAPI?.test)),- {- timeout: 30_000,- timeoutMsg: `Timeout waiting for the iframe API to load for ${this._name}.`- }- );+ try {+ await this.driver.waitUntil(+ // @ts-ignore+ () => this.execute(() => Boolean(window.jitsiAPI?.test)),+ {+ timeout: 30_000,+ timeoutMsg: `Timeout waiting for the iframe API to load for ${this._name}.`+ }+ );+ } catch (e) {+ this._iframeUnreachable = true;+ throw e;+ }const MAX_ATTEMPTS = 3;@@ -942,11 +1018,15 @@ export class Participant {await this.driver.switchFrame(this.driver.$('iframe'));this._inMainFrame = false;- // A switch can still land on a context that is gone or about to be replaced a second time (e.g. an- // internal redirect inside the app), which looks identical from here: no response, no error. Confirm- // the context is actually alive before trusting it, instead of finding out via some later, unrelated- // timeout.- const alive = await this.execute(() => document.readyState === 'complete')+ // A switch can still land on a context that never answers. Traced on a rejoin in the same tab: the+ // context id was the right one (it matched browsingContext.getTree, and the classic switch into the+ // frame succeeded), but Chrome's BiDi mapper never got an execution context for that frame, so every+ // script sent into it, including wdio's own polyfill injection right after the frame was created,+ // waited until the page was torn down and then failed with "execution contexts cleared". That looks+ // identical to a context about to be replaced (e.g. an internal redirect inside the app): no response,+ // no error. Confirm the context is actually alive before trusting it, with a short bound: a live one+ // answers in milliseconds, and a dead one never does, whatever the timeout.+ const alive = await this._executeWithin(IFRAME_PROBE_TIMEOUT, () => document.readyState === 'complete').catch(() => false);if (alive) {@@ -957,12 +1037,20 @@ export class Participant {await this.driver.switchFrame(null);if (attempt === MAX_ATTEMPTS) {+ this._iframeUnreachable = true;throw new Error(`Switched into a dead iframe context for ${this._name} after ${MAX_ATTEMPTS} attempts.`);}}}+ /**+ * Whether switchToIFrame() has already given up on this participant's iframe. See _iframeUnreachable.+ */+ get isIframeUnreachable(): boolean {+ return this._iframeUnreachable;+ }+/*** Returns the iframe API for this participant.*/diff --git a/tests/helpers/participants.ts b/tests/helpers/participants.tsindex 4a6c730f25..4431d82aa0 100644--- a/tests/helpers/participants.ts+++ b/tests/helpers/participants.ts@@ -217,11 +217,24 @@ async function joinParticipant( // eslint-disable-line max-paramsconst alreadyOnBasePage = (await p.driver.getUrl()).endsWith('/base.html');if (!alreadyOnBasePage) {+ let inMuc = false;+if (participantOptions.iFrameApi) {- await p.switchToIFrame();+ // The iframe may be gone or dead by now (e.g. the participant hung up through the iframe API, which+ // navigates the app inside it away). Then it cannot be in the meeting, and the page is reloaded+ // below anyway; a failure to look inside is not worth failing the join over.+ try {+ await p.switchToIFrame();+ inMuc = await p.isInMuc();+ } catch (e: any) {+ console.log(`Could not check whether ${participantOptions.name} is in the meeting: ${+ e?.message ?? e}`);+ }+ } else {+ inMuc = await p.isInMuc();}- if (await p.isInMuc()) {+ if (inMuc) {return p;}diff --git a/tests/wdio.conf.ts b/tests/wdio.conf.tsindex 5df74ffbce..a88e94de6c 100644--- a/tests/wdio.conf.ts+++ b/tests/wdio.conf.ts@@ -680,7 +680,21 @@ export const config: WebdriverIO.MultiremoteConfig = {// make sure all browsers are at the main app in iframe (if used), so we collect debug infoawait Promise.all(multiRemoteBrowser.instances.map(async (instance: string) => {// @ts-ignore- await ctx[instance]?.switchToIFrame();+ const participant = ctx[instance];++ // This hook runs inside the mocha budget of the test that just failed. When the failure was+ // switchToIFrame() giving up on a dead iframe context (3 attempts of 30s each), trying again here+ // would spend the same again and let the mocha timeout replace the real error and the debug info+ // with a bare "Timeout of 180000ms exceeded". Collect whatever the current context offers instead.+ if (!participant || participant.isIframeUnreachable) {+ return;+ }++ try {+ await participant.switchToIFrame();+ } catch (e) {+ console.error(`Failed to switch ${instance} into the iframe to collect debug info`, e);+ }}));const allProcessing: Promise<any>[] = [];