Skip to content

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

chore: remove cleanupWhenAborted in favor of try/catch/finally (#36896)

Dmitry Gozmana73982e7a0ce
diff --git a/packages/playwright-core/src/server/dom.ts b/packages/playwright-core/src/server/dom.ts
index 6f1cc8eb5d..a393afc170 100644
--- a/packages/playwright-core/src/server/dom.ts
+++ b/packages/playwright-core/src/server/dom.ts
@@ -447,12 +447,6 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
return { hitTargetDescription: error };
}
hitTargetInterceptionHandle = handle as any;
- progress.cleanupWhenAborted(() => {
- // Do not await here, just in case the renderer is stuck (e.g. on alert)
- // and we won't be able to cleanup.
- hitTargetInterceptionHandle!.evaluate(h => h.stop()).catch(e => {});
- hitTargetInterceptionHandle!.dispose();
- });
}
const actionResult = await this._page.frameManager.waitForSignalsCreatedBy(progress, options.waitAfter === true, async () => {
@@ -484,6 +478,11 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
if ((options as any).__testHookAfterPointerAction)
await progress.race((options as any).__testHookAfterPointerAction());
return 'done';
+ }).finally(() => {
+ // Do not await here, just in case the renderer is stuck (e.g. on alert)
+ // and we won't be able to cleanup.
+ const stopPromise = hitTargetInterceptionHandle?.evaluate(h => h.stop()).catch(() => {});
+ stopPromise?.then(() => hitTargetInterceptionHandle?.dispose());
});
if (actionResult !== 'done')
return actionResult;
diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.ts
index 9d85416427..efdd355cd4 100644
--- a/packages/playwright-core/src/server/frames.ts
+++ b/packages/playwright-core/src/server/frames.ts
@@ -166,14 +166,16 @@ export class FrameManager {
return action();
const barrier = new SignalBarrier(progress);
this._signalBarriers.add(barrier);
- progress.cleanupWhenAborted(() => this._signalBarriers.delete(barrier));
- const result = await action();
- await progress.race(this._page.delegate.inputActionEpilogue());
- await barrier.waitFor();
- this._signalBarriers.delete(barrier);
- // Resolve in the next task, after all waitForNavigations.
- await new Promise<void>(makeWaitForNextTask());
- return result;
+ try {
+ const result = await action();
+ await progress.race(this._page.delegate.inputActionEpilogue());
+ await barrier.waitFor();
+ // Resolve in the next task, after all waitForNavigations.
+ await new Promise<void>(makeWaitForNextTask());
+ return result;
+ } finally {
+ this._signalBarriers.delete(barrier);
+ }
}
frameWillPotentiallyRequestNavigation() {
@@ -862,10 +864,10 @@ export class Frame extends SdkObject {
}
async setContent(progress: Progress, html: string, options: types.NavigateOptions): Promise<void> {
+ const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;
await this.raceNavigationAction(progress, async () => {
const waitUntil = options.waitUntil === undefined ? 'load' : options.waitUntil;
progress.log(`setting frame content, waiting until "${waitUntil}"`);
- const tag = `--playwright--set--content--${this._id}--${++this._setContentCounter}--`;
const context = await progress.race(this._utilityContext());
const tagPromise = new ManualPromise<void>();
this._page.frameManager._consoleMessageTags.set(tag, () => {
@@ -873,7 +875,6 @@ export class Frame extends SdkObject {
this._onClearLifecycle();
tagPromise.resolve();
});
- progress.cleanupWhenAborted(() => this._page.frameManager._consoleMessageTags.delete(tag));
const lifecyclePromise = progress.race(tagPromise).then(() => this._waitForLoadState(progress, waitUntil));
const contentPromise = progress.race(context.evaluate(({ html, tag }) => {
document.open();
@@ -883,6 +884,8 @@ export class Frame extends SdkObject {
}, { html, tag }));
await Promise.all([contentPromise, lifecyclePromise]);
return null;
+ }).finally(() => {
+ this._page.frameManager._consoleMessageTags.delete(tag);
});
}
@@ -1489,10 +1492,16 @@ export class Frame extends SdkObject {
next();
return { result, abort: () => aborted = true };
}, { expression, isFunction, polling: options.pollingInterval, arg }));
- progress.cleanupWhenAborted(() => handle.evaluate(h => h.abort()).finally(() => handle.dispose()));
- const result = await progress.race(handle.evaluateHandle(h => h.result));
- handle.dispose();
- return result;
+ try {
+ return await progress.race(handle.evaluateHandle(h => h.result));
+ } catch (error) {
+ // Note: it is important to await "abort()" to prevent any side effects
+ // after this method returns.
+ await handle.evaluate(h => h.abort()).catch(() => {});
+ throw error;
+ } finally {
+ handle.dispose();
+ }
});
}
diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.ts
index 20883814b8..7753982667 100644
--- a/packages/playwright-core/src/server/page.ts
+++ b/packages/playwright-core/src/server/page.ts
@@ -325,10 +325,14 @@ export class Page extends SdkObject {
await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());
const binding = new PageBinding(name, playwrightBinding, needsHandle);
this._pageBindings.set(name, binding);
- progress.cleanupWhenAborted(() => this._pageBindings.delete(name));
- await progress.race(this.delegate.addInitScript(binding.initScript));
- await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, 'main'));
- return binding;
+ try {
+ await progress.race(this.delegate.addInitScript(binding.initScript));
+ await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, 'main'));
+ return binding;
+ } catch (error) {
+ this._pageBindings.delete(name);
+ throw error;
+ }
}
async removeExposedBindings(bindings: PageBinding[]) {
@@ -342,12 +346,15 @@ export class Page extends SdkObject {
async setExtraHTTPHeaders(progress: Progress, headers: types.HeadersArray) {
const oldHeaders = this._extraHTTPHeaders;
- this._extraHTTPHeaders = headers;
- progress.cleanupWhenAborted(async () => {
+ try {
+ this._extraHTTPHeaders = headers;
+ await progress.race(this.delegate.updateExtraHTTPHeaders());
+ } catch (error) {
this._extraHTTPHeaders = oldHeaders;
- await this.delegate.updateExtraHTTPHeaders();
- });
- await progress.race(this.delegate.updateExtraHTTPHeaders());
+ // Note: no await, headers will be updated in the background as soon as possible.
+ this.delegate.updateExtraHTTPHeaders().catch(() => {});
+ throw error;
+ }
}
extraHTTPHeaders(): types.HeadersArray | undefined {
@@ -502,10 +509,6 @@ export class Page extends SdkObject {
async emulateMedia(progress: Progress, options: Partial<EmulatedMedia>) {
const oldEmulatedMedia = { ...this._emulatedMedia };
- progress.cleanupWhenAborted(async () => {
- this._emulatedMedia = oldEmulatedMedia;
- await this.delegate.updateEmulateMedia();
- });
if (options.media !== undefined)
this._emulatedMedia.media = options.media;
@@ -518,7 +521,14 @@ export class Page extends SdkObject {
if (options.contrast !== undefined)
this._emulatedMedia.contrast = options.contrast;
- await progress.race(this.delegate.updateEmulateMedia());
+ try {
+ await progress.race(this.delegate.updateEmulateMedia());
+ } catch (error) {
+ this._emulatedMedia = oldEmulatedMedia;
+ // Note: no await, emulated media will be updated in the background as soon as possible.
+ this.delegate.updateEmulateMedia().catch(() => {});
+ throw error;
+ }
}
emulatedMedia(): EmulatedMedia {
@@ -534,13 +544,15 @@ export class Page extends SdkObject {
async setViewportSize(progress: Progress, viewportSize: types.Size) {
const oldEmulatedSize = this._emulatedSize;
- progress.cleanupWhenAborted(async () => {
+ try {
+ this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
+ await progress.race(this.delegate.updateEmulatedViewportSize());
+ } catch (error) {
this._emulatedSize = oldEmulatedSize;
- await this.delegate.updateEmulatedViewportSize();
- });
-
- this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
- await progress.race(this.delegate.updateEmulatedViewportSize());
+ // Note: no await, emulated size will be updated in the background as soon as possible.
+ this.delegate.updateEmulatedViewportSize().catch(() => {});
+ throw error;
+ }
}
setEmulatedSizeFromWindowOpen(emulatedSize: EmulatedSize) {
@@ -566,8 +578,13 @@ export class Page extends SdkObject {
async addInitScript(progress: Progress, source: string) {
const initScript = new InitScript(source);
this.initScripts.push(initScript);
- progress.cleanupWhenAborted(() => this.removeInitScripts([initScript]));
- await progress.race(this.delegate.addInitScript(initScript));
+ try {
+ await progress.race(this.delegate.addInitScript(initScript));
+ } catch (error) {
+ // Note: no await, script will be removed in the background as soon as possible.
+ this.removeInitScripts([initScript]).catch(() => {});
+ throw error;
+ }
return initScript;
}
diff --git a/packages/playwright-core/src/server/progress.ts b/packages/playwright-core/src/server/progress.ts
index e299c38e17..7fde3f2557 100644
--- a/packages/playwright-core/src/server/progress.ts
+++ b/packages/playwright-core/src/server/progress.ts
@@ -20,18 +20,12 @@ import { ManualPromise } from '../utils/isomorphic/manualPromise';
import type { Progress } from '@protocol/progress';
import type { CallMetadata, SdkObject } from './instrumentation';
-import type { LogName } from './utils/debugLogger';
export type { Progress } from '@protocol/progress';
export class ProgressController {
private _forceAbortPromise = new ManualPromise<any>();
private _donePromise = new ManualPromise<void>();
-
- // Cleanups to be run only in the case of abort.
- private _cleanups: ((error: Error | undefined) => any)[] = [];
-
- private _logName: LogName;
private _state: 'before' | 'running' | { error: Error } | 'finished' = 'before';
private _sdkObject: SdkObject;
@@ -40,14 +34,9 @@ export class ProgressController {
constructor(metadata: CallMetadata, sdkObject: SdkObject) {
this.metadata = metadata;
this._sdkObject = sdkObject;
- this._logName = sdkObject.logName || 'api';
this._forceAbortPromise.catch(e => null); // Prevent unhandled promise rejection.
}
- setLogName(logName: LogName) {
- this._logName = logName;
- }
-
async abort(error: Error) {
if (this._state === 'running') {
(error as any)[kAbortErrorSymbol] = true;
@@ -66,12 +55,7 @@ export class ProgressController {
if (this._state === 'running')
this.metadata.log.push(message);
// Note: we might be sending logs after progress has finished, for example browser logs.
- this._sdkObject.instrumentation.onCallLog(this._sdkObject, this.metadata, this._logName, message);
- },
- cleanupWhenAborted: (cleanup: (error: Error | undefined) => any) => {
- if (this._state !== 'running')
- throw new Error('Internal error: cannot register cleanup after operation has finished.');
- this._cleanups.push(cleanup);
+ this._sdkObject.instrumentation.onCallLog(this._sdkObject, this.metadata, this._sdkObject.logName || 'api', message);
},
metadata: this.metadata,
race: <T>(promise: Promise<T> | Promise<T>[]) => {
@@ -103,7 +87,6 @@ export class ProgressController {
return result;
} catch (error) {
this._state = { error };
- await Promise.all(this._cleanups.splice(0).map(cleanup => runCleanup(error, cleanup)));
throw error;
} finally {
clearTimeout(timer);
@@ -112,13 +95,6 @@ export class ProgressController {
}
}
-async function runCleanup(error: Error | undefined, cleanup: (error: Error | undefined) => any) {
- try {
- await cleanup(error);
- } catch (e) {
- }
-}
-
const kAbortErrorSymbol = Symbol('kAbortError');
export function isAbortError(error: Error): boolean {
diff --git a/packages/protocol/src/progress.d.ts b/packages/protocol/src/progress.d.ts
index 6890b3a048..6e8001629b 100644
--- a/packages/protocol/src/progress.d.ts
+++ b/packages/protocol/src/progress.d.ts
@@ -16,24 +16,26 @@
import type { CallMetadata } from './callMetadata';
-// Most server operations are run inside a Progress instance.
+// Most server operations are run inside a Progress instance, which is conceptually
+// similar to a cancellation token.
+//
// Each method that takes a Progress must result in one of the three outcomes:
// - It finishes successfully, returning a value, before the Progress is aborted.
// - It throws some error, before the Progress is aborted.
// - It throws the Progress's aborted error, because the Progress was aborted before
// the method could finish.
+//
// As a rule of thumb, the above is achieved by:
// - Passing the Progress instance when awaiting other methods.
// - Using `progress.race()` when awaiting other methods that do not take a Progress argument.
// In this case, it is important that awaited method has no side effects, for example
// it is a read-only browser protocol call.
// - In rare cases, when the awaited method does not take a Progress argument,
-// but it does have side effects such as creating a page - a proper cleanup
-// must be taken in case Progress is aborted before the awaited method finishes.
-// That's usually done by `progress.cleanupWhenAborted()`.
+// but it does have side effects such as creating a page - a proper try/catch/finally
+// should be used to cleanup. Whether the cleanup is awaited or not depends on the method details.
+// For the trickiest cases, look at `raceUncancellableOperationWithCleanup()` helper method.
export interface Progress {
log(message: string): void;
- cleanupWhenAborted(cleanup: (error: Error | undefined) => any): void;
race<T>(promise: Promise<T> | Promise<T>[]): Promise<T>;
wait(timeout: number): Promise<void>;
metadata: CallMetadata;