Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore: enforce dispatcher API convention for server types (6) (#40048)

Pavel Feldman2611e0441d44
diff --git a/packages/playwright-core/src/server/chromium/crDragDrop.ts b/packages/playwright-core/src/server/chromium/crDragDrop.ts
index 1bc75ef8b8..f18ec75acf 100644
--- a/packages/playwright-core/src/server/chromium/crDragDrop.ts
+++ b/packages/playwright-core/src/server/chromium/crDragDrop.ts
@@ -52,7 +52,7 @@ export class DragManager {
return true;
}
- async interceptDragCausedByMove(progress: Progress, x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, moveCallback: () => Promise<void>): Promise<void> {
+ async interceptDragCausedByMove(progress: Progress, x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, moveCallback: (progress: Progress) => Promise<void>): Promise<void> {
this._lastPosition = { x, y };
if (this._dragState) {
await progress.race(this._crPage._mainFrameSession._client.send('Input.dispatchDragEvent', {
@@ -65,7 +65,7 @@ export class DragManager {
return;
}
if (button !== 'left')
- return moveCallback();
+ return moveCallback(progress);
const client = this._crPage._mainFrameSession._client;
let onDragIntercepted: (payload: Protocol.Input.dragInterceptedPayload) => void;
@@ -97,7 +97,7 @@ export class DragManager {
client.on('Input.dragIntercepted', onDragIntercepted!);
await progress.race(client.send('Input.setInterceptDrags', { enabled: true }));
try {
- await progress.race(moveCallback());
+ await moveCallback(progress);
expectingDrag = (await progress.race(Promise.all(this._crPage._page.frames().map(async frame => {
return frame.nonStallingEvaluateInExistingContext('window.__cleanupDrag?.()', 'utility').catch(() => false);
})))).some(x => x);
diff --git a/packages/playwright-core/src/server/chromium/crInput.ts b/packages/playwright-core/src/server/chromium/crInput.ts
index f26717a441..aa8df78a04 100644
--- a/packages/playwright-core/src/server/chromium/crInput.ts
+++ b/packages/playwright-core/src/server/chromium/crInput.ts
@@ -102,7 +102,7 @@ export class RawMouseImpl implements input.RawMouse {
}
async move(progress: Progress, x: number, y: number, button: types.MouseButton | 'none', buttons: Set<types.MouseButton>, modifiers: Set<types.KeyboardModifier>, forClick: boolean): Promise<void> {
- const actualMove = async () => {
+ const actualMove = async (progress: Progress) => {
await progress.race(this._client.send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
button,
@@ -116,7 +116,7 @@ export class RawMouseImpl implements input.RawMouse {
if (forClick) {
// Avoid extra protocol calls related to drag and drop, because click relies on
// move-down-up protocol commands being sent synchronously.
- await progress.race(actualMove());
+ await actualMove(progress);
return;
}
await this._dragManager.interceptDragCausedByMove(progress, x, y, button, buttons, modifiers, actualMove);
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index bfb715958a..899e5a7064 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -224,7 +224,6 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
this._context._tempDirs.push(tmpDir);
return {
rootDir: params.rootDirName ? new WritableStreamDispatcher(this, tempDirWithRootName) : undefined,
- // eslint-disable-next-line progress/await-must-use-progress --- all elements are racing.
writableStreams: await Promise.all(params.items.map(async item => {
await progress.race(fs.promises.mkdir(path.dirname(path.join(tempDirWithRootName, item.name)), { recursive: true }));
const file = fs.createWriteStream(path.join(tempDirWithRootName, item.name));
diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.ts
index 390777b204..0e46c80093 100644
--- a/packages/playwright-core/src/server/dom.ts
+++ b/packages/playwright-core/src/server/dom.ts
@@ -219,7 +219,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
async _waitAndScrollIntoViewIfNeeded(progress: Progress, waitForVisible: boolean): Promise<void> {
- const result = await this._retryAction(progress, 'scroll into view', async () => {
+ const result = await this._retryAction(progress, 'scroll into view', async progress => {
progress.log(` waiting for element to be stable`);
const waitResult = await progress.race(this.evaluateInUtility(async ([injected, node, { waitForVisible }]) => {
return await injected.checkElementStates(node, waitForVisible ? ['visible', 'stable'] : ['stable']);
@@ -307,7 +307,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
};
}
- async _retryAction(progress: Progress, actionName: string, action: (retry: number) => Promise<PerformActionResult>, options: { trial?: boolean, force?: boolean, skipActionPreChecks?: boolean, noAutoWaiting?: boolean }): Promise<'error:notconnected' | 'done'> {
+ async _retryAction(progress: Progress, actionName: string, action: (progress: Progress, retry: number) => Promise<PerformActionResult>, options: { trial?: boolean, force?: boolean, skipActionPreChecks?: boolean, noAutoWaiting?: boolean }): Promise<'error:notconnected' | 'done'> {
let retry = 0;
// We progressively wait longer between retries, up to 500ms.
const waitTime = [0, 20, 100, 100, 500];
@@ -328,7 +328,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
if (!options.skipActionPreChecks && !options.force && !noAutoWaiting)
await this._frame._page.performActionPreChecks(progress);
- const result = await progress.race(action(retry));
+ const result = await action(progress, retry);
++retry;
if (result === 'error:notvisible') {
if (options.force || noAutoWaiting)
@@ -370,11 +370,11 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
}
- async _retryPointerAction(progress: Progress, actionName: ActionName, waitForEnabled: boolean, action: (point: types.Point) => Promise<void>,
+ async _retryPointerAction(progress: Progress, actionName: ActionName, waitForEnabled: boolean, action: (progress: Progress, point: types.Point) => Promise<void>,
options: { waitAfter: boolean | 'disabled' } & types.PointerActionOptions & types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
// Note: do not perform locator handlers checkpoint to avoid moving the mouse in the middle of a drag operation.
const skipActionPreChecks = actionName === 'move and up';
- return await this._retryAction(progress, actionName, async retry => {
+ return await this._retryAction(progress, actionName, async (progress, retry) => {
// By default, we scroll with protocol method to reveal the action point.
// However, that might not work to scroll from under position:sticky elements
// that overlay the target element. To fight this, we cycle through different
@@ -394,19 +394,19 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
progress: Progress,
actionName: ActionName,
waitForEnabled: boolean,
- action: (point: types.Point) => Promise<void>,
+ action: (progress: Progress, point: types.Point) => Promise<void>,
forceScrollOptions: ScrollIntoViewOptions | undefined,
options: { waitAfter: boolean | 'disabled' } & types.PointerActionOptions & types.PointerActionWaitOptions,
): Promise<PerformActionResult> {
const { force = false, position } = options;
- const doScrollIntoView = async () => {
+ const doScrollIntoView = async (progress: Progress) => {
if (forceScrollOptions) {
- return await this.evaluateInUtility(([injected, node, options]) => {
+ return await progress.race(this.evaluateInUtility(([injected, node, options]) => {
if (node.nodeType === 1 /* Node.ELEMENT_NODE */)
(node as Node as Element).scrollIntoView(options);
return 'done' as const;
- }, forceScrollOptions);
+ }, forceScrollOptions));
}
return await this._scrollRectIntoViewIfNeeded(progress, position ? { x: position.x, y: position.y, width: 0, height: 0 } : undefined);
};
@@ -415,7 +415,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
// Best-effort scroll to make sure any iframes containing this element are scrolled
// into view and visible, so they are not throttled.
// See https://github.com/microsoft/playwright/issues/27196 for an example.
- await progress.race(doScrollIntoView().catch(() => {}));
+ await doScrollIntoView(progress).catch(() => {});
}
if ((options as any).__testHookBeforeStable)
@@ -436,7 +436,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
await progress.race((options as any).__testHookAfterStable());
progress.log(' scrolling into view if needed');
- const scrolled = await progress.race(doScrollIntoView());
+ const scrolled = await doScrollIntoView(progress);
if (scrolled !== 'done')
return scrolled;
progress.log(' done scrolling');
@@ -473,14 +473,14 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
hitTargetInterceptionHandle = handle as any;
}
- const actionResult = await this._page.frameManager.waitForSignalsCreatedBy(progress, options.waitAfter === true, async () => {
+ const actionResult = await this._page.frameManager.waitForSignalsCreatedBy(progress, options.waitAfter === true, async progress => {
if ((options as any).__testHookBeforePointerAction)
await progress.race((options as any).__testHookBeforePointerAction());
let restoreModifiers: types.KeyboardModifier[] | undefined;
if (options && options.modifiers)
restoreModifiers = await this._page.keyboard.ensureModifiers(progress, options.modifiers);
progress.log(` performing ${actionName} action`);
- await action(point);
+ await action(progress, point);
if (restoreModifiers)
await this._page.keyboard.ensureModifiers(progress, restoreModifiers);
if (hitTargetInterceptionHandle) {
@@ -530,7 +530,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
_hover(progress: Progress, options: types.PointerActionOptions & types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
- return this._retryPointerAction(progress, 'hover', false /* waitForEnabled */, point => this._page.mouse.move(progress, point.x, point.y), { ...options, waitAfter: 'disabled' });
+ return this._retryPointerAction(progress, 'hover', false /* waitForEnabled */, (progress, point) => this._page.mouse.move(progress, point.x, point.y), { ...options, waitAfter: 'disabled' });
}
async click(progress: Progress, options: { noWaitAfter?: boolean } & types.MouseClickOptions & types.PointerActionWaitOptions): Promise<void> {
@@ -540,7 +540,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
_click(progress: Progress, options: { waitAfter: boolean | 'disabled' } & types.MouseClickOptions & types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
- return this._retryPointerAction(progress, 'click', true /* waitForEnabled */, point => this._page.mouse.click(progress, point.x, point.y, options), options);
+ return this._retryPointerAction(progress, 'click', true /* waitForEnabled */, (progress, point) => this._page.mouse.click(progress, point.x, point.y, options), options);
}
async dblclick(progress: Progress, options: types.MouseMultiClickOptions & types.PointerActionWaitOptions): Promise<void> {
@@ -550,7 +550,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
_dblclick(progress: Progress, options: types.MouseMultiClickOptions & types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
- return this._retryPointerAction(progress, 'dblclick', true /* waitForEnabled */, point => this._page.mouse.click(progress, point.x, point.y, { ...options, clickCount: 2 }), { ...options, waitAfter: 'disabled' });
+ return this._retryPointerAction(progress, 'dblclick', true /* waitForEnabled */, (progress, point) => this._page.mouse.click(progress, point.x, point.y, { ...options, clickCount: 2 }), { ...options, waitAfter: 'disabled' });
}
async tap(progress: Progress, options: types.PointerActionWaitOptions): Promise<void> {
@@ -560,7 +560,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
_tap(progress: Progress, options: types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
- return this._retryPointerAction(progress, 'tap', true /* waitForEnabled */, point => this._page.touchscreen.tap(progress, point.x, point.y), { ...options, waitAfter: 'disabled' });
+ return this._retryPointerAction(progress, 'tap', true /* waitForEnabled */, (progress, point) => this._page.touchscreen.tap(progress, point.x, point.y), { ...options, waitAfter: 'disabled' });
}
async selectOption(progress: Progress, elements: ElementHandle[], values: types.SelectOption[], options: types.CommonActionOptions): Promise<string[]> {
@@ -577,7 +577,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
async _selectOption(progress: Progress, elements: ElementHandle[], values: types.SelectOption[], options: types.CommonActionOptions): Promise<string[] | 'error:notconnected'> {
let resultingOptions: string[] = [];
- const result = await this._retryAction(progress, 'select option', async () => {
+ const result = await this._retryAction(progress, 'select option', async progress => {
await this._beforeNonPointerAction(progress);
if (!options.force)
progress.log(` waiting for element to be visible and enabled`);
@@ -610,7 +610,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
async _fill(progress: Progress, value: string, options: types.CommonActionOptions): Promise<'error:notconnected' | 'done'> {
progress.log(` fill("${value}")`);
- return await this._retryAction(progress, 'fill', async () => {
+ return await this._retryAction(progress, 'fill', async progress => {
await this._beforeNonPointerAction(progress);
if (!options.force)
progress.log(' waiting for element to be visible, enabled and editable');
@@ -635,7 +635,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
async selectText(progress: Progress, options: types.CommonActionOptions): Promise<void> {
- const result = await this._retryAction(progress, 'selectText', async () => {
+ const result = await this._retryAction(progress, 'selectText', async progress => {
if (!options.force)
progress.log(' waiting for element to be visible');
return await progress.race(this.evaluateInUtility(async ([injected, node, { force }]) => {
@@ -736,7 +736,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
async _press(progress: Progress, key: string, options: { delay?: number, noWaitAfter?: boolean } & types.StrictOptions): Promise<'error:notconnected' | 'done'> {
progress.log(`elementHandle.press("${key}")`);
await this._beforeNonPointerAction(progress);
- return this._page.frameManager.waitForSignalsCreatedBy(progress, !options.noWaitAfter, async () => {
+ return this._page.frameManager.waitForSignalsCreatedBy(progress, !options.noWaitAfter, async progress => {
const result = await this._focus(progress, true /* resetSelectionIfNotFocused */);
if (result !== 'done')
return result;
@@ -756,14 +756,14 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
}
async _setChecked(progress: Progress, state: boolean, options: { position?: types.Point } & types.PointerActionWaitOptions): Promise<'error:notconnected' | 'done'> {
- const isChecked = async () => {
+ const isChecked = async (progress: Progress) => {
const result = await progress.race(this.evaluateInUtility(([injected, node]) => injected.elementState(node, 'checked'), {}));
if (result === 'error:notconnected' || result.received === 'error:notconnected')
throwElementIsNotAttached();
return { matches: result.matches, isRadio: result.isRadio };
};
await this._markAsTargetElement(progress);
- const checkedState = await progress.race(isChecked());
+ const checkedState = await isChecked(progress);
if (checkedState.matches === state)
return 'done';
if (!state && checkedState.isRadio)
@@ -773,7 +773,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
return result;
if (options.trial)
return 'done';
- const finalState = await progress.race(isChecked());
+ const finalState = await isChecked(progress);
if (finalState.matches !== state)
throw new NonRecoverableDOMError('Clicking the checkbox did not change its state');
return 'done';
@@ -837,7 +837,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
async waitForElementState(progress: Progress, state: 'visible' | 'hidden' | 'stable' | 'enabled' | 'disabled' | 'editable'): Promise<void> {
const actionName = `wait for ${state}`;
- const result = await this._retryAction(progress, actionName, async () => {
+ const result = await this._retryAction(progress, actionName, async progress => {
return await progress.race(this.evaluateInUtility(async ([injected, node, state]) => {
return (await injected.checkElementStates(node, [state])) || 'done';
}, state));
diff --git a/packages/playwright-core/src/server/fetch.ts b/packages/playwright-core/src/server/fetch.ts
index c3987a2e92..dca6b204dd 100644
--- a/packages/playwright-core/src/server/fetch.ts
+++ b/packages/playwright-core/src/server/fetch.ts
@@ -312,6 +312,7 @@ export abstract class APIRequestContext extends SdkObject {
this.emit(APIRequestContext.Events.Request, requestEvent);
let destroyRequest: (() => void) | undefined;
+ progress.setAllowConcurrentOrNestedRaces(true);
const resultPromise = new Promise<SendRequestResult>((fulfill, reject) => {
const requestConstructor: ((url: URL, options: http.RequestOptions, callback?: (res: http.IncomingMessage) => void) => http.ClientRequest)
= (url.protocol === 'https:' ? https : http).request;
@@ -557,6 +558,8 @@ export abstract class APIRequestContext extends SdkObject {
return progress.race(resultPromise).catch(error => {
destroyRequest?.();
throw error;
+ }).finally(() => {
+ progress.setAllowConcurrentOrNestedRaces(false);
});
}
diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts
index 24f8a4f478..beff0ce1b7 100644
--- a/packages/playwright-core/src/server/frames.ts
+++ b/packages/playwright-core/src/server/frames.ts
@@ -166,15 +166,15 @@ export class FrameManager {
}
}
- async waitForSignalsCreatedBy<T>(progress: Progress, waitAfter: boolean, action: () => Promise<T>): Promise<T> {
+ async waitForSignalsCreatedBy<T>(progress: Progress, waitAfter: boolean, action: (progress: Progress) => Promise<T>): Promise<T> {
if (!waitAfter)
- return action();
+ return action(progress);
const barrier = new SignalBarrier(progress);
this._signalBarriers.add(barrier);
try {
- const result = await progress.race(action());
+ const result = await action(progress);
await progress.race(this._page.delegate.inputActionEpilogue());
- await progress.race(barrier.waitFor());
+ await barrier.waitFor(progress);
// Resolve in the next task, after all waitForNavigations.
await new Promise<void>(makeWaitForNextTask());
return result;
@@ -603,7 +603,8 @@ export class Frame extends SdkObject<FrameEventMap> {
}
async raceNavigationAction(progress: Progress, action: () => Promise<network.Response | null>): Promise<network.Response | null> {
- return LongStandingScope.raceMultiple([
+ progress.setAllowConcurrentOrNestedRaces(true);
+ const result = await progress.race(LongStandingScope.raceMultiple([
this._detachedScope,
this._page.openScope,
], action().catch(e => {
@@ -615,7 +616,9 @@ export class Frame extends SdkObject<FrameEventMap> {
}
}
throw e;
- }));
+ })));
+ progress.setAllowConcurrentOrNestedRaces(false);
+ return result;
}
redirectNavigation(url: string, documentId: string, referer: string | undefined) {
@@ -689,7 +692,7 @@ export class Frame extends SdkObject<FrameEventMap> {
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
const request = event.newDocument ? event.newDocument.request : undefined;
- const response = request ? progress.race(request._finalRequest().response(progress)) : null;
+ const response = request ? await request._finalRequest().response(progress) : null;
return response;
}
@@ -713,7 +716,7 @@ export class Frame extends SdkObject<FrameEventMap> {
await helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e: types.LifecycleEvent) => e === waitUntil).promise;
const request = navigationEvent.newDocument ? navigationEvent.newDocument.request : undefined;
- return request ? progress.race(request._finalRequest().response(progress)) : null;
+ return request ? request._finalRequest().response(progress) : null;
}
async waitForLoadState(progress: Progress, state: types.LifecycleEvent): Promise<void> {
@@ -922,6 +925,7 @@ export class Frame extends SdkObject<FrameEventMap> {
this._onClearLifecycle();
tagPromise.resolve();
});
+ progress.setAllowConcurrentOrNestedRaces(true);
const lifecyclePromise = progress.race(tagPromise).then(() => this.waitForLoadState(progress, waitUntil));
const contentPromise = progress.race(context.evaluate(({ html, tag }) => {
document.open();
@@ -930,6 +934,7 @@ export class Frame extends SdkObject<FrameEventMap> {
document.close();
}, { html, tag }));
await Promise.all([contentPromise, lifecyclePromise]);
+ progress.setAllowConcurrentOrNestedRaces(false);
return null;
}).finally(() => {
this._page.frameManager._consoleMessageTags.delete(tag);
@@ -1210,7 +1215,7 @@ export class Frame extends SdkObject<FrameEventMap> {
async dragAndDrop(progress: Progress, source: string, target: string, options: types.DragActionOptions & types.PointerActionWaitOptions) {
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, source, options, async (progress, handle) => {
- return handle._retryPointerAction(progress, 'move and down', false, async point => {
+ return handle._retryPointerAction(progress, 'move and down', false, async (progress, point) => {
await this._page.mouse.move(progress, point.x, point.y);
await this._page.mouse.down(progress);
}, {
@@ -1221,7 +1226,7 @@ export class Frame extends SdkObject<FrameEventMap> {
}));
// Note: do not perform locator handlers checkpoint to avoid moving the mouse in the middle of a drag operation.
dom.assertDone(await this._retryWithProgressIfNotConnected(progress, target, { ...options, performActionPreChecks: false }, async (progress, handle) => {
- return handle._retryPointerAction(progress, 'move and up', false, async point => {
+ return handle._retryPointerAction(progress, 'move and up', false, async (progress, point) => {
await this._page.mouse.move(progress, point.x, point.y, { steps: options.steps });
await this._page.mouse.up(progress);
}, {
@@ -1623,7 +1628,7 @@ export class Frame extends SdkObject<FrameEventMap> {
return;
const context = await progress.race(this.utilityContext());
- // eslint-disable-next-line progress/await-must-use-progress --- all promises are awaited with progress race.
+ progress.setAllowConcurrentOrNestedRaces(true);
await Promise.all([
// wait for double raf
progress.race(context.evaluate(() => new Promise(x => {
@@ -1633,6 +1638,7 @@ export class Frame extends SdkObject<FrameEventMap> {
}))),
progress.wait(timeout),
]);
+ progress.setAllowConcurrentOrNestedRaces(false);
}
_onDetached() {
@@ -1779,9 +1785,9 @@ class SignalBarrier {
this.retain();
}
- waitFor(): Promise<void> {
+ waitFor(progress: Progress): Promise<void> {
this.release();
- return this._progress.race(this._promise);
+ return progress.race(this._promise);
}
addFrameNavigation(frame: Frame) {
diff --git a/packages/playwright-core/src/server/input.ts b/packages/playwright-core/src/server/input.ts
index 2dfbf672eb..f7f94b8654 100644
--- a/packages/playwright-core/src/server/input.ts
+++ b/packages/playwright-core/src/server/input.ts
@@ -276,6 +276,7 @@ export class Mouse {
await progress.wait(delay);
}
} else {
+ progress.setAllowConcurrentOrNestedRaces(true);
const promises = [];
const movePromise = this.move(progress, x, y, { forClick: true, steps });
if (steps !== undefined && steps > 1)
@@ -286,7 +287,8 @@ export class Mouse {
promises.push(this.down(progress, { ...options, clickCount: cc }));
promises.push(this.up(progress, { ...options, clickCount: cc }));
}
- await progress.race(Promise.all(promises));
+ await Promise.all(promises);
+ progress.setAllowConcurrentOrNestedRaces(false);
}
}
diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.ts
index 0c298919d3..c1acb77805 100644
--- a/packages/playwright-core/src/server/page.ts
+++ b/packages/playwright-core/src/server/page.ts
@@ -568,8 +568,10 @@ export class Page extends SdkObject<PageEventMap> {
}
});
try {
+ progress.setAllowConcurrentOrNestedRaces(true);
await progress.race(this.openScope.race(promise));
} finally {
+ progress.setAllowConcurrentOrNestedRaces(false);
--this._locatorHandlerRunningCounter;
}
progress.log(` interception handler has finished, continuing`);
@@ -691,9 +693,9 @@ export class Page extends SdkObject<PageEventMap> {
async expectScreenshot(progress: Progress, options: ExpectScreenshotOptions): Promise<{ actual?: Buffer, previous?: Buffer, diff?: Buffer, errorMessage?: string, log?: string[], timedOut?: boolean }> {
const locator = options.locator;
- const rafrafScreenshot = locator ? async (timeout: number) => {
+ const rafrafScreenshot = locator ? async (progress: Progress, timeout: number) => {
return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
- } : async (timeout: number) => {
+ } : async (progress: Progress, timeout: number) => {
await this.performActionPreChecks(progress);
await this.mainFrame().rafrafTimeout(progress, timeout);
return await this.screenshotter.screenshotPage(progress, options || {});
@@ -741,12 +743,12 @@ export class Page extends SdkObject<PageEventMap> {
if (screenshotTimeout)
progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
previous = actual;
- actual = await progress.race(rafrafScreenshot(screenshotTimeout).catch(e => {
+ actual = await rafrafScreenshot(progress, screenshotTimeout).catch(e => {
if (this.mainFrame().isNonRetriableError(e))
throw e;
progress.log(`failed to take screenshot - ` + e.message);
return undefined;
- }));
+ });
if (!actual)
continue;
// Compare against expectation for the first iteration.
@@ -1092,13 +1094,14 @@ export async function ariaSnapshotForFrame(progress: Progress, frame: frames.Fra
// Only fetch child snapshots for iframes that were actually rendered (not filtered by depth).
const renderedIframeRefs = snapshot.iframeRefs.filter(ref => ref in snapshot.iframeDepths);
+ progress.setAllowConcurrentOrNestedRaces(true);
const childSnapshotPromises = renderedIframeRefs.map(ref => {
const iframeDepth = snapshot.iframeDepths[ref];
const childDepth = options.depth ? options.depth - iframeDepth - 1 : undefined;
return ariaSnapshotFrameRef(progress, frame, ref, { ...options, depth: childDepth });
});
- // eslint-disable-next-line progress/await-must-use-progress --- all promises are callbacks w/ progress.
const childSnapshots = await Promise.all(childSnapshotPromises);
+ progress.setAllowConcurrentOrNestedRaces(false);
const full = [];
let incremental: string[] | undefined;
diff --git a/packages/playwright-core/src/server/progress.ts b/packages/playwright-core/src/server/progress.ts
index 132dfe0581..461e982a84 100644
--- a/packages/playwright-core/src/server/progress.ts
+++ b/packages/playwright-core/src/server/progress.ts
@@ -67,6 +67,9 @@ export class ProgressController {
this._state = 'running';
let timer: NodeJS.Timeout | undefined;
+ let outerProgress: string | undefined;
+ let allowConcurrent = false;
+
const progress: Progress = {
timeout: timeout ?? 0,
deadline,
@@ -80,11 +83,26 @@ export class ProgressController {
this._onCallLog?.(message);
},
metadata: this.metadata,
+ setAllowConcurrentOrNestedRaces: (allow: boolean) => {
+ allowConcurrent = allow;
+ },
race: <T>(promise: Promise<T> | Promise<T>[]) => {
+ if (process.env.PW_DETECT_NESTED_PROGRESS) {
+ const innerProgress = new Error().stack;
+ if (outerProgress && !allowConcurrent && outerProgress !== innerProgress) {
+ // eslint-disable-next-line no-console
+ console.error('Cannot call race() inside another race()');
+ // eslint-disable-next-line no-console
+ console.error('<<<<<OUTER>>>>>:', outerProgress);
+ // eslint-disable-next-line no-console
+ console.error('<<<<<INNER>>>>>:', innerProgress);
+ }
+ outerProgress = innerProgress;
+ }
const promises = Array.isArray(promise) ? promise : [promise];
if (!promises.length)
return Promise.resolve();
- return Promise.race([...promises, this._forceAbortPromise]);
+ return Promise.race([...promises, this._forceAbortPromise]).finally(() => outerProgress = undefined);
},
wait: async (timeout: number) => {
// Timeout = 0 here means nowait. Counter to what it typically is (wait forever).
@@ -165,5 +183,6 @@ export const nullProgress: Progress = {
params: {},
log: [],
internal: true,
- }
+ },
+ setAllowConcurrentOrNestedRaces() { },
};
diff --git a/packages/playwright-core/src/server/recorder/recorderUtils.ts b/packages/playwright-core/src/server/recorder/recorderUtils.ts
index dadeb21a48..a90def3332 100644
--- a/packages/playwright-core/src/server/recorder/recorderUtils.ts
+++ b/packages/playwright-core/src/server/recorder/recorderUtils.ts
@@ -118,6 +118,7 @@ export function collapseActions(actions: actions.ActionInContext[]): actions.Act
export async function generateFrameSelector(progress: Progress, frame: Frame): Promise<string[]> {
const selectorPromises: Promise<string>[] = [];
+ progress.setAllowConcurrentOrNestedRaces(true);
while (frame) {
const parent = frame.parentFrame();
if (!parent)
@@ -125,7 +126,8 @@ export async function generateFrameSelector(progress: Progress, frame: Frame): P
selectorPromises.push(generateFrameSelectorInParent(progress, parent, frame));
frame = parent;
}
- const result = await progress.race(Promise.all(selectorPromises));
+ const result = await Promise.all(selectorPromises);
+ progress.setAllowConcurrentOrNestedRaces(false);
return result.reverse();
}
diff --git a/packages/protocol/src/progress.d.ts b/packages/protocol/src/progress.d.ts
index 097b9d37e8..72280b317b 100644
--- a/packages/protocol/src/progress.d.ts
+++ b/packages/protocol/src/progress.d.ts
@@ -39,4 +39,5 @@ export interface Progress {
wait(timeout: number): Promise<void>; // timeout = 0 here means "wait 0 ms", not forever.
signal: AbortSignal;
metadata: CallMetadata;
+ setAllowConcurrentOrNestedRaces(allow: boolean): void;
}
diff --git a/utils/eslint-plugin-progress/index.js b/utils/eslint-plugin-progress/index.js
index 0930cf7a31..1a00e1a2a3 100644
--- a/utils/eslint-plugin-progress/index.js
+++ b/utils/eslint-plugin-progress/index.js
@@ -169,6 +169,15 @@ const rule = createRule({
if (passesProgressAsFirstArg(awaited, services))
return;
+ // Promise.all/race/allSettled/any are aggregation helpers, not async operations themselves.
+ if (awaited.type === 'CallExpression' &&
+ awaited.callee.type === 'MemberExpression' &&
+ awaited.callee.object.type === 'Identifier' &&
+ awaited.callee.object.name === 'Promise' &&
+ awaited.callee.property.type === 'Identifier' &&
+ ['all', 'race', 'allSettled', 'any'].includes(awaited.callee.property.name))
+ return;
+
// Check if this await is inside a progress.race() call higher up.
if (isInsideProgressRace(node))
return;