From 5783508749552cca85a08e60d733538648db8fcc Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 17:58:10 -0800 Subject: [PATCH 01/14] refactor(errors): port errors.ts --- .../playwright/impl/APIResponseImpl.java | 2 +- .../playwright/impl/BrowserContextImpl.java | 1 + .../playwright/impl/BrowserImpl.java | 1 + .../microsoft/playwright/impl/Connection.java | 32 +------ .../com/microsoft/playwright/impl/Errors.java | 86 +++++++++++++++++++ .../microsoft/playwright/impl/PageImpl.java | 1 + .../com/microsoft/playwright/impl/Utils.java | 8 -- 7 files changed, 92 insertions(+), 39 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Errors.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java index 904f6147b..48693a031 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/APIResponseImpl.java @@ -35,7 +35,7 @@ import static com.microsoft.playwright.impl.ChannelOwner.NO_TIMEOUT; import static com.microsoft.playwright.impl.Serialization.gson; -import static com.microsoft.playwright.impl.Utils.isSafeCloseError; +import static com.microsoft.playwright.impl.Errors.isSafeCloseError; import static java.util.Arrays.asList; class APIResponseImpl implements APIResponse { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java index 41e77105d..f7afe34da 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -38,6 +38,7 @@ import static com.microsoft.playwright.impl.Serialization.*; import static com.microsoft.playwright.impl.Utils.*; +import static com.microsoft.playwright.impl.Errors.isSafeCloseError; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.readAllBytes; import static java.util.Arrays.asList; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java index cc0dccf18..fef81dde7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -35,6 +35,7 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Utils.*; +import static com.microsoft.playwright.impl.Errors.isSafeCloseError; public class BrowserImpl extends ChannelOwner implements Browser { // Insertion order, so that browser.contexts() lists the contexts in creation order like the other clients. diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java index 41d1ff6f3..42b2bd1c3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -60,7 +60,7 @@ public String toString() { ", method='" + method + '\'' + ", params=" + (params == null ? null : "<...>") + ", result='" + result + '\'' + - ", error='" + Connection.errorToString(error) + '\'' + + ", error='" + Errors.errorToString(error) + '\'' + '}'; } } @@ -333,24 +333,6 @@ public byte[] read(JsonReader in) throws IOException { } } - // Format of the driver error message; tests match on it. - static String errorToString(SerializedError.SerializedErrorError error) { - return "Error {\n" + - " message='" + error.message + '\n' + - " name='" + error.name + '\n' + - " stack='" + error.stack + '\n' + - '}'; - } - - static String errorToString(SerializedError error) { - if (error.error != null) { - return errorToString(error.error); - } - return "SerializedError{" + - "value=" + error.value + - '}'; - } - private static String formatCallLog(JsonArray log) { if (log == null) { return ""; @@ -387,17 +369,7 @@ private void dispatch(Message message) { if (message.error == null) { callback.complete(message.result); } else { - String callLog = formatCallLog(message.log); - PlaywrightException exception; - if (message.error.error == null) { - exception = new PlaywrightException(errorToString(message.error) + callLog); - } else if ("TimeoutError".equals(message.error.error.name)) { - exception = new TimeoutError(errorToString(message.error.error) + callLog); - } else if ("TargetClosedError".equals(message.error.error.name)) { - exception = new TargetClosedError(errorToString(message.error.error) + callLog); - } else { - exception = new DriverException(errorToString(message.error.error) + callLog); - } + PlaywrightException exception = Errors.parseError(message.error, formatCallLog(message.log)); if (message.errorDetails != null) { exception = new ServerErrorWithDetails(exception, message.errorDetails, message.log); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java new file mode 100644 index 000000000..d21601d6f --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Port of packages/playwright-core/src/client/errors.ts +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.TimeoutError; + +// java: errors.ts declares the error classes (PlaywrightError, TimeoutError, TargetClosedError) +// and the functions next to them. Here the classes stay in their own files (TimeoutError is +// public API, TargetClosedError is public, DriverException is upstream's generic PlaywrightError) +// and this class holds the functions. +class Errors { + private Errors() { + } + + static boolean isTargetClosedError(Throwable error) { + return error instanceof TargetClosedError; + } + + // serializeError is not needed: the client never sends errors to the server. + + // java: the message is built the way the Java client always did, see errorToString, because the + // tests match on it. Upstream uses error.error.message and appends the call log in Connection.dispatch. + static PlaywrightException parseError(SerializedError error) { + return parseError(error, ""); + } + + // java: exceptions are immutable here, so the formatted call log is appended while the message + // is built; upstream rewrites the message afterwards (rewriteErrorMessage in Connection.dispatch). + static PlaywrightException parseError(SerializedError error, String callLog) { + if (error.error == null) { + // java: upstream parses error.value back into a value; here the structure is only printed. + return new PlaywrightException(errorToString(error) + callLog); + } + String message = errorToString(error.error) + callLog; + if ("TimeoutError".equals(error.error.name)) { + return new TimeoutError(message); + } + if ("TargetClosedError".equals(error.error.name)) { + return new TargetClosedError(message); + } + return new DriverException(message); + } + + // java: the "has been closed" family that close paths swallow; not in errors.ts. + static boolean isSafeCloseError(PlaywrightException exception) { + return isSafeCloseError(exception.getMessage()); + } + + static boolean isSafeCloseError(String error) { + return error.contains("Browser has been closed") || error.contains("Target page, context or browser has been closed"); + } + + // java: format of the driver error message; tests match on it. + static String errorToString(SerializedError.SerializedErrorError error) { + return "Error {\n" + + " message='" + error.message + '\n' + + " name='" + error.name + '\n' + + " stack='" + error.stack + '\n' + + '}'; + } + + static String errorToString(SerializedError error) { + if (error.error != null) { + return errorToString(error.error); + } + return "SerializedError{" + + "value=" + error.value + + '}'; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index ae532e651..f055df985 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -34,6 +34,7 @@ import static com.microsoft.playwright.impl.Serialization.gson; import static com.microsoft.playwright.impl.Serialization.parseError; import static com.microsoft.playwright.impl.Utils.*; +import static com.microsoft.playwright.impl.Errors.isSafeCloseError; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.readAllBytes; import static java.util.Arrays.asList; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java index b0e3aa035..c7578feff 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java @@ -356,14 +356,6 @@ static void writeToFile(InputStream inputStream, Path path) { } } - static boolean isSafeCloseError(PlaywrightException exception) { - return isSafeCloseError(exception.getMessage()); - } - - static boolean isSafeCloseError(String error) { - return error.contains("Browser has been closed") || error.contains("Target page, context or browser has been closed"); - } - static String createGuid() { StringBuffer result = new StringBuffer(); Random random = new Random(); From 0d85caa2f8b9478acc1dc083c93fa4c3f3f6aa95 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:13:49 -0800 Subject: [PATCH 02/14] refactor(connection): follow connection.ts and channelOwner.ts Connection and ChannelOwner now follow the member order of the upstream files: object factories, sendMessageToServer with CallOptions, close(cause) rejecting the pending calls, wrapApiCall with an ApiZone, dispose(reason), setEventToSubscriptionMapping and updateSubscription. --- .../playwright/impl/ArtifactImpl.java | 4 +- .../playwright/impl/BrowserContextImpl.java | 10 +- .../playwright/impl/BrowserImpl.java | 3 +- .../playwright/impl/BrowserTypeImpl.java | 2 +- .../playwright/impl/ChannelOwner.java | 164 +++-- .../microsoft/playwright/impl/Connection.java | 631 +++++++++--------- .../microsoft/playwright/impl/FrameImpl.java | 4 +- .../microsoft/playwright/impl/JsonPipe.java | 4 + .../playwright/impl/ListenerCollection.java | 23 +- .../microsoft/playwright/impl/PageImpl.java | 18 +- .../playwright/impl/PlaywrightImpl.java | 2 +- .../playwright/impl/StackTraceCollector.java | 6 +- .../playwright/impl/TracingImpl.java | 12 +- .../com/microsoft/playwright/impl/Utils.java | 2 +- .../microsoft/playwright/impl/VideoImpl.java | 2 +- .../playwright/impl/WaitForEventLogger.java | 12 +- .../tests/library/TestBrowsertypeConnect.java | 1 - 17 files changed, 487 insertions(+), 413 deletions(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java index 03ea75ca3..ce83e2c6a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ArtifactImpl.java @@ -66,14 +66,14 @@ public String failure() { } public Path pathAfterFinished() { - if (connection.isRemote) { + if (connection.isRemote()) { throw new PlaywrightException("Path is not available when using browserType.connect(). Use download.saveAs() to save a local copy."); } return FileSystems.getDefault().getPath(channel.pathAfterFinished(NO_TIMEOUT).value); } public void saveAs(Path path) { - if (connection.isRemote) { + if (connection.isRemote()) { Stream stream = channel.saveAsStream(NO_TIMEOUT).stream; writeToFile(stream.stream(), path); return; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java index f7afe34da..f35c22854 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -526,7 +526,7 @@ public APIRequestContextImpl request() { @Override public AutoCloseable route(String url, Consumer handler, RouteOptions options) { - route(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils, false), handler, options); + route(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils(), false), handler, options); return new DisposableStub(() -> unroute(url, handler)); } @@ -551,8 +551,8 @@ public void routeFromHAR(Path har, RouteFromHAROptions options) { recordIntoHar(null, har, options, null); return; } - UrlMatcher matcher = UrlMatcher.forOneOf(baseUrl(), options.url, this.connection.localUtils, false); - HARRouter harRouter = new HARRouter(connection.localUtils, har, options.notFound); + UrlMatcher matcher = UrlMatcher.forOneOf(baseUrl(), options.url, this.connection.localUtils(), false); + HARRouter harRouter = new HARRouter(connection.localUtils(), har, options.notFound); onClose(context -> harRouter.dispose()); route(matcher, route -> harRouter.handle(route), null); } @@ -564,7 +564,7 @@ private void route(UrlMatcher matcher, Consumer handler, RouteOptions opt @Override public void routeWebSocket(String url, Consumer handler) { - routeWebSocketImpl(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils, true), handler); + routeWebSocketImpl(UrlMatcher.forGlob(baseUrl(), url, this.connection.localUtils(), true), handler); } @Override @@ -681,7 +681,7 @@ public void unrouteAll() { @Override public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(this.baseUrl(), url, this.connection.localUtils, false), handler); + unroute(UrlMatcher.forGlob(this.baseUrl(), url, this.connection.localUtils(), false), handler); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java index fef81dde7..5ac321362 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -92,7 +92,8 @@ public void close(CloseOptions options) { closeReason = options.reason; if (isConnectedOverWebSocket) { try { - connection.close(); + // java: the message of a call that fails because of this, the default close reason of JsonPipe. + connection.close("Browser has been closed"); } catch (IOException e) { throw new PlaywrightException("Failed to close browser connection", e); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java index 5ea7b91ab..3b6c529d2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -86,7 +86,7 @@ public Browser connect(String wsEndpoint, ConnectOptions options) { } JsonPipe pipe = connection.localUtils().channel.connect(params, timeout).pipe; - Connection connection = new Connection(pipe, this.connection.env, this.connection.localUtils); + Connection connection = new Connection(pipe, this.connection.env, this.connection.localUtils()); PlaywrightImpl playwright = connection.initializePlaywright(); if (!playwright.initializer.has("preLaunchedBrowser")) { try { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index 0cdff1555..62d5e70f1 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of packages/playwright-core/src/client/channelOwner.ts package com.microsoft.playwright.impl; import com.google.gson.JsonElement; @@ -34,50 +35,134 @@ public class ChannelOwner extends LoggingSupport { final String type; final String guid; final JsonObject initializer; - private boolean wasCollected; + private Map eventToSubscriptionMapping = new HashMap<>(); + boolean wasCollected; + // java: a call without a timeout; the server does not enforce one. static Double NO_TIMEOUT = null; protected ChannelOwner(ChannelOwner parent, String type, String guid, JsonObject initializer) { this(parent.connection, parent, type, guid, initializer); } + // java: upstream has one constructor taking `parent: ChannelOwner | Connection`; this is the Connection case. protected ChannelOwner(Connection connection, String type, String guid) { this(connection, null, type, guid, new JsonObject()); } - private ChannelOwner(Connection connection, ChannelOwner parent, String type, String guid, JsonObject initializer) { this.connection = connection; - this.parent = parent; this.type = type; this.guid = guid; + this.parent = parent; + + this.connection.registerObject(guid, this); + if (this.parent != null) { + this.parent.objects.put(guid, this); + } + this.initializer = initializer; + } - connection.registerObject(guid, this); - if (parent != null) { - parent.objects.put(guid, this); + void setEventToSubscriptionMapping(Map mapping) { + this.eventToSubscriptionMapping = mapping; + } + + // java: upstream calls this from the overridden on/off of its event emitter; ListenerCollection does it until EventEmitter is ported. + void updateSubscription(String event, boolean enabled) { + String protocolEvent = eventToSubscriptionMapping.get(event); + if (protocolEvent != null) { + JsonObject params = new JsonObject(); + params.addProperty("event", protocolEvent); + params.addProperty("enabled", enabled); + sendMessageAsync("updateSubscription", params); } } - void disposeChannelOwner(boolean wasGarbageCollected) { + void adopt(ChannelOwner child) { + child.parent.objects.remove(child.guid); + objects.put(child.guid, child); + child.parent = this; + } + + ChannelOwner parentOfType(String type) { + ChannelOwner parent = this.parent; + while (parent != null) { + if (parent.type.equals(type)) { + return parent; + } + parent = parent.parent; + } + return null; + } + + void dispose(String reason) { // Clean up from parent and connection. if (parent != null) { parent.objects.remove(guid); } connection.unregisterObject(guid); - wasCollected = wasGarbageCollected; + wasCollected = "gc".equals(reason); + // Dispose all children. - for (ChannelOwner child : new ArrayList<>(objects.values())) { - child.disposeChannelOwner(wasGarbageCollected); + for (ChannelOwner object : new ArrayList<>(objects.values())) { + object.dispose(reason); } objects.clear(); } - void adopt(ChannelOwner child) { - child.parent.objects.remove(child.guid); - objects.put(child.guid, child); - child.parent = this; + // java: upstream's createChannel() wraps every channel call in wrapApiCall and sends the message + // from there. This builds the options of that message; the zone of a call without wrapApiCall is + // not installed, so that the calls of event handlers dispatched while the call waits are reported on their own. + private Connection.CallOptions callOptions(Double timeout) { + ApiZone apiZone = connection.apiZone; + if (apiZone == null) { + apiZone = new ApiZone(null, false); + } + Connection.CallOptions options = new Connection.CallOptions(); + options.timeout = timeout; + if (!apiZone.internal && !apiZone.reported) { + // Reporting/tracing/logging this api call for the first time. + apiZone.reported = true; + options.title = apiZone.title; + options.frames = connection.captureLibraryStackTrace(); + } else { + // Since this api call is either internal, or has already been reported/traced once, + // passing as internal. + options.internal = true; + } + return options; + } + + R wrapApiCall(Supplier func, String title, boolean internal) { + if (connection.apiZone != null) { + return func.get(); + } + // java: no stack trace is captured here, the first message of the call does it (see callOptions). + ApiZone apiZone = new ApiZone(title, internal); + connection.apiZone = apiZone; + try { + return func.get(); + } finally { + connection.apiZone = null; + } + } + + // java: the Runnable overload for calls without a result. + void wrapApiCall(Runnable func, String title, boolean internal) { + wrapApiCall(() -> { + func.run(); + return null; + }, title, internal); + } + + // java: the tracing title of a call, upstream passes it to @apiCall / _wrapApiCall. + void withTitle(String title, Runnable code) { + wrapApiCall(code, title, false); + } + + T withTitle(String title, Supplier code) { + return wrapApiCall(code, title, false); } T withWaitLogging(String apiName, Function code) { @@ -93,30 +178,13 @@ T withWaitLoggingTitled(String apiName, String title, Function co return new WaitForEventLogger<>(this, apiName, null, title, code).get(); } - - void withTitle(String title, Runnable code) { - withTitle(title, () -> { - code.run(); - return null; - }); - } - - T withTitle(String title, Supplier code) { - String previousTitle = connection.setTitle(title); - try { - return code.get(); - } finally { - connection.setTitle(previousTitle); - } - } - + // java: the sendMessage family is the typed channel proxy of upstream's createChannel(). WaitableResult sendMessageAsync(String method) { return sendMessageAsync(method, new JsonObject()); } WaitableResult sendMessageAsync(String method, JsonObject params) { - checkNotCollected(); - return connection.sendMessageAsync(guid, method, params); + return connection.sendMessageToServer(this, method, params, callOptions(null)); } /** Typed counterpart of {@link #sendMessageAsync(String, JsonObject)}; {@code null} params mean an empty object. */ @@ -138,12 +206,10 @@ private JsonObject paramsToJson(Object params) { return json; } - // Fire-and-forget: silently drop if the object was collected. + // Fire-and-forget: Connection.sendMessageToServer registers no callback for __waitInfo__, the only caller, + // and drops it silently when the object was collected. void sendMessageNoReply(String method, JsonObject params) { - if (wasCollected) { - return; - } - connection.sendMessageNoReply(guid, method, params); + connection.sendMessageToServer(this, method, params, callOptions(null)); } JsonElement sendMessage(String method) { @@ -151,14 +217,13 @@ JsonElement sendMessage(String method) { } JsonElement sendMessage(String method, JsonObject params, Double timeout) { - checkNotCollected(); if (timeout != null) { // Timeout is passed in the message metadata, remove potential leftover from serialized options. params.remove("timeout"); } else if (params.has("timeout")) { throw new PlaywrightException("Internal error: timeout must be passed explicitly."); } - return connection.sendMessage(guid, method, params, timeout); + return connection.sendMessage(this, method, params, callOptions(timeout)); } /** @@ -180,11 +245,7 @@ public void sendMessage(String method, Object params, Double timeout) { sendMessage(method, params, Void.class, timeout); } - private void checkNotCollected() { - if (wasCollected) - throw new PlaywrightException("The object has been collected to prevent unbounded heap growth."); - } - + // java: pumps the connection until the waitable is done; upstream awaits promises. T runUntil(Runnable code, Waitable waitable) { try { code.run(); @@ -197,12 +258,25 @@ T runUntil(Runnable code, Waitable waitable) { } } + // java: upstream's Connection.dispatch emits the event on the channel; subclasses override this until EventEmitter is ported. void handleEvent(String event, JsonObject parameters) { } + // java: upstream's tChannelImplToWire. JsonObject toProtocolRef() { JsonObject json = new JsonObject(); json.addProperty("guid", guid); return json; } } + +class ApiZone { + final String title; + final boolean internal; + boolean reported; + + ApiZone(String title, boolean internal) { + this.title = title; + this.internal = internal; + } +} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java index 42b2bd1c3..3ad4d435e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -13,19 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +// Port of packages/playwright-core/src/client/connection.ts package com.microsoft.playwright.impl; import com.microsoft.playwright.impl.protocol.*; import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.TimeoutError; @@ -40,233 +42,271 @@ import java.util.concurrent.TimeUnit; import static com.microsoft.playwright.impl.Serialization.gson; -import static java.lang.System.currentTimeMillis; -class Message { - String id; - String guid; - String method; - JsonObject params; - JsonElement result; - SerializedError error; - JsonObject errorDetails; - JsonArray log; +class Root extends ChannelOwner { + Root(Connection connection) { + super(connection, "Root", ""); + } - @Override - public String toString() { - return "Message{" + - "id='" + id + '\'' + - ", guid='" + guid + '\'' + - ", method='" + method + '\'' + - ", params=" + (params == null ? null : "<...>") + - ", result='" + result + '\'' + - ", error='" + Errors.errorToString(error) + '\'' + - '}'; + PlaywrightImpl initialize() { + RootInitializeParams params = new RootInitializeParams(); + params.sdkLanguage = "java"; + return new RootChannel(this).initialize(params, NO_TIMEOUT).playwright; } } +class DummyChannelOwner extends ChannelOwner { + DummyChannelOwner(ChannelOwner parent, String type, String guid, JsonObject initializer) { + super(parent, type, guid, initializer); + } +} + +interface ChannelOwnerFactory { + ChannelOwner create(ChannelOwner parent, String type, String guid, JsonObject initializer); +} public class Connection { + final Map objects = new HashMap<>(); + // java: upstream keeps { resolve, reject, signal, title, type, method } per call, nothing but the result is needed here. + private final Map> callbacks = new HashMap<>(); + private final Root rootObject; + private TargetClosedError closedError; + private boolean isRemote = false; + private LocalUtils localUtils; + private int tracingCount; + private final Map objectFactories = new HashMap<>(); + + // java: everything below has no counterpart in connection.ts. private final Transport transport; - private final Map objects = new HashMap<>(); + // Upstream creates the ids with createCallIdGenerator(); the prefix is unique for each client to avoid id clashes in a trace. + private final String callIdPrefix = createCallIdPrefix(); + private int lastId = 0; + private final StackTraceCollector stackTraceCollector; private final Gson protocolGson = gson().newBuilder() .registerTypeAdapterFactory(new ChannelOwnerAdapterFactory()) .registerTypeAdapter(byte[].class, new Base64Adapter().nullSafe()) .create(); - private final Root root; - final boolean isRemote; - private int lastId = 0; - // Use a unique prefix for each client to avoid id clashes in a trace. - private final String callIdPrefix = createCallIdPrefix(); - private final StackTraceCollector stackTraceCollector; - private final Map> callbacks = new HashMap<>(); - private String title; - private boolean titleReported = false; + // java: upstream keeps the api zone in an AsyncLocalStorage; the single API thread keeps it here, see ChannelOwner.wrapApiCall. + ApiZone apiZone; + PlaywrightImpl playwright; + final Map env; private static final long DRIVER_RESPONSE_GRACE_MS = 10_000; private static final boolean isLogging; static { String debug = System.getenv("DEBUG"); isLogging = (debug != null) && debug.contains("pw:channel"); } - LocalUtils localUtils; - PlaywrightImpl playwright; - final Map env; - private int tracingCount; - - class Root extends ChannelOwner { - Root(Connection connection) { - super(connection, "Root", ""); - } - PlaywrightImpl initialize() { - RootInitializeParams params = new RootInitializeParams(); - params.sdkLanguage = "java"; - params.supportsLoneSurrogates = true; - return new RootChannel(this).initialize(params, NO_TIMEOUT).playwright; - } + /** The options of upstream's sendMessageToServer; {@code timeout == null} means that no timeout is sent. */ + static class CallOptions { + String title; + boolean internal; + Double timeout; + JsonArray frames; } + // java: the connection of a connect() call is remote and shares LocalUtils with the driver connection. Connection(Transport pipe, Map env, LocalUtils localUtils) { - this(pipe, env, true); - this.localUtils = localUtils; + this(pipe, env, localUtils, true); } Connection(Transport transport, Map env) { - this(transport, env, false); + this(transport, env, null, false); } - private Connection(Transport transport, Map env, boolean isRemote) { + private Connection(Transport transport, Map env, LocalUtils localUtils, boolean remote) { this.env = env; - this.isRemote = isRemote; if (isLogging) { transport = new TransportLogger(transport); } this.transport = transport; - root = new Root(this); stackTraceCollector = StackTraceCollector.createFromEnv(env); + this.localUtils = localUtils; + this.rootObject = new Root(this); + if (remote) { + markAsRemote(); + } + registerObjectFactories(); } - private static String createCallIdPrefix() { - String alphabet = "abcdefghijklmnopqrstuvwxyz"; - StringBuilder prefix = new StringBuilder(); - for (int i = 0; i < 4; i++) { - prefix.append(alphabet.charAt(ThreadLocalRandom.current().nextInt(alphabet.length()))); - } - return prefix.toString(); + private void registerObjectFactories() { + // java: Android and Electron are not ported, their objects are ignored. + objectFactories.put("Android", (parent, type, guid, init) -> null); + objectFactories.put("AndroidDevice", (parent, type, guid, init) -> null); + objectFactories.put("AndroidSocket", (parent, type, guid, init) -> null); + objectFactories.put("APIRequestContext", (parent, type, guid, init) -> new APIRequestContextImpl(parent, type, guid, init)); + objectFactories.put("Artifact", (parent, type, guid, init) -> new ArtifactImpl(parent, type, guid, init)); + objectFactories.put("BindingCall", (parent, type, guid, init) -> new BindingCall(parent, type, guid, init)); + objectFactories.put("Browser", (parent, type, guid, init) -> new BrowserImpl(parent, type, guid, init)); + objectFactories.put("BrowserContext", (parent, type, guid, init) -> new BrowserContextImpl(parent, type, guid, init)); + objectFactories.put("BrowserType", (parent, type, guid, init) -> new BrowserTypeImpl(parent, type, guid, init)); + objectFactories.put("CDPSession", (parent, type, guid, init) -> new CDPSessionImpl(parent, type, guid, init)); + objectFactories.put("Debugger", (parent, type, guid, init) -> new DebuggerImpl(parent, type, guid, init)); + objectFactories.put("Dialog", (parent, type, guid, init) -> new DialogImpl(parent, type, guid, init)); + objectFactories.put("Disposable", (parent, type, guid, init) -> new DisposableObject(parent, type, guid, init)); + objectFactories.put("Electron", (parent, type, guid, init) -> null); + objectFactories.put("ElementHandle", (parent, type, guid, init) -> new ElementHandleImpl(parent, type, guid, init)); + objectFactories.put("Frame", (parent, type, guid, init) -> new FrameImpl(parent, type, guid, init)); + objectFactories.put("JSHandle", (parent, type, guid, init) -> new JSHandleImpl(parent, type, guid, init)); + objectFactories.put("JsonPipe", (parent, type, guid, init) -> new JsonPipe(parent, type, guid, init)); + objectFactories.put("LocalUtils", (parent, type, guid, init) -> { + LocalUtils result = new LocalUtils(parent, type, guid, init); + if (localUtils == null) { + localUtils = result; + } + return result; + }); + objectFactories.put("Page", (parent, type, guid, init) -> new PageImpl(parent, type, guid, init)); + objectFactories.put("Playwright", (parent, type, guid, init) -> new PlaywrightImpl(parent, type, guid, init)); + objectFactories.put("Request", (parent, type, guid, init) -> new RequestImpl(parent, type, guid, init)); + objectFactories.put("Response", (parent, type, guid, init) -> new ResponseImpl(parent, type, guid, init)); + objectFactories.put("Route", (parent, type, guid, init) -> new RouteImpl(parent, type, guid, init)); + objectFactories.put("Stream", (parent, type, guid, init) -> new Stream(parent, type, guid, init)); + objectFactories.put("SocksSupport", (parent, type, guid, init) -> new DummyChannelOwner(parent, type, guid, init)); + objectFactories.put("Tracing", (parent, type, guid, init) -> new TracingImpl(parent, type, guid, init)); + objectFactories.put("WebSocket", (parent, type, guid, init) -> new WebSocketImpl(parent, type, guid, init)); + objectFactories.put("WebSocketRoute", (parent, type, guid, init) -> new WebSocketRouteImpl(parent, type, guid, init)); + objectFactories.put("Worker", (parent, type, guid, init) -> new WorkerImpl(parent, type, guid, init)); + objectFactories.put("WritableStream", (parent, type, guid, init) -> new WritableStream(parent, type, guid, init)); } - void setIsTracing(boolean tracing) { - if (tracing) { - ++tracingCount; - } else { - --tracingCount; - } + void markAsRemote() { + isRemote = true; } - String title() { - return title; + boolean isRemote() { + return isRemote; } - String setTitle(String newTitle) { - String previous = title; - titleReported = false; - title = newTitle; - return previous; + LocalUtils localUtils() { + return localUtils; } - void close() throws IOException { - transport.close(); + public PlaywrightImpl initializePlaywright() { + // java: also remembered for getByTestId, which needs the selectors of the Playwright object. + playwright = rootObject.initialize(); + return playwright; } - public JsonElement sendMessage(String guid, String method, JsonObject params) { - return sendMessage(guid, method, params, null); + // java: upstream has getObjectWithKnownName(guid) for the same lookup; this one throws for an unknown guid. + public T getExistingObject(String guid) { + @SuppressWarnings("unchecked") T result = (T) objects.get(guid); + if (result == null) + throw new PlaywrightException("Object doesn't exist: " + guid); + return result; } - public JsonElement sendMessage(String guid, String method, JsonObject params, Double timeout) { - WaitableResult result = internalSendMessage(guid, method, params, timeout, true, true); - if (timeout == null || timeout == 0) { - return root.runUntil(() -> {}, result); - } - // The driver enforces the timeout, but the driver itself may hang. - long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.longValue() + DRIVER_RESPONSE_GRACE_MS); - while (!result.isDone()) { - if (!processOneMessage() && System.nanoTime() - deadline > 0) { - result.completeExceptionally(new TimeoutError("Timeout " + timeout.longValue() + "ms exceeded while waiting for the driver to respond to " + - method + ". The driver is not responding.")); - } - } - return result.get(); + void registerObject(String guid, ChannelOwner object) { + objects.put(guid, object); } - public WaitableResult sendMessageAsync(String guid, String method, JsonObject params) { - return internalSendMessage(guid, method, params, null, true, true); + void unregisterObject(String guid) { + objects.remove(guid); } - // Fire-and-forget: the server never replies. - public void sendMessageNoReply(String guid, String method, JsonObject params) { - internalSendMessage(guid, method, params, null, false, false); + void setIsTracing(boolean tracing) { + if (tracing) { + ++tracingCount; + } else { + --tracingCount; + } } - private WaitableResult internalSendMessage(String guid, String method, JsonObject params, Double timeout, boolean sendStack, boolean expectsReply) { - String id = callIdPrefix + "@" + (++lastId); - WaitableResult result = new WaitableResult<>(); - if (expectsReply) { - callbacks.put(id, result); + // java: upstream returns a promise; the result is completed by dispatch() while some thread pumps messages. + WaitableResult sendMessageToServer(ChannelOwner object, String method, JsonObject params, CallOptions options) { + // Fire-and-forget: server intentionally never replies to __waitInfo__, + // so silently drop it after the connection is closed or the object was collected. + if ("__waitInfo__".equals(method) && (closedError != null || object.wasCollected)) { + return completed(); + } + if (closedError != null) { + // java: a new exception, so that the stack trace points at the caller. + throw new TargetClosedError(closedError.getMessage(), closedError); + } + if (object.wasCollected) { + throw new PlaywrightException("The object has been collected to prevent unbounded heap growth."); } + + String guid = object.guid; + String type = object.type; + String id = callIdPrefix + "@" + (++lastId); JsonObject message = new JsonObject(); message.addProperty("id", id); message.addProperty("guid", guid); message.addProperty("method", method); message.add("params", params); JsonObject metadata = new JsonObject(); - metadata.addProperty("wallTime", currentTimeMillis()); - if (timeout != null) { - metadata.addProperty("timeout", timeout); + if (options.title != null) { + metadata.addProperty("title", options.title); + } + if (options.frames != null && !options.frames.isEmpty()) { + JsonObject frame = options.frames.get(0).getAsJsonObject(); + JsonObject location = new JsonObject(); + location.addProperty("file", frame.get("file").getAsString()); + location.addProperty("line", frame.get("line").getAsInt()); + location.addProperty("column", frame.get("column").getAsInt()); + metadata.add("location", location); } - JsonArray stack = null; - if (titleReported) { + if (options.internal) { metadata.addProperty("internal", true); - } else { - if (title != null) { - metadata.addProperty("title", title); - // All but first message in a custom-titled API call are considered internal and will be hidden from the inspector. - titleReported = true; - } - if (stackTraceCollector != null) { - stack = stackTraceCollector.currentStackTrace(); - if (!stack.isEmpty()) { - JsonObject location = new JsonObject(); - JsonObject frame = stack.get(0).getAsJsonObject(); - location.addProperty("file", frame.get("file").getAsString()); - location.addProperty("line", frame.get("line").getAsInt()); - location.addProperty("column", frame.get("column").getAsInt()); - metadata.add("location", location); - } - } + } + // java: upstream always sends a timeout, 0 by default; here null stays absent. + if (options.timeout != null) { + metadata.addProperty("timeout", options.timeout); } message.add("metadata", metadata); + // java: registered before sending, the callback is looked up by id only when a reply arrives. + WaitableResult result = new WaitableResult<>(); + // Fire-and-forget: server intentionally never replies to __waitInfo__. + boolean expectsReply = !"__waitInfo__".equals(method); + if (expectsReply) { + callbacks.put(id, result); + } transport.send(message); - if (sendStack && tracingCount > 0 && stack != null && !method.startsWith("LocalUtils")) { + if (tracingCount > 0 && options.frames != null && !"LocalUtils".equals(type)) { JsonObject callData = new JsonObject(); callData.addProperty("id", id); - callData.add("stack", stack); + callData.add("stack", options.frames); JsonObject stackParams = new JsonObject(); stackParams.add("callData", callData); // LocalUtils belongs to the driver connection, which is not this one when the browser came from connect(). - localUtils.connection.internalSendMessage(localUtils.guid,"addStackToTracingNoReply", stackParams, null, false, true); + CallOptions stackOptions = new CallOptions(); + stackOptions.internal = true; + localUtils.connection.sendMessageToServer(localUtils, "addStackToTracingNoReply", stackParams, stackOptions); } - return result; - } - - public PlaywrightImpl initializePlaywright() { - playwright = root.initialize(); - return playwright; - } - - LocalUtils localUtils() { - return localUtils; + return expectsReply ? result : completed(); } - /** Gson that serializes channel owners as {guid} and resolves them back through this connection (see channelOwner.ts, connection.ts upstream). */ - Gson protocolGson() { - return protocolGson; - } - - public T getExistingObject(String guid) { - @SuppressWarnings("unchecked") T result = (T) objects.get(guid); - if (result == null) - throw new PlaywrightException("Object doesn't exist: " + guid); + private static WaitableResult completed() { + WaitableResult result = new WaitableResult<>(); + result.complete(null); return result; } - void registerObject(String guid, ChannelOwner object) { - objects.put(guid, object); - } - - void unregisterObject(String guid) { - objects.remove(guid); + // java: sends the message and pumps messages until the reply arrives; upstream awaits the promise of sendMessageToServer. + JsonElement sendMessage(ChannelOwner object, String method, JsonObject params, CallOptions options) { + if (closedError != null && transport instanceof JsonPipe) { + // java: a call over a closed JsonPipe fails like the pipe does, with the reason the server gave + // ('Browser closed' after it went away); async calls and waits get the closedError. + throw new TargetClosedError(((JsonPipe) transport).closeReason(), closedError); + } + WaitableResult result = sendMessageToServer(object, method, params, options); + Double timeout = options.timeout; + if (timeout == null || timeout == 0) { + return rootObject.runUntil(() -> {}, result); + } + // The driver enforces the timeout, but the driver itself may hang. + long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout.longValue() + DRIVER_RESPONSE_GRACE_MS); + while (!result.isDone()) { + if (!processOneMessage() && System.nanoTime() - deadline > 0) { + result.completeExceptionally(new TimeoutError("Timeout " + timeout.longValue() + "ms exceeded while waiting for the driver to respond to " + + method + ". The driver is not responding.")); + } + } + return result.get(); } + // java: upstream receives messages through onmessage(); here the pump polls the transport. boolean processOneMessage() { JsonObject message = transport.poll(Duration.ofMillis(10)); if (message == null) { @@ -278,6 +318,84 @@ boolean processOneMessage() { return true; } + private void dispatch(Message message) { + if (closedError != null) { + return; + } + + if (message.id != null) { + WaitableResult callback = callbacks.get(message.id); + if (callback == null) { + throw new PlaywrightException("Cannot find command to respond: " + message.id); + } + callbacks.remove(message.id); + if (message.error == null) { + callback.complete(message.result); + } else { + PlaywrightException parsedError = Errors.parseError(message.error, formatCallLog(message.log)); + if (message.errorDetails != null) { + parsedError = new ServerErrorWithDetails(parsedError, message.errorDetails, message.log); + } + callback.completeExceptionally(parsedError); + } + return; + } + + // TODO: throw? + if (message.method == null) { + return; + } + if (message.method.equals("__create__")) { + createRemoteObject(message.guid, message.params.get("type").getAsString(), message.params.get("guid").getAsString(), message.params.getAsJsonObject("initializer")); + return; + } + + ChannelOwner object = objects.get(message.guid); + if (object == null) { + throw new PlaywrightException("Cannot find object to call " + message.method + ": " + message.guid); + } + if (message.method.equals("__adopt__")) { + String childGuid = message.params.get("guid").getAsString(); + ChannelOwner child = objects.get(childGuid); + if (child == null) { + throw new PlaywrightException("Unknown new child: " + childGuid); + } + object.adopt(child); + return; + } + if (message.method.equals("__dispose__")) { + String reason = message.params != null && message.params.has("reason") ? message.params.get("reason").getAsString() : null; + object.dispose(reason); + return; + } + + // java: upstream emits the event on the channel, ChannelOwner.handleEvent does the same until EventEmitter is ported. + object.handleEvent(message.method, message.params); + } + + void close() throws IOException { + close(null); + } + + void close(String cause) throws IOException { + if (closedError != null) { + return; + } + closedError = new TargetClosedError(cause); + for (WaitableResult callback : callbacks.values()) { + callback.completeExceptionally(closedError); + } + callbacks.clear(); + // java: upstream emits 'close' here; the transport has to be closed as well. + transport.close(); + } + + // java: upstream's _tChannelImplFromWire and, in channelOwner.ts, tChannelImplToWire; Gson adapters instead of validator hooks. + /** Gson that serializes channel owners as {guid} and resolves them back through this connection. */ + Gson protocolGson() { + return protocolGson; + } + private class ChannelOwnerAdapterFactory implements TypeAdapterFactory { @Override @SuppressWarnings("unchecked") @@ -333,6 +451,32 @@ public byte[] read(JsonReader in) throws IOException { } } + private ChannelOwner createRemoteObject(String parentGuid, String type, String guid, JsonObject initializer) { + ChannelOwner parent = objects.get(parentGuid); + if (parent == null) { + throw new PlaywrightException("Cannot find parent object " + parentGuid + " to create " + guid); + } + ChannelOwnerFactory factory = objectFactories.get(type); + if (factory == null) { + throw new PlaywrightException("Unknown type " + type); + } + return factory.create(parent, type, guid, initializer); + } + + // java: upstream's captureLibraryStackTrace() lives in clientStackTrace.ts; null when PLAYWRIGHT_JAVA_SRC is not set. + JsonArray captureLibraryStackTrace() { + return stackTraceCollector == null ? null : stackTraceCollector.captureLibraryStackTrace(); + } + + private static String createCallIdPrefix() { + String alphabet = "abcdefghijklmnopqrstuvwxyz"; + StringBuilder prefix = new StringBuilder(); + for (int i = 0; i < 4; i++) { + prefix.append(alphabet.charAt(ThreadLocalRandom.current().nextInt(alphabet.length()))); + } + return prefix.toString(); + } + private static String formatCallLog(JsonArray log) { if (log == null) { return ""; @@ -356,169 +500,28 @@ private static String formatCallLog(JsonArray log) { lines.add(""); return String.join("\n", lines); } +} - private void dispatch(Message message) { -// System.out.println("Message: " + message.method + " " + message.id); - if (message.id != null) { - WaitableResult callback = callbacks.get(message.id); - if (callback == null) { - throw new PlaywrightException("Cannot find command to respond: " + message.id); - } - callbacks.remove(message.id); -// System.out.println("Message: " + message.id + " " + message); - if (message.error == null) { - callback.complete(message.result); - } else { - PlaywrightException exception = Errors.parseError(message.error, formatCallLog(message.log)); - if (message.errorDetails != null) { - exception = new ServerErrorWithDetails(exception, message.errorDetails, message.log); - } - callback.completeExceptionally(exception); - } - return; - } - - // TODO: throw? - if (message.method == null) { - return; - } - if (message.method.equals("__create__")) { - createRemoteObject(message.guid, message.params); - return; - } - - ChannelOwner object = objects.get(message.guid); - if (object == null) { - throw new PlaywrightException("Cannot find object to call " + message.method + ": " + message.guid); - } - if (message.method.equals("__adopt__")) { - String childGuid = message.params.get("guid").getAsString(); - ChannelOwner child = objects.get(childGuid); - if (child == null) { - throw new PlaywrightException("Unknown new child: " + childGuid); - } - object.adopt(child); - return; - } - if (message.method.equals("__dispose__")) { - boolean wasCollected = message.params.has("reason") && "gc".equals(message.params.get("reason").getAsString()); - object.disposeChannelOwner(wasCollected); - return; - } - object.handleEvent(message.method, message.params); - } - - private ChannelOwner createRemoteObject(String parentGuid, JsonObject params) { - String type = params.get("type").getAsString(); - String guid = params.get("guid").getAsString(); - - ChannelOwner parent = objects.get(parentGuid); - if (parent == null) { - throw new PlaywrightException("Cannot find parent object " + parentGuid + " to create " + guid); - } - JsonObject initializer = params.getAsJsonObject("initializer"); - ChannelOwner result = null; - switch (type) { - case "Android": -// result = new Android(parent, type, guid, initializer); - break; - case "AndroidSocket": -// result = new AndroidSocket(parent, type, guid, initializer); - break; - case "AndroidDevice": -// result = new AndroidDevice(parent, type, guid, initializer); - break; - case "Artifact": - result = new ArtifactImpl(parent, type, guid, initializer); - break; - case "BindingCall": - result = new BindingCall(parent, type, guid, initializer); - break; - case "BrowserType": - result = new BrowserTypeImpl(parent, type, guid, initializer); - break; - case "Browser": - result = new BrowserImpl(parent, type, guid, initializer); - break; - case "BrowserContext": - result = new BrowserContextImpl(parent, type, guid, initializer); - break; - case "Dialog": - result = new DialogImpl(parent, type, guid, initializer); - break; - case "Disposable": - result = new DisposableObject(parent, type, guid, initializer); - break; - case "Electron": -// result = new Playwright(parent, type, guid, initializer); - break; - case "ElementHandle": - result = new ElementHandleImpl(parent, type, guid, initializer); - break; - case "APIRequestContext": - // Create fake object as this API is experimental an only exposed in Node.js. - result = new APIRequestContextImpl(parent, type, guid, initializer); - break; - case "Frame": - result = new FrameImpl(parent, type, guid, initializer); - break; - case "JSHandle": - result = new JSHandleImpl(parent, type, guid, initializer); - break; - case "JsonPipe": - result = new JsonPipe(parent, type, guid, initializer); - break; - case "LocalUtils": - result = new LocalUtils(parent, type, guid, initializer); - if (localUtils == null) { - localUtils = (LocalUtils) result; - } - break; - case "Page": - result = new PageImpl(parent, type, guid, initializer); - break; - case "Playwright": - result = new PlaywrightImpl(parent, type, guid, initializer); - break; - case "Request": - result = new RequestImpl(parent, type, guid, initializer); - break; - case "Response": - result = new ResponseImpl(parent, type, guid, initializer); - break; - case "Route": - result = new RouteImpl(parent, type, guid, initializer); - break; - case "Stream": - result = new Stream(parent, type, guid, initializer); - break; - case "SocksSupport": - break; - case "Debugger": - result = new DebuggerImpl(parent, type, guid, initializer); - break; - case "Tracing": - result = new TracingImpl(parent, type, guid, initializer); - break; - case "WebSocket": - result = new WebSocketImpl(parent, type, guid, initializer); - break; - case "WebSocketRoute": - result = new WebSocketRouteImpl(parent, type, guid, initializer); - break; - case "Worker": - result = new WorkerImpl(parent, type, guid, initializer); - break; - case "WritableStream": - result = new WritableStream(parent, type, guid, initializer); - break; - case "CDPSession": - result = new CDPSessionImpl(parent, type, guid, initializer); - break; - default: - throw new PlaywrightException("Unknown type " + type); - } +// java: the wire shape of an incoming message. +class Message { + String id; + String guid; + String method; + JsonObject params; + JsonElement result; + SerializedError error; + JsonObject errorDetails; + JsonArray log; - return result; + @Override + public String toString() { + return "Message{" + + "id='" + id + '\'' + + ", guid='" + guid + '\'' + + ", method='" + method + '\'' + + ", params=" + (params == null ? null : "<...>") + + ", result='" + result + '\'' + + ", error='" + Errors.errorToString(error) + '\'' + + '}'; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index 4cfd275b7..05fe9ecad 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -974,7 +974,7 @@ private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavi List> waitables = new ArrayList<>(); if (matcher == null) { - matcher = UrlMatcher.forOneOf(page.context().baseUrl(), options.url, this.connection.localUtils, false); + matcher = UrlMatcher.forOneOf(page.context().baseUrl(), options.url, this.connection.localUtils(), false); } logger.log("waiting for navigation " + matcher); waitables.add(new WaitForNavigationHelper(matcher, options.waitUntil, logger)); @@ -1008,7 +1008,7 @@ public void waitForTimeout(double timeout) { @Override public void waitForURL(String url, WaitForURLOptions options) { - waitForURL(UrlMatcher.forGlob(page.context().baseUrl(), url, this.connection.localUtils, false), options); + waitForURL(UrlMatcher.forGlob(page.context().baseUrl(), url, this.connection.localUtils(), false), options); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java index b791721d8..5df37b39e 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -86,6 +86,10 @@ public void close() throws IOException { } } + String closeReason() { + return closeReason; + } + void onClose(Consumer handler) { listeners.add(EventType.CLOSE, handler); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java b/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java index b0cce97d5..30e4eb889 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java @@ -16,7 +16,6 @@ package com.microsoft.playwright.impl; -import com.google.gson.JsonObject; import com.microsoft.playwright.PlaywrightException; import java.util.*; @@ -24,15 +23,21 @@ class ListenerCollection { private final HashMap>> listeners = new HashMap<>(); - private final Map eventSubscriptions; private final ChannelOwner channelOwner; ListenerCollection() { this(null, null); } ListenerCollection(Map eventSubscriptions, ChannelOwner channelOwner) { - this.eventSubscriptions = eventSubscriptions; this.channelOwner = channelOwner; + if (eventSubscriptions != null) { + // java: the per-class EventType enums stay until EventEmitter is ported, the owner is keyed by their names. + Map mapping = new HashMap<>(); + for (Map.Entry entry : eventSubscriptions.entrySet()) { + mapping.put(entry.getKey().toString(), entry.getValue()); + } + channelOwner.setEventToSubscriptionMapping(mapping); + } } void notify(EventType eventType, T param) { @@ -76,16 +81,8 @@ boolean hasListeners(EventType type) { } private void updateSubscription(EventType eventType, boolean enabled) { - if (eventSubscriptions == null) { - return; - } - String protocolEvent = eventSubscriptions.get(eventType); - if (protocolEvent == null) { - return; + if (channelOwner != null) { + channelOwner.updateSubscription(eventType.toString(), enabled); } - JsonObject params = new JsonObject(); - params.addProperty("event", protocolEvent); - params.addProperty("enabled", enabled); - channelOwner.sendMessageAsync("updateSubscription", params); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index f055df985..87670c74b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -822,7 +822,7 @@ public Frame frame(String name) { @Override public Frame frameByUrl(String glob) { - return frameFor(UrlMatcher.forGlob(browserContext.baseUrl(), glob, this.connection.localUtils, false)); + return frameFor(UrlMatcher.forGlob(browserContext.baseUrl(), glob, this.connection.localUtils(), false)); } @Override @@ -1172,7 +1172,7 @@ private Response reloadImpl(ReloadOptions options) { @Override public AutoCloseable route(String url, Consumer handler, RouteOptions options) { - route(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils, false), handler, options); + route(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), handler, options); return new DisposableStub(() -> unroute(url, handler)); } @@ -1197,8 +1197,8 @@ public void routeFromHAR(Path har, RouteFromHAROptions options) { browserContext.recordIntoHar(this, har, convertType(options, BrowserContext.RouteFromHAROptions.class), null); return; } - UrlMatcher matcher = UrlMatcher.forOneOf(browserContext.baseUrl(), options.url, this.connection.localUtils, false); - HARRouter harRouter = new HARRouter(connection.localUtils, har, options.notFound); + UrlMatcher matcher = UrlMatcher.forOneOf(browserContext.baseUrl(), options.url, this.connection.localUtils(), false); + HARRouter harRouter = new HARRouter(connection.localUtils(), har, options.notFound); onClose(context -> harRouter.dispose()); route(matcher, route -> harRouter.handle(route), null); } @@ -1210,7 +1210,7 @@ private void route(UrlMatcher matcher, Consumer handler, RouteOptions opt @Override public void routeWebSocket(String url, Consumer handler) { - routeWebSocketImpl(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils, true), handler); + routeWebSocketImpl(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), true), handler); } @Override @@ -1397,7 +1397,7 @@ public void unrouteAll() { @Override public void unroute(String url, Consumer handler) { - unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils, false), handler); + unroute(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), handler); } @Override @@ -1543,7 +1543,7 @@ public T get() { @Override public Request waitForRequest(String urlGlob, WaitForRequestOptions options, Runnable code) { - return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils, false), null, options, code); + return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, options, code); } @Override @@ -1588,7 +1588,7 @@ private Request waitForRequestFinishedImpl(WaitForRequestFinishedOptions options @Override public Response waitForResponse(String urlGlob, WaitForResponseOptions options, Runnable code) { - return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils, false), null, options, code); + return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, options, code); } @Override @@ -1640,7 +1640,7 @@ public void waitForTimeout(double timeout) { @Override public void waitForURL(String url, WaitForURLOptions options) { - waitForURL(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils, false), options); + waitForURL(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), options); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java index 070e754ea..448d9a2a5 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PlaywrightImpl.java @@ -84,7 +84,7 @@ public static PlaywrightImpl createImpl(CreateOptions options, boolean forceNewD } public LocalUtils localUtils() { - return connection.localUtils; + return connection.localUtils(); } public JsonArray deviceDescriptors() { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java b/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java index 3ebaacac1..7d2c365bd 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/StackTraceCollector.java @@ -14,6 +14,7 @@ * limitations under the License. */ +// Port of packages/playwright-core/src/client/clientStackTrace.ts package com.microsoft.playwright.impl; import com.google.gson.JsonArray; @@ -27,6 +28,9 @@ import java.util.*; import java.util.stream.Collectors; +// java: clientStackTrace.ts exports one function, captureLibraryStackTrace(), which returns the frames +// outside of the library and the api name. The api name is not used here (the tracing titles come from +// wrapApiCall), and the frames are mapped to source files of PLAYWRIGHT_JAVA_SRC; hence a class with state. class StackTraceCollector { static final String PLAYWRIGHT_JAVA_SRC = "PLAYWRIGHT_JAVA_SRC"; private final List srcDirs; @@ -97,7 +101,7 @@ private String resolveSourcePath(Path relativePath) { return path; } - JsonArray currentStackTrace() { + JsonArray captureLibraryStackTrace() { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); int index = 0; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java index 3ee126d9b..b9199199b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TracingImpl.java @@ -101,11 +101,11 @@ private void saveChunk(Path path, String stacksId, List capturedAddition return; } - boolean isLocal = !connection.isRemote; + boolean isLocal = !connection.isRemote(); if (isLocal) { params.mode = "entries"; TracingTracingStopChunkResult result = channel.tracingStopChunk(params, NO_TIMEOUT); - connection.localUtils.zip(path, result.entries, stacksId, false, includeSources, capturedAdditionalSources); + connection.localUtils().zip(path, result.entries, stacksId, false, includeSources, capturedAdditionalSources); return; } @@ -131,7 +131,7 @@ private void saveChunk(Path path, String stacksId, List capturedAddition } artifact.delete(); - connection.localUtils.zip(path, new ArrayList<>(), stacksId, true, includeSources, capturedAdditionalSources); + connection.localUtils().zip(path, new ArrayList<>(), stacksId, true, includeSources, capturedAdditionalSources); } @Override @@ -284,7 +284,7 @@ void exportHar(String harId) { if (harParams == null) { return; } - boolean isLocal = !connection.isRemote; + boolean isLocal = !connection.isRemote(); boolean isZip = isZip(harParams.path); TracingHarExportParams params = new TracingHarExportParams(); @@ -295,7 +295,7 @@ void exportHar(String harId) { if (!isZip) { return; } - connection.localUtils.zip(harParams.path, json.entries, null, false, false, java.util.Collections.emptyList()); + connection.localUtils().zip(harParams.path, json.entries, null, false, false, java.util.Collections.emptyList()); return; } @@ -312,7 +312,7 @@ void exportHar(String harId) { LocalUtilsHarUnzipParams unzipParams = new LocalUtilsHarUnzipParams(); unzipParams.zipFile = tmpPath; unzipParams.harFile = harParams.path.toString(); - connection.localUtils.channel.harUnzip(unzipParams, NO_TIMEOUT); + connection.localUtils().channel.harUnzip(unzipParams, NO_TIMEOUT); artifact.delete(); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java index c7578feff..fa4f92435 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Utils.java @@ -182,7 +182,7 @@ static UploadParams addFilePathUploadParams(Path[] items, BrowserContextImpl con if (items.length == 0) { // FIXME: shouldBeAbleToResetSelectedFilesWithEmptyFileList tesst hangs in Chromium if we pass empty paths list. upload.emptyPayloads = true; - } else if (context.connection.isRemote) { + } else if (context.connection.isRemote()) { if (localDirectory != null) { localPaths = collectFiles(localDirectory); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java index a4bb66d65..ca5e45424 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/VideoImpl.java @@ -43,7 +43,7 @@ public void delete() { @Override public Path path() { - if (page.connection.isRemote) { + if (page.connection.isRemote()) { throw new PlaywrightException("Path is not available when using browserType.connect(). Use saveAs() to save a local copy."); } if (artifact == null) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java b/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java index 530100255..63c394c94 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java @@ -78,19 +78,11 @@ private void sendWaitInfo(JsonObject info) { // message only, so that the calls made from the callback of the wait are not hidden as internal. private void sendWaitInfo(JsonObject info, String title) { info.addProperty("waitId", waitId); - Connection connection = channel.connection; - boolean setTitle = title != null && connection.title() == null; - if (setTitle) { - connection.setTitle(title); - } + // java: wrapApiCall reuses the zone of an outer call, so that call keeps its own title. try { - channel.sendMessageNoReply("__waitInfo__", info); + channel.wrapApiCall(() -> channel.sendMessageNoReply("__waitInfo__", info), title, false); } catch (RuntimeException e) { // Fire-and-forget: never throw to the caller. - } finally { - if (setTitle) { - connection.setTitle(null); - } } } } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java index c7ad5d68f..1c2faecfe 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java @@ -677,7 +677,6 @@ void shouldEmitCloseEventsOnPagesAndContexts(Connect connect, StartRemoteServer @PlaywrightTest @DisplayName("BT-059 should terminate network waiters") - @Fixme("java: the error of a wait after a disconnect is 'Browser closed', not the target closed message") void shouldTerminateNetworkWaiters(Connect connect, StartRemoteServer startRemoteServer, TestServer server) { PlaywrightServer remoteServer = startRemoteServer.start(kind); Browser browser = connect.connect(remoteServer.wsEndpoint()); From 5590430e8779ca2108dec66c55ee565ccf7c9fa3 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:19:53 -0800 Subject: [PATCH 03/14] refactor(events): port events.ts --- .../com/microsoft/playwright/impl/Events.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Events.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Events.java b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java new file mode 100644 index 000000000..37400a6fc --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Events.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Port of packages/playwright-core/src/client/events.ts +package com.microsoft.playwright.impl; + +final class Events { + private Events() { + } + + static final class Browser { + static final String CONTEXT = "context"; + static final String DISCONNECTED = "disconnected"; + } + + static final class Debugger { + static final String PAUSED_STATE_CHANGED = "pausedstatechanged"; + static final String API_CALLS_UPDATED = "apicallsupdated"; + } + + static final class BrowserContext { + static final String CONSOLE = "console"; + static final String CLOSE = "close"; + static final String DIALOG = "dialog"; + static final String DIALOG_CLOSED = "dialogclosed"; + static final String DOWNLOAD = "download"; + static final String FRAME_ATTACHED = "frameattached"; + static final String FRAME_DETACHED = "framedetached"; + static final String FRAME_NAVIGATED = "framenavigated"; + static final String PAGE = "page"; + static final String PAGE_CLOSE = "pageclose"; + static final String PAGE_LOAD = "pageload"; + // Can't use just 'error' due to node.js special treatment of error events. + static final String WEB_ERROR = "weberror"; + static final String BACKGROUND_PAGE = "backgroundpage"; // Deprecated in v1.56, never emitted anymore. + static final String SERVICE_WORKER = "serviceworker"; + static final String REQUEST = "request"; + static final String RESPONSE = "response"; + static final String REQUEST_FAILED = "requestfailed"; + static final String REQUEST_FINISHED = "requestfinished"; + } + + static final class Page { + static final String CLOSE = "close"; + static final String CRASH = "crash"; + static final String CONSOLE = "console"; + static final String DIALOG = "dialog"; + static final String DIALOG_CLOSED = "dialogclosed"; + static final String DOWNLOAD = "download"; + static final String FILE_CHOOSER = "filechooser"; + static final String DOM_CONTENT_LOADED = "domcontentloaded"; + // Can't use just 'error' due to node.js special treatment of error events. + static final String PAGE_ERROR = "pageerror"; + static final String REQUEST = "request"; + static final String RESPONSE = "response"; + static final String REQUEST_FAILED = "requestfailed"; + static final String REQUEST_FINISHED = "requestfinished"; + static final String FRAME_ATTACHED = "frameattached"; + static final String FRAME_DETACHED = "framedetached"; + static final String FRAME_NAVIGATED = "framenavigated"; + static final String LOAD = "load"; + static final String POPUP = "popup"; + static final String WEB_SOCKET = "websocket"; + static final String WORKER = "worker"; + } + + static final class WebSocket { + static final String CLOSE = "close"; + static final String ERROR = "socketerror"; + static final String FRAME_RECEIVED = "framereceived"; + static final String FRAME_SENT = "framesent"; + } + + static final class Worker { + static final String CLOSE = "close"; + static final String CONSOLE = "console"; + } + + // java: events that upstream emits as string literals (cdpSession.ts) or does not have (the Java + // frame waits that upstream implements with promises, the json pipe close that the transport observes). + static final class CDPSession { + static final String CLOSE = "close"; + } + + static final class Frame { + static final String LOAD_STATE = "loadstate"; + static final String NAVIGATED = "navigated"; + } + + static final class JsonPipe { + static final String CLOSE = "close"; + } +} From 341d6883a0f0ac96becf9a436cbfa7463d7f0486 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:20:31 -0800 Subject: [PATCH 04/14] refactor(events): port eventEmitter.ts --- .../playwright/impl/CDPSessionImpl.java | 7 +- .../playwright/impl/ChannelOwner.java | 33 ++++++- .../playwright/impl/EventEmitter.java | 88 +++++++++++++++++++ 3 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java index 6f28c69be..7a00f70b6 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -79,13 +79,16 @@ public JsonObject send(String method, JsonObject params, SendOptions options) { else return response.result.getAsJsonObject(); } + // java: the raw parameter type overrides EventEmitter.on(String, Consumer) and implements CDPSession.on at once. @Override - public void on(String event, Consumer handler) { + @SuppressWarnings("rawtypes") + public void on(String event, Consumer handler) { listeners.add(event, handler); } @Override - public void off(String event, Consumer handler) { + @SuppressWarnings("rawtypes") + public void off(String event, Consumer handler) { listeners.remove(event, handler); } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index 62d5e70f1..4e3321521 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -24,10 +24,11 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -public class ChannelOwner extends LoggingSupport { +public class ChannelOwner extends EventEmitter { final Connection connection; private ChannelOwner parent; private final Map objects = new HashMap<>(); @@ -68,7 +69,6 @@ void setEventToSubscriptionMapping(Map mapping) { this.eventToSubscriptionMapping = mapping; } - // java: upstream calls this from the overridden on/off of its event emitter; ListenerCollection does it until EventEmitter is ported. void updateSubscription(String event, boolean enabled) { String protocolEvent = eventToSubscriptionMapping.get(event); if (protocolEvent != null) { @@ -79,6 +79,35 @@ void updateSubscription(String event, boolean enabled) { } } + // java: the listener is added first so that a null listener fails before anything is sent. + @Override + void on(String event, Consumer listener) { + addListener(event, listener); + } + + @Override + void addListener(String event, Consumer listener) { + super.addListener(event, listener); + if (listenerCount(event) == 1) { + updateSubscription(event, true); + } + } + + @Override + void off(String event, Consumer listener) { + removeListener(event, listener); + } + + @Override + void removeListener(String event, Consumer listener) { + // java: nothing is sent when there was no listener to remove, upstream sends the disable message anyway. + boolean hadListeners = listenerCount(event) > 0; + super.removeListener(event, listener); + if (hadListeners && listenerCount(event) == 0) { + updateSubscription(event, false); + } + } + void adopt(ChannelOwner child) { child.parent.objects.remove(child.guid); objects.put(child.guid, child); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java new file mode 100644 index 000000000..5d35e5533 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/EventEmitter.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Port of packages/playwright-core/src/client/eventEmitter.ts +package com.microsoft.playwright.impl; + +import com.microsoft.playwright.PlaywrightException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +// java: upstream's ChannelOwner and the rest of the client reach the logging helpers through +// imports; here they stay reachable as inherited statics. +class EventEmitter extends LoggingSupport { + private final Map>> events = new HashMap<>(); + + void emit(String type, T arg) { + List> handlers = events.get(type); + if (handlers == null) { + return; + } + // The handlers are copied, a handler may remove itself. + for (Consumer handler : new ArrayList<>(handlers)) { + ((Consumer) handler).accept(arg); + } + } + + void addListener(String type, Consumer listener) { + if (listener == null) { + throw new PlaywrightException("Can't add a null listener"); + } + List> list = events.get(type); + if (list == null) { + list = new ArrayList<>(); + events.put(type, list); + } + list.add(listener); + } + + void on(String type, Consumer listener) { + addListener(type, listener); + } + + void removeListener(String type, Consumer listener) { + List> list = events.get(type); + if (list == null) { + return; + } + // java: removes every registration of the listener, upstream removes the last one only. + list.removeAll(java.util.Collections.singleton(listener)); + if (list.isEmpty()) { + events.remove(type); + } + } + + void off(String type, Consumer listener) { + removeListener(type, listener); + } + + void removeAllListeners(String type) { + events.remove(type); + } + + int listenerCount(String type) { + List> list = events.get(type); + return list == null ? 0 : list.size(); + } + + List> listeners(String type) { + List> list = events.get(type); + return list == null ? new ArrayList>() : new ArrayList<>(list); + } +} From 96130f7b767a33fddf0f6eb4d6610c824738515f Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:21:55 -0800 Subject: [PATCH 05/14] refactor(events): emit upstream event names --- .../playwright/impl/BrowserContextImpl.java | 174 ++++++++--------- .../playwright/impl/BrowserImpl.java | 18 +- .../playwright/impl/CDPSessionImpl.java | 21 +- .../microsoft/playwright/impl/FrameImpl.java | 20 +- .../microsoft/playwright/impl/JsonPipe.java | 8 +- .../playwright/impl/ListenerCollection.java | 88 --------- .../microsoft/playwright/impl/PageImpl.java | 182 ++++++++---------- .../playwright/impl/WaitableEvent.java | 18 +- .../playwright/impl/WebSocketImpl.java | 48 ++--- .../microsoft/playwright/impl/WorkerImpl.java | 24 +-- 10 files changed, 217 insertions(+), 384 deletions(-) delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java index f35c22854..2520b26a3 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -55,55 +55,33 @@ public class BrowserContextImpl extends ChannelOwner implements BrowserContext { final Router routes = new Router(); final WebSocketRouter webSocketRoutes = new WebSocketRouter(); private boolean closingOrClosed; - private final WaitableEvent closePromise; + private final WaitableEvent closePromise; final Map bindings = new HashMap<>(); PageImpl ownerPage; private String closeReason; - private static final Map eventSubscriptions() { - Map result = new HashMap<>(); - result.put(EventType.CONSOLE, "console"); - result.put(EventType.DIALOG, "dialog"); - result.put(EventType.DIALOGCLOSED, "dialogClosed"); - result.put(EventType.REQUEST, "request"); - result.put(EventType.RESPONSE, "response"); - result.put(EventType.REQUESTFINISHED, "requestFinished"); - result.put(EventType.REQUESTFAILED, "requestFailed"); - return result; - } - private final ListenerCollection listeners = new ListenerCollection<>(eventSubscriptions(), this); final TimeoutSettings timeoutSettings = new TimeoutSettings(); - enum EventType { - CLOSE, - CONSOLE, - DIALOG, - DIALOGCLOSED, - DOWNLOAD, - FRAMEATTACHED, - FRAMEDETACHED, - FRAMENAVIGATED, - PAGE, - PAGECLOSE, - PAGELOAD, - WEBERROR, - REQUEST, - REQUESTFAILED, - REQUESTFINISHED, - RESPONSE, - } - final BrowserContextChannel channel = new BrowserContextChannel(this); BrowserContextImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); + Map mapping = new HashMap<>(); + mapping.put(Events.BrowserContext.CONSOLE, "console"); + mapping.put(Events.BrowserContext.DIALOG, "dialog"); + mapping.put(Events.BrowserContext.DIALOG_CLOSED, "dialogClosed"); + mapping.put(Events.BrowserContext.REQUEST, "request"); + mapping.put(Events.BrowserContext.RESPONSE, "response"); + mapping.put(Events.BrowserContext.REQUEST_FINISHED, "requestFinished"); + mapping.put(Events.BrowserContext.REQUEST_FAILED, "requestFailed"); + setEventToSubscriptionMapping(mapping); tracing = connection.getExistingObject(initializer.getAsJsonObject("tracing").get("guid").getAsString()); debugger = connection.getExistingObject(initializer.getAsJsonObject("debugger").get("guid").getAsString()); request = connection.getExistingObject(initializer.getAsJsonObject("requestContext").get("guid").getAsString()); request.timeoutSettings = timeoutSettings; clock = new ClockImpl(this); credentials = new CredentialsImpl(this); - closePromise = new WaitableEvent<>(listeners, EventType.CLOSE); + closePromise = new WaitableEvent<>(this, Events.BrowserContext.CLOSE); } Path videosDir() { @@ -145,186 +123,186 @@ public void offBackgroundPage(Consumer handler) { @Override public void onDownload(Consumer handler) { - listeners.add(EventType.DOWNLOAD, handler); + on(Events.BrowserContext.DOWNLOAD, handler); } @Override public void offDownload(Consumer handler) { - listeners.remove(EventType.DOWNLOAD, handler); + off(Events.BrowserContext.DOWNLOAD, handler); } void notifyDownload(Download download) { - listeners.notify(EventType.DOWNLOAD, download); + emit(Events.BrowserContext.DOWNLOAD, download); } @Override public void onClose(Consumer handler) { - listeners.add(EventType.CLOSE, handler); + on(Events.BrowserContext.CLOSE, handler); } @Override public void offClose(Consumer handler) { - listeners.remove(EventType.CLOSE, handler); + off(Events.BrowserContext.CLOSE, handler); } @Override public void onConsoleMessage(Consumer handler) { - listeners.add(EventType.CONSOLE, handler); + on(Events.BrowserContext.CONSOLE, handler); } @Override public void offConsoleMessage(Consumer handler) { - listeners.remove(EventType.CONSOLE, handler); + off(Events.BrowserContext.CONSOLE, handler); } @Override public void onDialog(Consumer handler) { - listeners.add(EventType.DIALOG, handler); + on(Events.BrowserContext.DIALOG, handler); } @Override public void offDialog(Consumer handler) { - listeners.remove(EventType.DIALOG, handler); + off(Events.BrowserContext.DIALOG, handler); } @Override public void onDialogClosed(Consumer handler) { - listeners.add(EventType.DIALOGCLOSED, handler); + on(Events.BrowserContext.DIALOG_CLOSED, handler); } @Override public void offDialogClosed(Consumer handler) { - listeners.remove(EventType.DIALOGCLOSED, handler); + off(Events.BrowserContext.DIALOG_CLOSED, handler); } @Override public void onPage(Consumer handler) { - listeners.add(EventType.PAGE, handler); + on(Events.BrowserContext.PAGE, handler); } @Override public void offPage(Consumer handler) { - listeners.remove(EventType.PAGE, handler); + off(Events.BrowserContext.PAGE, handler); } @Override public void onFrameAttached(Consumer handler) { - listeners.add(EventType.FRAMEATTACHED, handler); + on(Events.BrowserContext.FRAME_ATTACHED, handler); } @Override public void offFrameAttached(Consumer handler) { - listeners.remove(EventType.FRAMEATTACHED, handler); + off(Events.BrowserContext.FRAME_ATTACHED, handler); } void notifyFrameAttached(FrameImpl frame) { - listeners.notify(EventType.FRAMEATTACHED, frame); + emit(Events.BrowserContext.FRAME_ATTACHED, frame); } @Override public void onFrameDetached(Consumer handler) { - listeners.add(EventType.FRAMEDETACHED, handler); + on(Events.BrowserContext.FRAME_DETACHED, handler); } @Override public void offFrameDetached(Consumer handler) { - listeners.remove(EventType.FRAMEDETACHED, handler); + off(Events.BrowserContext.FRAME_DETACHED, handler); } void notifyFrameDetached(FrameImpl frame) { - listeners.notify(EventType.FRAMEDETACHED, frame); + emit(Events.BrowserContext.FRAME_DETACHED, frame); } @Override public void onFrameNavigated(Consumer handler) { - listeners.add(EventType.FRAMENAVIGATED, handler); + on(Events.BrowserContext.FRAME_NAVIGATED, handler); } @Override public void offFrameNavigated(Consumer handler) { - listeners.remove(EventType.FRAMENAVIGATED, handler); + off(Events.BrowserContext.FRAME_NAVIGATED, handler); } void notifyFrameNavigated(FrameImpl frame) { - listeners.notify(EventType.FRAMENAVIGATED, frame); + emit(Events.BrowserContext.FRAME_NAVIGATED, frame); } @Override public void onPageClose(Consumer handler) { - listeners.add(EventType.PAGECLOSE, handler); + on(Events.BrowserContext.PAGE_CLOSE, handler); } @Override public void offPageClose(Consumer handler) { - listeners.remove(EventType.PAGECLOSE, handler); + off(Events.BrowserContext.PAGE_CLOSE, handler); } void notifyPageClose(PageImpl page) { - listeners.notify(EventType.PAGECLOSE, page); + emit(Events.BrowserContext.PAGE_CLOSE, page); } @Override public void onPageLoad(Consumer handler) { - listeners.add(EventType.PAGELOAD, handler); + on(Events.BrowserContext.PAGE_LOAD, handler); } @Override public void offPageLoad(Consumer handler) { - listeners.remove(EventType.PAGELOAD, handler); + off(Events.BrowserContext.PAGE_LOAD, handler); } void notifyPageLoad(PageImpl page) { - listeners.notify(EventType.PAGELOAD, page); + emit(Events.BrowserContext.PAGE_LOAD, page); } @Override public void onWebError(Consumer handler) { - listeners.add(EventType.WEBERROR, handler); + on(Events.BrowserContext.WEB_ERROR, handler); } @Override public void offWebError(Consumer handler) { - listeners.remove(EventType.WEBERROR, handler); + off(Events.BrowserContext.WEB_ERROR, handler); } @Override public void onRequest(Consumer handler) { - listeners.add(EventType.REQUEST, handler); + on(Events.BrowserContext.REQUEST, handler); } @Override public void offRequest(Consumer handler) { - listeners.remove(EventType.REQUEST, handler); + off(Events.BrowserContext.REQUEST, handler); } @Override public void onRequestFailed(Consumer handler) { - listeners.add(EventType.REQUESTFAILED, handler); + on(Events.BrowserContext.REQUEST_FAILED, handler); } @Override public void offRequestFailed(Consumer handler) { - listeners.remove(EventType.REQUESTFAILED, handler); + off(Events.BrowserContext.REQUEST_FAILED, handler); } @Override public void onRequestFinished(Consumer handler) { - listeners.add(EventType.REQUESTFINISHED, handler); + on(Events.BrowserContext.REQUEST_FINISHED, handler); } @Override public void offRequestFinished(Consumer handler) { - listeners.remove(EventType.REQUESTFINISHED, handler); + off(Events.BrowserContext.REQUEST_FINISHED, handler); } @Override public void onResponse(Consumer handler) { - listeners.add(EventType.RESPONSE, handler); + on(Events.BrowserContext.RESPONSE, handler); } @Override public void offResponse(Consumer handler) { - listeners.remove(EventType.RESPONSE, handler); + off(Events.BrowserContext.RESPONSE, handler); } @Override @@ -337,9 +315,9 @@ public Credentials credentials() { return credentials; } - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { + private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); + waitables.add(new WaitableEvent<>(this, eventType, predicate)); waitables.add(new WaitableContextClose<>()); waitables.add(timeoutSettings.createWaitable(timeout)); return runUntil(code, new WaitableRace<>(waitables)); @@ -354,7 +332,7 @@ private Page waitForPageImpl(WaitForPageOptions options, Runnable code) { if (options == null) { options = new WaitForPageOptions(); } - return waitForEventWithTimeout(EventType.PAGE, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.BrowserContext.PAGE, code, options.predicate, options.timeout); } @Override @@ -712,12 +690,12 @@ private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions op if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(EventType.CONSOLE, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.BrowserContext.CONSOLE, code, options.predicate, options.timeout); } - private class WaitableContextClose extends WaitableEvent { + private class WaitableContextClose extends WaitableEvent { WaitableContextClose() { - super(BrowserContextImpl.this.listeners, EventType.CLOSE); + super(BrowserContextImpl.this, Events.BrowserContext.CLOSE); } @Override @@ -774,15 +752,15 @@ protected void handleEvent(String event, JsonObject params) { String guid = params.getAsJsonObject("dialog").get("guid").getAsString(); DialogImpl dialog = connection.getExistingObject(guid); boolean hasListeners = false; - if (listeners.hasListeners(EventType.DIALOG)) { + if (listenerCount(Events.BrowserContext.DIALOG) > 0) { hasListeners = true; - listeners.notify(EventType.DIALOG, dialog); + emit(Events.BrowserContext.DIALOG, dialog); } PageImpl page = dialog.page(); if (page != null) { - if (page.listeners.hasListeners(PageImpl.EventType.DIALOG)) { + if (page.listenerCount(Events.Page.DIALOG) > 0) { hasListeners = true; - page.listeners.notify(PageImpl.EventType.DIALOG, dialog); + page.emit(Events.Page.DIALOG, dialog); } } // Although we do similar handling on the server side, we still need this logic @@ -801,10 +779,10 @@ protected void handleEvent(String event, JsonObject params) { } } else if ("dialogClosed".equals(event)) { DialogImpl dialog = connection.getExistingObject(params.getAsJsonObject("dialog").get("guid").getAsString()); - listeners.notify(EventType.DIALOGCLOSED, dialog); + emit(Events.BrowserContext.DIALOG_CLOSED, dialog); PageImpl page = dialog.page(); if (page != null) { - page.listeners.notify(PageImpl.EventType.DIALOGCLOSED, dialog); + page.emit(Events.Page.DIALOG_CLOSED, dialog); } } else if ("route".equals(event)) { RouteImpl route = connection.getExistingObject(params.getAsJsonObject("route").get("guid").getAsString()); @@ -816,7 +794,7 @@ protected void handleEvent(String event, JsonObject params) { } else if ("page".equals(event)) { PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); pages.add(page); - listeners.notify(EventType.PAGE, page); + emit(Events.BrowserContext.PAGE, page); if (page.opener() != null && !page.opener().isClosed()) { page.opener().notifyPopup(page); } @@ -831,20 +809,20 @@ protected void handleEvent(String event, JsonObject params) { PageImpl page = consoleEvent.page; WorkerImpl worker = consoleEvent.worker; ConsoleMessageImpl message = new ConsoleMessageImpl(consoleEvent); - listeners.notify(BrowserContextImpl.EventType.CONSOLE, message); + emit(Events.BrowserContext.CONSOLE, message); if (worker != null) { - worker.listeners.notify(WorkerImpl.EventType.CONSOLE, message); + worker.emit(Events.Worker.CONSOLE, message); } if (page != null) { - page.listeners.notify(PageImpl.EventType.CONSOLE, message); + page.emit(Events.Page.CONSOLE, message); } } else if ("request".equals(event)) { String guid = params.getAsJsonObject("request").get("guid").getAsString(); RequestImpl request = connection.getExistingObject(guid); - listeners.notify(EventType.REQUEST, request); + emit(Events.BrowserContext.REQUEST, request); if (params.has("page")) { PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.listeners.notify(PageImpl.EventType.REQUEST, request); + page.emit(Events.Page.REQUEST, request); } } else if ("requestFailed".equals(event)) { String guid = params.getAsJsonObject("request").get("guid").getAsString(); @@ -856,10 +834,10 @@ protected void handleEvent(String event, JsonObject params) { if (request.timing != null) { request.timing.responseEnd = params.get("responseEndTiming").getAsDouble(); } - listeners.notify(EventType.REQUESTFAILED, request); + emit(Events.BrowserContext.REQUEST_FAILED, request); if (params.has("page")) { PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.listeners.notify(PageImpl.EventType.REQUESTFAILED, request); + page.emit(Events.Page.REQUEST_FAILED, request); } } else if ("requestFinished".equals(event)) { String guid = params.getAsJsonObject("request").get("guid").getAsString(); @@ -868,18 +846,18 @@ protected void handleEvent(String event, JsonObject params) { if (request.timing != null) { request.timing.responseEnd = params.get("responseEndTiming").getAsDouble(); } - listeners.notify(EventType.REQUESTFINISHED, request); + emit(Events.BrowserContext.REQUEST_FINISHED, request); if (params.has("page")) { PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.listeners.notify(PageImpl.EventType.REQUESTFINISHED, request); + page.emit(Events.Page.REQUEST_FINISHED, request); } } else if ("response".equals(event)) { String guid = params.getAsJsonObject("response").get("guid").getAsString(); ResponseImpl response = connection.getExistingObject(guid); - listeners.notify(EventType.RESPONSE, response); + emit(Events.BrowserContext.RESPONSE, response); if (params.has("page")) { PageImpl page = connection.getExistingObject(params.getAsJsonObject("page").get("guid").getAsString()); - page.listeners.notify(PageImpl.EventType.RESPONSE, response); + page.emit(Events.Page.RESPONSE, response); } } else if ("pageError".equals(event)) { String errorStr = parseError(params.getAsJsonObject("error")); @@ -893,9 +871,9 @@ protected void handleEvent(String event, JsonObject params) { if (params.has("location")) { location = gson().fromJson(params.getAsJsonObject("location"), WebErrorLocation.class); } - listeners.notify(BrowserContextImpl.EventType.WEBERROR, new WebErrorImpl(page, errorStr, location)); + emit(Events.BrowserContext.WEB_ERROR, new WebErrorImpl(page, errorStr, location)); if (page != null) { - page.listeners.notify(PageImpl.EventType.PAGEERROR, errorStr); + page.emit(Events.Page.PAGE_ERROR, errorStr); } } else if ("close".equals(event)) { didClose(); @@ -910,7 +888,7 @@ void didClose() { } tracing.resetStackCounter(); request.tracing().resetStackCounter(); - listeners.notify(EventType.CLOSE, this); + emit(Events.BrowserContext.CLOSE, this); } protected void initializeHarFromOptions(Browser.NewContextOptions options) { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java index 5ac321362..5a0c23e26 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -40,7 +40,6 @@ public class BrowserImpl extends ChannelOwner implements Browser { // Insertion order, so that browser.contexts() lists the contexts in creation order like the other clients. final Set contexts = new LinkedHashSet<>(); - private final ListenerCollection listeners = new ListenerCollection<>(); boolean isConnectedOverWebSocket; private boolean isConnected = true; BrowserTypeImpl browserType; @@ -48,11 +47,6 @@ public class BrowserImpl extends ChannelOwner implements Browser { private Path tracePath; String closeReason; - enum EventType { - CONTEXT, - DISCONNECTED, - } - final BrowserChannel channel = new BrowserChannel(this); BrowserImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { @@ -61,22 +55,22 @@ enum EventType { @Override public void onContext(Consumer handler) { - listeners.add(EventType.CONTEXT, handler); + on(Events.Browser.CONTEXT, handler); } @Override public void offContext(Consumer handler) { - listeners.remove(EventType.CONTEXT, handler); + off(Events.Browser.CONTEXT, handler); } @Override public void onDisconnected(Consumer handler) { - listeners.add(EventType.DISCONNECTED, handler); + on(Events.Browser.DISCONNECTED, handler); } @Override public void offDisconnected(Consumer handler) { - listeners.remove(EventType.DISCONNECTED, handler); + off(Events.Browser.DISCONNECTED, handler); } @Override @@ -365,11 +359,11 @@ private void didCreateContext(BrowserContextImpl context) { context.setTracesDir(tracePath); browserType.playwright.selectors.contextsForSelectors.add(context); } - listeners.notify(EventType.CONTEXT, context); + emit(Events.Browser.CONTEXT, context); } private void didClose() { isConnected = false; - listeners.notify(EventType.DISCONNECTED, this); + emit(Events.Browser.DISCONNECTED, this); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java index 7a00f70b6..07ad4d812 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -21,16 +21,9 @@ import com.google.gson.JsonObject; import com.microsoft.playwright.CDPSession; -import java.util.HashMap; import java.util.function.Consumer; public class CDPSessionImpl extends ChannelOwner implements CDPSession { - private final ListenerCollection listeners = new ListenerCollection<>(new HashMap<>(), this); - private final ListenerCollection typedListeners = new ListenerCollection<>(new HashMap<>(), this); - - enum EventType { - CLOSE, - } final CDPSessionChannel channel = new CDPSessionChannel(this); @@ -47,21 +40,21 @@ void handleEvent(String event, JsonObject parameters) { if (parameters.has("params")) { params = parameters.get("params").getAsJsonObject(); } - listeners.notify(method, params); - listeners.notify("event", parameters); + emit(method, params); + emit("event", parameters); } else if ("close".equals(event)) { - typedListeners.notify(EventType.CLOSE, this); + emit(Events.CDPSession.CLOSE, this); } } @Override public void onClose(Consumer handler) { - typedListeners.add(EventType.CLOSE, handler); + on(Events.CDPSession.CLOSE, handler); } @Override public void offClose(Consumer handler) { - typedListeners.remove(EventType.CLOSE, handler); + off(Events.CDPSession.CLOSE, handler); } public JsonObject send(String method) { @@ -83,13 +76,13 @@ public JsonObject send(String method, JsonObject params, SendOptions options) { @Override @SuppressWarnings("rawtypes") public void on(String event, Consumer handler) { - listeners.add(event, handler); + super.on(event, handler); } @Override @SuppressWarnings("rawtypes") public void off(String event, Consumer handler) { - listeners.remove(event, handler); + off(event, handler); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index 05fe9ecad..b8ba9151a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -44,8 +44,6 @@ public class FrameImpl extends ChannelOwner implements Frame { Set childFrames = new LinkedHashSet<>(); private final Set loadStates = new HashSet<>(); - enum InternalEventType { NAVIGATED, LOADSTATE } - private final ListenerCollection internalListeners = new ListenerCollection<>(); PageImpl page; boolean isDetached; private final WebMCPImpl webmcp = new WebMCPImpl(this); @@ -859,7 +857,7 @@ private class WaitForLoadStateHelper implements Waitable, Consumer, Consumer incoming = new LinkedList<>(); - private ListenerCollection listeners = new ListenerCollection<>(); - private enum EventType { CLOSE } private boolean isClosed; private String closeReason = "Browser has been closed"; @@ -91,11 +89,11 @@ String closeReason() { } void onClose(Consumer handler) { - listeners.add(EventType.CLOSE, handler); + on(Events.JsonPipe.CLOSE, handler); } void offClose(Consumer handler) { - listeners.remove(EventType.CLOSE, handler); + off(Events.JsonPipe.CLOSE, handler); } @@ -111,7 +109,7 @@ protected void handleEvent(String event, JsonObject params) { closeReason = reason; } } - listeners.notify(EventType.CLOSE, this); + emit(Events.JsonPipe.CLOSE, this); } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java b/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java deleted file mode 100644 index 30e4eb889..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -import com.microsoft.playwright.PlaywrightException; - -import java.util.*; -import java.util.function.Consumer; - -class ListenerCollection { - private final HashMap>> listeners = new HashMap<>(); - private final ChannelOwner channelOwner; - - ListenerCollection() { - this(null, null); - } - ListenerCollection(Map eventSubscriptions, ChannelOwner channelOwner) { - this.channelOwner = channelOwner; - if (eventSubscriptions != null) { - // java: the per-class EventType enums stay until EventEmitter is ported, the owner is keyed by their names. - Map mapping = new HashMap<>(); - for (Map.Entry entry : eventSubscriptions.entrySet()) { - mapping.put(entry.getKey().toString(), entry.getValue()); - } - channelOwner.setEventToSubscriptionMapping(mapping); - } - } - - void notify(EventType eventType, T param) { - List> list = listeners.get(eventType); - if (list == null) { - return; - } - - for (Consumer listener: new ArrayList<>(list)) { - ((Consumer) listener).accept(param); - } - } - - void add(EventType type, Consumer listener) { - if (listener == null) { - throw new PlaywrightException("Can't add a null listener"); - } - List> list = listeners.get(type); - if (list == null) { - list = new ArrayList<>(); - listeners.put(type, list); - updateSubscription(type, true); - } - list.add(listener); - } - - void remove(EventType type, Consumer listener) { - List> list = listeners.get(type); - if (list == null) { - return; - } - list.removeAll(Collections.singleton(listener)); - if (list.isEmpty()) { - updateSubscription(type, false); - listeners.remove(type); - } - } - - boolean hasListeners(EventType type) { - return listeners.containsKey(type); - } - - private void updateSubscription(EventType eventType, boolean enabled) { - if (channelOwner != null) { - channelOwner.updateSubscription(eventType.toString(), enabled); - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index 87670c74b..1fae316f2 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -84,19 +84,6 @@ private boolean shouldRemove() { } } - private static final Map eventSubscriptions() { - Map result = new HashMap<>(); - result.put(EventType.CONSOLE, "console"); - result.put(EventType.DIALOG, "dialog"); - result.put(EventType.DIALOGCLOSED, "dialogClosed"); - result.put(EventType.REQUEST, "request"); - result.put(EventType.RESPONSE, "response"); - result.put(EventType.REQUESTFINISHED, "requestFinished"); - result.put(EventType.REQUESTFAILED, "requestFailed"); - result.put(EventType.FILECHOOSER, "fileChooser"); - return result; - } - final ListenerCollection listeners = new ListenerCollection(eventSubscriptions(), this); final Map bindings = new HashMap<>(); BrowserContextImpl ownedContext; private boolean isClosed; @@ -106,31 +93,18 @@ private static final Map eventSubscriptions() { private final PageImpl opener; private String closeReason; - enum EventType { - CLOSE, - CONSOLE, - CRASH, - DIALOG, - DIALOGCLOSED, - DOMCONTENTLOADED, - DOWNLOAD, - FILECHOOSER, - FRAMEATTACHED, - FRAMEDETACHED, - FRAMENAVIGATED, - LOAD, - PAGEERROR, - POPUP, - REQUEST, - REQUESTFAILED, - REQUESTFINISHED, - RESPONSE, - WEBSOCKET, - WORKER, - } - PageImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { super(parent, type, guid, initializer); + Map mapping = new HashMap<>(); + mapping.put(Events.Page.CONSOLE, "console"); + mapping.put(Events.Page.DIALOG, "dialog"); + mapping.put(Events.Page.DIALOG_CLOSED, "dialogClosed"); + mapping.put(Events.Page.REQUEST, "request"); + mapping.put(Events.Page.RESPONSE, "response"); + mapping.put(Events.Page.REQUEST_FINISHED, "requestFinished"); + mapping.put(Events.Page.REQUEST_FAILED, "requestFailed"); + mapping.put(Events.Page.FILE_CHOOSER, "fileChooser"); + setEventToSubscriptionMapping(mapping); browserContext = (BrowserContextImpl) parent; mainFrame = connection.getExistingObject(initializer.getAsJsonObject("mainFrame").get("guid").getAsString()); mainFrame.page = this; @@ -169,22 +143,22 @@ protected void handleEvent(String event, JsonObject params) { WorkerImpl worker = connection.getExistingObject(guid); worker.page = this; workers.add(worker); - listeners.notify(EventType.WORKER, worker); + emit(Events.Page.WORKER, worker); } else if ("webSocket".equals(event)) { String guid = params.getAsJsonObject("webSocket").get("guid").getAsString(); WebSocketImpl webSocket = connection.getExistingObject(guid); - listeners.notify(EventType.WEBSOCKET, webSocket); + emit(Events.Page.WEB_SOCKET, webSocket); } else if ("download".equals(event)) { String artifactGuid = params.getAsJsonObject("artifact").get("guid").getAsString(); ArtifactImpl artifact = connection.getExistingObject(artifactGuid); DownloadImpl download = new DownloadImpl(this, artifact, params); - listeners.notify(EventType.DOWNLOAD, download); + emit(Events.Page.DOWNLOAD, download); browserContext.notifyDownload(download); } else if ("fileChooser".equals(event)) { String guid = params.getAsJsonObject("element").get("guid").getAsString(); ElementHandleImpl elementHandle = connection.getExistingObject(guid); FileChooser fileChooser = new FileChooserImpl(this, elementHandle, params.get("isMultiple").getAsBoolean()); - listeners.notify(EventType.FILECHOOSER, fileChooser); + emit(Events.Page.FILE_CHOOSER, fileChooser); } else if ("bindingCall".equals(event)) { String guid = params.getAsJsonObject("binding").get("guid").getAsString(); BindingCall bindingCall = connection.getExistingObject(guid); @@ -209,7 +183,7 @@ protected void handleEvent(String event, JsonObject params) { if (frame.parentFrame != null) { frame.parentFrame.childFrames.add(frame); } - listeners.notify(EventType.FRAMEATTACHED, frame); + emit(Events.Page.FRAME_ATTACHED, frame); browserContext.notifyFrameAttached(frame); } else if ("frameDetached".equals(event)) { String guid = params.getAsJsonObject("frame").get("guid").getAsString(); @@ -219,7 +193,7 @@ protected void handleEvent(String event, JsonObject params) { if (frame.parentFrame != null) { frame.parentFrame.childFrames.remove(frame); } - listeners.notify(EventType.FRAMEDETACHED, frame); + emit(Events.Page.FRAME_DETACHED, frame); browserContext.notifyFrameDetached(frame); } else if ("locatorHandlerTriggered".equals(event)) { int uid = params.get("uid").getAsInt(); @@ -247,7 +221,7 @@ protected void handleEvent(String event, JsonObject params) { browserContext.handleWebSocketRoute(route); } } else if ("crash".equals(event)) { - listeners.notify(EventType.CRASH, this); + emit(Events.Page.CRASH, this); } else if ("close".equals(event)) { didClose(); } else if ("screencastFrame".equals(event)) { @@ -256,13 +230,13 @@ protected void handleEvent(String event, JsonObject params) { } void notifyPopup(PageImpl popup) { - listeners.notify(EventType.POPUP, popup); + emit(Events.Page.POPUP, popup); } void didClose() { isClosed = true; browserContext.pages.remove(this); - listeners.notify(EventType.CLOSE, this); + emit(Events.Page.CLOSE, this); browserContext.notifyPageClose(this); } @@ -275,202 +249,202 @@ private String effectiveCloseReason() { @Override public void onClose(Consumer handler) { - listeners.add(EventType.CLOSE, handler); + on(Events.Page.CLOSE, handler); } @Override public void offClose(Consumer handler) { - listeners.remove(EventType.CLOSE, handler); + off(Events.Page.CLOSE, handler); } @Override public void onConsoleMessage(Consumer handler) { - listeners.add(EventType.CONSOLE, handler); + on(Events.Page.CONSOLE, handler); } @Override public void offConsoleMessage(Consumer handler) { - listeners.remove(EventType.CONSOLE, handler); + off(Events.Page.CONSOLE, handler); } @Override public void onCrash(Consumer handler) { - listeners.add(EventType.CRASH, handler); + on(Events.Page.CRASH, handler); } @Override public void offCrash(Consumer handler) { - listeners.remove(EventType.CRASH, handler); + off(Events.Page.CRASH, handler); } @Override public void onDialog(Consumer handler) { - listeners.add(EventType.DIALOG, handler); + on(Events.Page.DIALOG, handler); } @Override public void offDialog(Consumer handler) { - listeners.remove(EventType.DIALOG, handler); + off(Events.Page.DIALOG, handler); } @Override public void onDialogClosed(Consumer handler) { - listeners.add(EventType.DIALOGCLOSED, handler); + on(Events.Page.DIALOG_CLOSED, handler); } @Override public void offDialogClosed(Consumer handler) { - listeners.remove(EventType.DIALOGCLOSED, handler); + off(Events.Page.DIALOG_CLOSED, handler); } @Override public void onDOMContentLoaded(Consumer handler) { - listeners.add(EventType.DOMCONTENTLOADED, handler); + on(Events.Page.DOM_CONTENT_LOADED, handler); } @Override public void offDOMContentLoaded(Consumer handler) { - listeners.remove(EventType.DOMCONTENTLOADED, handler); + off(Events.Page.DOM_CONTENT_LOADED, handler); } @Override public void onDownload(Consumer handler) { - listeners.add(EventType.DOWNLOAD, handler); + on(Events.Page.DOWNLOAD, handler); } @Override public void offDownload(Consumer handler) { - listeners.remove(EventType.DOWNLOAD, handler); + off(Events.Page.DOWNLOAD, handler); } @Override public void onFileChooser(Consumer handler) { - listeners.add(EventType.FILECHOOSER, handler); + on(Events.Page.FILE_CHOOSER, handler); } @Override public void offFileChooser(Consumer handler) { - listeners.remove(EventType.FILECHOOSER, handler); + off(Events.Page.FILE_CHOOSER, handler); } @Override public void onFrameAttached(Consumer handler) { - listeners.add(EventType.FRAMEATTACHED, handler); + on(Events.Page.FRAME_ATTACHED, handler); } @Override public void offFrameAttached(Consumer handler) { - listeners.remove(EventType.FRAMEATTACHED, handler); + off(Events.Page.FRAME_ATTACHED, handler); } @Override public void onFrameDetached(Consumer handler) { - listeners.add(EventType.FRAMEDETACHED, handler); + on(Events.Page.FRAME_DETACHED, handler); } @Override public void offFrameDetached(Consumer handler) { - listeners.remove(EventType.FRAMEDETACHED, handler); + off(Events.Page.FRAME_DETACHED, handler); } @Override public void onFrameNavigated(Consumer handler) { - listeners.add(EventType.FRAMENAVIGATED, handler); + on(Events.Page.FRAME_NAVIGATED, handler); } @Override public void offFrameNavigated(Consumer handler) { - listeners.remove(EventType.FRAMENAVIGATED, handler); + off(Events.Page.FRAME_NAVIGATED, handler); } @Override public void onLoad(Consumer handler) { - listeners.add(EventType.LOAD, handler); + on(Events.Page.LOAD, handler); } @Override public void offLoad(Consumer handler) { - listeners.remove(EventType.LOAD, handler); + off(Events.Page.LOAD, handler); } @Override public void onPageError(Consumer handler) { - listeners.add(EventType.PAGEERROR, handler); + on(Events.Page.PAGE_ERROR, handler); } @Override public void offPageError(Consumer handler) { - listeners.remove(EventType.PAGEERROR, handler); + off(Events.Page.PAGE_ERROR, handler); } @Override public void onPopup(Consumer handler) { - listeners.add(EventType.POPUP, handler); + on(Events.Page.POPUP, handler); } @Override public void offPopup(Consumer handler) { - listeners.remove(EventType.POPUP, handler); + off(Events.Page.POPUP, handler); } @Override public void onRequest(Consumer handler) { - listeners.add(EventType.REQUEST, handler); + on(Events.Page.REQUEST, handler); } @Override public void offRequest(Consumer handler) { - listeners.remove(EventType.REQUEST, handler); + off(Events.Page.REQUEST, handler); } @Override public void onRequestFailed(Consumer handler) { - listeners.add(EventType.REQUESTFAILED, handler); + on(Events.Page.REQUEST_FAILED, handler); } @Override public void offRequestFailed(Consumer handler) { - listeners.remove(EventType.REQUESTFAILED, handler); + off(Events.Page.REQUEST_FAILED, handler); } @Override public void onRequestFinished(Consumer handler) { - listeners.add(EventType.REQUESTFINISHED, handler); + on(Events.Page.REQUEST_FINISHED, handler); } @Override public void offRequestFinished(Consumer handler) { - listeners.remove(EventType.REQUESTFINISHED, handler); + off(Events.Page.REQUEST_FINISHED, handler); } @Override public void onResponse(Consumer handler) { - listeners.add(EventType.RESPONSE, handler); + on(Events.Page.RESPONSE, handler); } @Override public void offResponse(Consumer handler) { - listeners.remove(EventType.RESPONSE, handler); + off(Events.Page.RESPONSE, handler); } @Override public void onWebSocket(Consumer handler) { - listeners.add(EventType.WEBSOCKET, handler); + on(Events.Page.WEB_SOCKET, handler); } @Override public void offWebSocket(Consumer handler) { - listeners.remove(EventType.WEBSOCKET, handler); + off(Events.Page.WEB_SOCKET, handler); } @Override public void onWorker(Consumer handler) { - listeners.add(EventType.WORKER, handler); + on(Events.Page.WORKER, handler); } @Override public void offWorker(Consumer handler) { - listeners.remove(EventType.WORKER, handler); + off(Events.Page.WORKER, handler); } @Override @@ -487,7 +461,7 @@ private Page waitForCloseImpl(WaitForCloseOptions options, Runnable code) { if (options == null) { options = new WaitForCloseOptions(); } - return waitForEventWithTimeout(EventType.CLOSE, code, null, options.timeout); + return waitForEventWithTimeout(Events.Page.CLOSE, code, null, options.timeout); } @Override @@ -499,7 +473,7 @@ private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions op if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(EventType.CONSOLE, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.CONSOLE, code, options.predicate, options.timeout); } @Override @@ -511,7 +485,7 @@ private Download waitForDownloadImpl(WaitForDownloadOptions options, Runnable co if (options == null) { options = new WaitForDownloadOptions(); } - return waitForEventWithTimeout(EventType.DOWNLOAD, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.DOWNLOAD, code, options.predicate, options.timeout); } @Override @@ -524,7 +498,7 @@ private FileChooser waitForFileChooserImpl(WaitForFileChooserOptions options, Ru if (options == null) { options = new WaitForFileChooserOptions(); } - return waitForEventWithTimeout(EventType.FILECHOOSER, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.FILE_CHOOSER, code, options.predicate, options.timeout); } @Override @@ -536,7 +510,7 @@ private Page waitForPopupImpl(WaitForPopupOptions options, Runnable code) { if (options == null) { options = new WaitForPopupOptions(); } - return waitForEventWithTimeout(EventType.POPUP, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.POPUP, code, options.predicate, options.timeout); } @Override @@ -548,7 +522,7 @@ private WebSocket waitForWebSocketImpl(WaitForWebSocketOptions options, Runnable if (options == null) { options = new WaitForWebSocketOptions(); } - return waitForEventWithTimeout(EventType.WEBSOCKET, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.WEB_SOCKET, code, options.predicate, options.timeout); } @Override @@ -560,12 +534,12 @@ private Worker waitForWorkerImpl(WaitForWorkerOptions options, Runnable code) { if (options == null) { options = new WaitForWorkerOptions(); } - return waitForEventWithTimeout(EventType.WORKER, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.WORKER, code, options.predicate, options.timeout); } - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { + private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); + waitables.add(new WaitableEvent<>(this, eventType, predicate)); waitables.add(createWaitForCloseHelper()); waitables.add(createWaitableTimeout(timeout)); return runUntil(code, new WaitableRace<>(waitables)); @@ -1481,13 +1455,13 @@ private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavi } void frameNavigated(FrameImpl frame) { - listeners.notify(EventType.FRAMENAVIGATED, frame); + emit(Events.Page.FRAME_NAVIGATED, frame); browserContext.notifyFrameNavigated(frame); } - private class WaitableFrameDetach extends WaitableEvent { + private class WaitableFrameDetach extends WaitableEvent { WaitableFrameDetach(Frame frameArg) { - super(PageImpl.this.listeners, EventType.FRAMEDETACHED, detachedFrame -> frameArg.equals(detachedFrame)); + super(PageImpl.this, Events.Page.FRAME_DETACHED, detachedFrame -> frameArg.equals(detachedFrame)); } @Override @@ -1511,11 +1485,11 @@ Waitable createWaitForCloseHelper(boolean rejectIfClosed) { return new WaitableRace(asList(new WaitablePageClose(rejectIfClosed && isClosed), new WaitablePageCrash())); } - private class WaitablePageClose extends WaitableEvent { + private class WaitablePageClose extends WaitableEvent { private final boolean closedBefore; WaitablePageClose(boolean closedBefore) { - super(PageImpl.this.listeners, EventType.CLOSE); + super(PageImpl.this, Events.Page.CLOSE); this.closedBefore = closedBefore; } @@ -1530,9 +1504,9 @@ public T get() { } } - private class WaitablePageCrash extends WaitableEvent { + private class WaitablePageCrash extends WaitableEvent { WaitablePageCrash() { - super(PageImpl.this.listeners, EventType.CRASH); + super(PageImpl.this, Events.Page.CRASH); } @Override @@ -1571,7 +1545,7 @@ private Request waitForRequestImpl(Predicate predicate, WaitForRequestO if (options == null) { options = new WaitForRequestOptions(); } - return waitForEventWithTimeout(EventType.REQUEST, code, predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.REQUEST, code, predicate, options.timeout); } @Override @@ -1583,7 +1557,7 @@ private Request waitForRequestFinishedImpl(WaitForRequestFinishedOptions options if (options == null) { options = new WaitForRequestFinishedOptions(); } - return waitForEventWithTimeout(EventType.REQUESTFINISHED, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.REQUEST_FINISHED, code, options.predicate, options.timeout); } @Override @@ -1616,7 +1590,7 @@ private Response waitForResponseImpl(Predicate predicate, WaitForRespo if (options == null) { options = new WaitForResponseOptions(); } - return waitForEventWithTimeout(EventType.RESPONSE, code, predicate, options.timeout); + return waitForEventWithTimeout(Events.Page.RESPONSE, code, predicate, options.timeout); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WaitableEvent.java b/playwright/src/main/java/com/microsoft/playwright/impl/WaitableEvent.java index f9f63060f..99709bbd0 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WaitableEvent.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WaitableEvent.java @@ -19,21 +19,21 @@ import java.util.function.Consumer; import java.util.function.Predicate; -class WaitableEvent implements Waitable, Consumer { - final ListenerCollection listeners; - private final EventType type; +class WaitableEvent implements Waitable, Consumer { + final EventEmitter emitter; + private final String type; private final Predicate predicate; private T eventArg; - WaitableEvent(ListenerCollection listeners, EventType type) { - this(listeners, type, null); + WaitableEvent(EventEmitter emitter, String type) { + this(emitter, type, null); } - WaitableEvent(ListenerCollection listeners, EventType type, Predicate predicate) { - this.listeners = listeners; + WaitableEvent(EventEmitter emitter, String type, Predicate predicate) { + this.emitter = emitter; this.type = type; this.predicate = predicate; - listeners.add(type, this); + emitter.on(type, this); } @Override @@ -53,7 +53,7 @@ public boolean isDone() { @Override public void dispose() { - listeners.remove(type, this); + emitter.off(type, this); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java index 4edc44fa5..009f29f81 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java @@ -28,17 +28,9 @@ import java.util.function.Predicate; public class WebSocketImpl extends ChannelOwner implements WebSocket { - private final ListenerCollection listeners = new ListenerCollection<>(); private final PageImpl page; private boolean isClosed; - enum EventType { - CLOSE, - FRAMERECEIVED, - FRAMESENT, - SOCKETERROR, - } - final WebSocketChannel channel = new WebSocketChannel(this); WebSocketImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { @@ -48,42 +40,42 @@ enum EventType { @Override public void onClose(Consumer handler) { - listeners.add(EventType.CLOSE, handler); + on(Events.WebSocket.CLOSE, handler); } @Override public void offClose(Consumer handler) { - listeners.remove(EventType.CLOSE, handler); + off(Events.WebSocket.CLOSE, handler); } @Override public void onFrameReceived(Consumer handler) { - listeners.add(EventType.FRAMERECEIVED, handler); + on(Events.WebSocket.FRAME_RECEIVED, handler); } @Override public void offFrameReceived(Consumer handler) { - listeners.remove(EventType.FRAMERECEIVED, handler); + off(Events.WebSocket.FRAME_RECEIVED, handler); } @Override public void onFrameSent(Consumer handler) { - listeners.add(EventType.FRAMESENT, handler); + on(Events.WebSocket.FRAME_SENT, handler); } @Override public void offFrameSent(Consumer handler) { - listeners.remove(EventType.FRAMESENT, handler); + off(Events.WebSocket.FRAME_SENT, handler); } @Override public void onSocketError(Consumer handler) { - listeners.add(EventType.SOCKETERROR, handler); + on(Events.WebSocket.ERROR, handler); } @Override public void offSocketError(Consumer handler) { - listeners.remove(EventType.SOCKETERROR, handler); + off(Events.WebSocket.ERROR, handler); } @Override @@ -95,7 +87,7 @@ private WebSocketFrame waitForFrameReceivedImpl(WaitForFrameReceivedOptions opti if (options == null) { options = new WaitForFrameReceivedOptions(); } - return waitForEventWithTimeout(EventType.FRAMERECEIVED, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.WebSocket.FRAME_RECEIVED, code, options.predicate, options.timeout); } @Override @@ -107,7 +99,7 @@ private WebSocketFrame waitForFrameSentImpl(WaitForFrameSentOptions options, Run if (options == null) { options = new WaitForFrameSentOptions(); } - return waitForEventWithTimeout(EventType.FRAMESENT, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.WebSocket.FRAME_SENT, code, options.predicate, options.timeout); } @Override @@ -120,9 +112,9 @@ public String url() { return initializer.get("url").getAsString(); } - private class WaitableWebSocketClose extends WaitableEvent { + private class WaitableWebSocketClose extends WaitableEvent { WaitableWebSocketClose() { - super(WebSocketImpl.this.listeners, EventType.CLOSE); + super(WebSocketImpl.this, Events.WebSocket.CLOSE); } @Override @@ -131,9 +123,9 @@ public T get() { } } - private class WaitableWebSocketError extends WaitableEvent { + private class WaitableWebSocketError extends WaitableEvent { WaitableWebSocketError() { - super(WebSocketImpl.this.listeners, EventType.SOCKETERROR); + super(WebSocketImpl.this, Events.WebSocket.ERROR); } @Override @@ -142,9 +134,9 @@ public T get() { } } - private WebSocketFrame waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { + private WebSocketFrame waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); + waitables.add(new WaitableEvent<>(this, eventType, predicate)); waitables.add(new WaitableWebSocketClose<>()); waitables.add(new WaitableWebSocketError<>()); waitables.add(page.createWaitForCloseHelper()); @@ -162,7 +154,7 @@ void handleEvent(String event, JsonObject parameters) { } WebSocketFrameImpl WebSocketFrame = new WebSocketFrameImpl( parameters.get("data").getAsString(), opCode == 2); - listeners.notify(EventType.FRAMESENT, WebSocketFrame); + emit(Events.WebSocket.FRAME_SENT, WebSocketFrame); break; } case "frameReceived": { @@ -172,17 +164,17 @@ void handleEvent(String event, JsonObject parameters) { } WebSocketFrameImpl WebSocketFrame = new WebSocketFrameImpl( parameters.get("data").getAsString(), opCode == 2); - listeners.notify(EventType.FRAMERECEIVED, WebSocketFrame); + emit(Events.WebSocket.FRAME_RECEIVED, WebSocketFrame); break; } case "socketError": { String error = parameters.get("error").getAsString(); - listeners.notify(EventType.SOCKETERROR, error); + emit(Events.WebSocket.ERROR, error); break; } case "close": { isClosed = true; - listeners.notify(EventType.CLOSE, this); + emit(Events.WebSocket.CLOSE, this); break; } default: { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java index 4004f45b0..93c8ff12a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java @@ -32,14 +32,8 @@ import static com.microsoft.playwright.impl.Serialization.*; public class WorkerImpl extends ChannelOwner implements Worker { - final ListenerCollection listeners = new ListenerCollection<>(); PageImpl page; - enum EventType { - CLOSE, - CONSOLE, - } - final WorkerChannel channel = new WorkerChannel(this); WorkerImpl(ChannelOwner parent, String type, String guid, JsonObject initializer) { @@ -48,27 +42,27 @@ enum EventType { @Override public void onClose(Consumer handler) { - listeners.add(EventType.CLOSE, handler); + on(Events.Worker.CLOSE, handler); } @Override public void offClose(Consumer handler) { - listeners.remove(EventType.CLOSE, handler); + off(Events.Worker.CLOSE, handler); } @Override public void onConsole(Consumer handler) { - listeners.add(EventType.CONSOLE, handler); + on(Events.Worker.CONSOLE, handler); } @Override public void offConsole(Consumer handler) { - listeners.remove(EventType.CONSOLE, handler); + off(Events.Worker.CONSOLE, handler); } - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { + private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); + waitables.add(new WaitableEvent<>(this, eventType, predicate)); waitables.add(page.createWaitForCloseHelper()); waitables.add(page.createWaitableTimeout(timeout)); return runUntil(code, new WaitableRace<>(waitables)); @@ -88,14 +82,14 @@ private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions op if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(EventType.CONSOLE, code, options.predicate, options.timeout); + return waitForEventWithTimeout(Events.Worker.CONSOLE, code, options.predicate, options.timeout); } private Worker waitForCloseImpl(WaitForCloseOptions options, Runnable code) { if (options == null) { options = new WaitForCloseOptions(); } - return waitForEventWithTimeout(EventType.CLOSE, code, null, options.timeout); + return waitForEventWithTimeout(Events.Worker.CLOSE, code, null, options.timeout); } @Override @@ -125,7 +119,7 @@ protected void handleEvent(String event, JsonObject params) { if (page != null) { page.workers.remove(this); } - listeners.notify(EventType.CLOSE, this); + emit(Events.Worker.CLOSE, this); } } } From 80c825e735983af3929d778a2b3880d92367dcf1 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:24:36 -0800 Subject: [PATCH 06/14] fix(events): CDPSession.off calls the emitter --- .../main/java/com/microsoft/playwright/impl/CDPSessionImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java index 07ad4d812..2e785a0cc 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java @@ -82,7 +82,7 @@ public void on(String event, Consumer handler) { @Override @SuppressWarnings("rawtypes") public void off(String event, Consumer handler) { - off(event, handler); + super.off(event, handler); } @Override From 74bf5d25023aca84904a1f808fc61c56689329c4 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:35:58 -0800 Subject: [PATCH 07/14] refactor(timeouts): follow timeoutSettings.ts --- .../playwright/impl/BrowserTypeImpl.java | 6 +- .../playwright/impl/TimeoutSettings.java | 60 +++++++++++-------- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java index 3b6c529d2..e52831a2f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -51,7 +51,7 @@ public BrowserImpl launch(LaunchOptions options) { options = new LaunchOptions(); } BrowserTypeLaunchParams params = toProtocol(options, BrowserTypeLaunchParams.class); - BrowserImpl browser = channel.launch(params, TimeoutSettings.launchTimeout(options.timeout)).browser; + BrowserImpl browser = channel.launch(params, new TimeoutSettings().launchTimeout(options.timeout)).browser; browser.browserType = this; browser.launchOptions = options; return browser; @@ -124,7 +124,7 @@ public Browser connectOverCDP(String endpointURL, ConnectOverCDPOptions options) BrowserTypeConnectOverCDPParams params = toProtocol(options, BrowserTypeConnectOverCDPParams.class); params.endpointURL = endpointURL; - BrowserImpl browser = channel.connectOverCDP(params, TimeoutSettings.launchTimeout(options.timeout)).browser; + BrowserImpl browser = channel.connectOverCDP(params, new TimeoutSettings().launchTimeout(options.timeout)).browser; browser.connectToBrowserType(this, null); return browser; } @@ -206,7 +206,7 @@ public BrowserContextImpl launchPersistentContext(Path userDataDir, LaunchPersis params.acceptDownloads = options.acceptDownloads == null ? null : (options.acceptDownloads ? "accept" : "deny"); params.selectorEngines = new ArrayList<>(playwright.selectors.selectorEngines); params.testIdAttributeName = playwright.selectors.testIdAttributeName; - BrowserTypeLaunchPersistentContextResult result = channel.launchPersistentContext(params, TimeoutSettings.launchTimeout(options.timeout)); + BrowserTypeLaunchPersistentContextResult result = channel.launchPersistentContext(params, new TimeoutSettings().launchTimeout(options.timeout)); BrowserImpl browser = result.browser; browser.connectToBrowserType(this, options.tracesDir); BrowserContextImpl context = result.context; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java index 099e2d703..06e840a70 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/TimeoutSettings.java @@ -16,28 +16,24 @@ package com.microsoft.playwright.impl; +// Port of timeoutSettings.ts. java: no AbortSignal and no PWDEBUG=inspector branch, a timeout is a Double +// and 0 means no deadline. class TimeoutSettings { - private static final int DEFAULT_TIMEOUT_MS = 30_000; - private static final int DEFAULT_LAUNCH_TIMEOUT_MS = 180_000; + static final int DEFAULT_TIMEOUT = 30_000; + static final int DEFAULT_LAUNCH_TIMEOUT = 180_000; private final TimeoutSettings parent; - private Double defaultTimeout ; + private Double defaultTimeout; private Double defaultNavigationTimeout; TimeoutSettings() { this(null); } + TimeoutSettings(TimeoutSettings parent) { this.parent = parent; } - Double defaultTimeout() { - return defaultTimeout; - } - Double defaultNavigationTimeout() { - return defaultNavigationTimeout; - } - void setDefaultTimeout(Double timeout) { defaultTimeout = timeout; } @@ -46,46 +42,58 @@ void setDefaultNavigationTimeout(Double timeout) { defaultNavigationTimeout = timeout; } - double timeout(Double timeout) { + Double defaultNavigationTimeout() { + return defaultNavigationTimeout; + } + + Double defaultTimeout() { + return defaultTimeout; + } + + double navigationTimeout(Double timeout) { if (timeout != null) { return timeout; } + if (defaultNavigationTimeout != null) { + return defaultNavigationTimeout; + } if (defaultTimeout != null) { return defaultTimeout; } if (parent != null) { - return parent.timeout(timeout); + return parent.navigationTimeout(timeout); } - return DEFAULT_TIMEOUT_MS; + return DEFAULT_TIMEOUT; } - double navigationTimeout(Double timeout) { + double timeout(Double timeout) { if (timeout != null) { return timeout; } - if (defaultNavigationTimeout != null) { - return defaultNavigationTimeout; - } if (defaultTimeout != null) { return defaultTimeout; } if (parent != null) { - return parent.navigationTimeout(timeout); + return parent.timeout(timeout); } - return DEFAULT_TIMEOUT_MS; + return DEFAULT_TIMEOUT; } + double launchTimeout(Double timeout) { + if (timeout != null) { + return timeout; + } + if (parent != null) { + return parent.launchTimeout(timeout); + } + return DEFAULT_LAUNCH_TIMEOUT; + } + + // java: removed once every wait goes through Waiter. Waitable createWaitable(Double timeout) { if (timeout != null && timeout == 0) { return new WaitableNever<>(); } return new WaitableTimeout<>(timeout(timeout)); } - - static double launchTimeout(Double timeout) { - if (timeout != null) { - return timeout; - } - return DEFAULT_LAUNCH_TIMEOUT_MS; - } } From 969cdfe491bb4af5e9984286b02a79935d372886 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:38:07 -0800 Subject: [PATCH 08/14] refactor(waiter): port waiter.ts --- .../playwright/impl/ChannelOwner.java | 2 +- .../com/microsoft/playwright/impl/Waiter.java | 249 ++++++++++++++++++ 2 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index 4e3321521..1d1fef0e7 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -300,7 +300,7 @@ JsonObject toProtocolRef() { } class ApiZone { - final String title; + String title; final boolean internal; boolean reported; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java new file mode 100644 index 000000000..c2e06bac2 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) Microsoft Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.microsoft.playwright.impl; + +import com.google.gson.JsonObject; +import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.TimeoutError; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Predicate; +import java.util.function.Supplier; + +import static com.microsoft.playwright.impl.Utils.createGuid; + +// Port of waiter.ts. java: promises are Waitables, the API thread pumps the connection in waitForPromise(), +// there are no zones to save and no AbortSignal. +class Waiter { + private final List dispose = new ArrayList<>(); + private final List> failures = new ArrayList<>(); + private RuntimeException immediateError; + private final List logs = new ArrayList<>(); + private final ChannelOwner channelOwner; + private final String waitId; + private String error; + private boolean disposed; + + Waiter(ChannelOwner channelOwner, String event) { + this.waitId = createGuid(); + this.channelOwner = channelOwner; + + String title = "Wait for event \"" + event + "\""; + JsonObject info = new JsonObject(); + info.addProperty("waitId", waitId); + info.addProperty("phase", "before"); + info.addProperty("event", event); + sendWaitInfo(info, title, false); + dispose.add(() -> { + JsonObject after = new JsonObject(); + after.addProperty("waitId", waitId); + after.addProperty("phase", "after"); + if (error != null) { + after.addProperty("error", error); + } + sendWaitInfo(after, null, true); + }); + } + + static Waiter createForEvent(ChannelOwner channelOwner, String event) { + return new Waiter(channelOwner, event); + } + + private void sendWaitInfo(JsonObject info, String title, boolean internal) { + // Fire-and-forget: server intentionally never replies, and we never throw to the caller. + try { + channelOwner.wrapApiCall(() -> { + ApiZone apiZone = channelOwner.connection.apiZone; + if (!apiZone.internal && !apiZone.reported && apiZone.title == null) { + // An outer wrapApiCall may have set its own title (e.g. "Wait for navigation"); + // fall back to ours only when the outer zone left it blank. + apiZone.title = title; + } + // sendMessageNoReply reports the call when it is the first message of the zone and sends it + // as internal otherwise. + channelOwner.sendMessageNoReply("__waitInfo__", info); + }, title, internal); + } catch (RuntimeException e) { + // Fire-and-forget: never throw to the caller. + } + } + + Waitable waitForEvent(EventEmitter emitter, String event, Predicate predicate) { + return new WaitableEvent<>(emitter, event, predicate); + } + + void rejectOnEvent(EventEmitter emitter, String event, Supplier error) { + rejectOnEvent(emitter, event, error, null); + } + + void rejectOnEvent(EventEmitter emitter, String event, Supplier error, Predicate predicate) { + rejectOn(new WaitableEvent(emitter, event, predicate) { + @Override + public T get() { + throw error.get(); + } + }); + } + + void rejectOnTimeout(Double timeout, String timeoutMessage) { + if (timeout != null && timeout != 0) { + rejectOn(new WaitableTimeout(timeout) { + @Override + public Object get() { + throw new TimeoutError(timeoutMessage); + } + }); + } + } + + void rejectImmediately(RuntimeException error) { + immediateError = error; + } + + void throwIfImmediatelyRejected() { + if (immediateError != null) { + throw immediateError; + } + } + + void dispose() { + // java: the "after" message goes out once, a failed wait disposes the waiter and the caller does it again. + if (disposed) { + return; + } + disposed = true; + for (Runnable d : dispose) { + d.run(); + } + } + + T waitForPromise(Waitable waitable) { + return waitForPromise(waitable, null); + } + + @SuppressWarnings("unchecked") + private T waitForPromise(Waitable waitable, Runnable code) { + if (code != null) { + try { + code.run(); + } catch (RuntimeException e) { + // java: the callback is the caller's own code, its exception is not a failure of the wait. + waitable.dispose(); + error = e.getMessage(); + dispose(); + throw e; + } + } + try { + throwIfImmediatelyRejected(); + List> race = new ArrayList<>(); + race.add(waitable); + for (Waitable failure : failures) { + // The failures stay armed for the next waitForPromise(), only dispose() releases them. + race.add(new Undisposable<>((Waitable) failure)); + } + // The waitable is disposed by runUntil in any case, as the dispose() argument of waitForPromise upstream. + return channelOwner.runUntil(() -> {}, new WaitableRace<>(race)); + } catch (RuntimeException e) { + waitable.dispose(); + error = e.getMessage(); + dispose(); + throw rewriteErrorMessage(e); + } + } + + void log(String s) { + logs.add(s); + LoggingSupport.logApiIfEnabled(s); + JsonObject info = new JsonObject(); + info.addProperty("waitId", waitId); + info.addProperty("phase", "log"); + info.addProperty("message", s); + sendWaitInfo(info, null, true); + } + + private void rejectOn(Waitable failure) { + failures.add(failure); + dispose.add(failure::dispose); + } + + // java: exceptions are immutable, so a new one of the same class carries the message with the logs. + private RuntimeException rewriteErrorMessage(RuntimeException e) { + String recording = formatLogRecording(logs); + if (recording.isEmpty()) { + return e; + } + String message = e.getMessage() + recording; + if (e instanceof TimeoutError) { + return new TimeoutError(message, e); + } + if (e instanceof TargetClosedError) { + return new TargetClosedError(message, e); + } + if (e.getClass() == PlaywrightException.class) { + return new PlaywrightException(message, e); + } + return e; + } + + static String formatLogRecording(List log) { + if (log.isEmpty()) { + return ""; + } + String header = " logs "; + int headerLength = 60; + int leftLength = (headerLength - header.length()) / 2; + int rightLength = headerLength - header.length() - leftLength; + return "\n" + repeat('=', leftLength) + header + repeat('=', rightLength) + "\n" + String.join("\n", log) + "\n" + repeat('=', headerLength); + } + + private static String repeat(char c, int n) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < n; i++) { + sb.append(c); + } + return sb.toString(); + } + + private static class Undisposable implements Waitable { + private final Waitable delegate; + + Undisposable(Waitable delegate) { + this.delegate = delegate; + } + + @Override + public boolean isDone() { + return delegate.isDone(); + } + + @Override + public T get() { + return delegate.get(); + } + + @Override + public void dispose() { + } + } + + // java: the callback-style API. Subscribes first, then runs the code, then waits. + T waitForEvent(EventEmitter emitter, String event, Predicate predicate, Runnable code) { + return waitForPromise(waitForEvent(emitter, event, predicate), code); + } +} From 4b647f10a62e5c8aa2ceb3d661b22edf73e4a8ab Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:41:08 -0800 Subject: [PATCH 09/14] refactor(waits): use Waiter like the Node.js client --- .../playwright/impl/BrowserContextImpl.java | 33 ++- .../playwright/impl/ChannelOwner.java | 13 - .../microsoft/playwright/impl/FrameImpl.java | 245 +++++++----------- .../com/microsoft/playwright/impl/Logger.java | 21 -- .../microsoft/playwright/impl/PageImpl.java | 172 +++--------- .../playwright/impl/WaitForEventLogger.java | 88 ------- .../com/microsoft/playwright/impl/Waiter.java | 8 + .../playwright/impl/WebSocketImpl.java | 53 ++-- .../microsoft/playwright/impl/WorkerImpl.java | 41 +-- 9 files changed, 197 insertions(+), 477 deletions(-) delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/Logger.java delete mode 100644 playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java index 2520b26a3..854213eb5 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserContextImpl.java @@ -315,24 +315,25 @@ public Credentials credentials() { return credentials; } - private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(this, eventType, predicate)); - waitables.add(new WaitableContextClose<>()); - waitables.add(timeoutSettings.createWaitable(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); - } - @Override public Page waitForPage(WaitForPageOptions options, Runnable code) { - return withWaitLogging("BrowserContext.waitForPage", "page", logger -> waitForPageImpl(options, code)); - } - - private Page waitForPageImpl(WaitForPageOptions options, Runnable code) { if (options == null) { options = new WaitForPageOptions(); } - return waitForEventWithTimeout(Events.BrowserContext.PAGE, code, options.predicate, options.timeout); + return waitForEvent(Events.BrowserContext.PAGE, options.predicate, options.timeout, code); + } + + // waitForEvent in browserContext.ts + private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { + double timeoutMs = timeoutSettings.timeout(timeout); + Waiter waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.BrowserContext.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.BrowserContext.CLOSE, () -> new TargetClosedError(effectiveCloseReason())); + } + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } @Override @@ -683,14 +684,10 @@ public void waitForCondition(BooleanSupplier predicate, WaitForConditionOptions @Override public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - return withWaitLogging("BrowserContext.waitForConsoleMessage", "console", logger -> waitForConsoleMessageImpl(options, code)); - } - - private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions options, Runnable code) { if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(Events.BrowserContext.CONSOLE, code, options.predicate, options.timeout); + return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, code); } private class WaitableContextClose extends WaitableEvent { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index 1d1fef0e7..29f8fe24a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -194,19 +194,6 @@ T withTitle(String title, Supplier code) { return wrapApiCall(code, title, false); } - T withWaitLogging(String apiName, Function code) { - return new WaitForEventLogger<>(this, apiName, null, null, code).get(); - } - - /** A wait for the event, titled {@code Wait for event ""} in the trace like the Node.js client's waitForEvent. */ - T withWaitLogging(String apiName, String event, Function code) { - return new WaitForEventLogger<>(this, apiName, event, "Wait for event \"" + event + "\"", code).get(); - } - - T withWaitLoggingTitled(String apiName, String title, Function code) { - return new WaitForEventLogger<>(this, apiName, null, title, code).get(); - } - // java: the sendMessage family is the typed channel proxy of upstream's createChannel(). WaitableResult sendMessageAsync(String method) { return sendMessageAsync(method, new JsonObject()); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java index b8ba9151a..c490036ef 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/FrameImpl.java @@ -820,166 +820,115 @@ public JSHandle waitForFunction(String pageFunction, Object arg, WaitForFunction return channel.waitForFunction(params, timeout(options.timeout)).handle; } - @Override - public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { - withWaitLogging("Frame.waitForLoadState", logger -> { - waitForLoadStateImpl(state, options, logger); - return null; - }); - } - - void waitForLoadStateImpl(LoadState state, WaitForLoadStateOptions options, Logger logger) { - waitForLoadStateImpl(convertType(state, WaitUntilState.class), options, logger); + private Waiter setupNavigationWaiter(Double timeout) { + Waiter waiter = new Waiter(page, ""); + if (page.isClosed()) { + waiter.rejectImmediately(page.closeErrorWithReason()); + } + waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); + waiter.rejectOnEvent(page, Events.Page.CRASH, () -> new PlaywrightException("Navigation failed because page crashed!")); + waiter.rejectOnEvent(page, Events.Page.FRAME_DETACHED, () -> new PlaywrightException("Navigating frame was detached!"), frame -> frame == this); + double timeoutMs = page.timeoutSettings.navigationTimeout(timeout); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded."); + return waiter; } - private void waitForLoadStateImpl(WaitUntilState state, WaitForLoadStateOptions options, Logger logger) { + @Override + public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) { if (options == null) { - options = new WaitForLoadStateOptions(); - } - if (state == null) { - state = LOAD; + options = new WaitForNavigationOptions(); } - - List> waitables = new ArrayList<>(); - waitables.add(page.createWaitForCloseHelper(true)); - waitables.add(new WaitForLoadStateHelper(state, logger)); - waitables.add(page.createWaitableTimeout(options.timeout)); - runUntil(() -> {}, new WaitableRace<>(waitables)); + UrlMatcher matcher = UrlMatcher.forOneOf(page.context().baseUrl(), options.url, this.connection.localUtils(), false); + return waitForNavigation(matcher, options.url instanceof String ? (String) options.url : null, options.waitUntil, options.timeout, code); } - private class WaitForLoadStateHelper implements Waitable, Consumer { - private final WaitUntilState expectedState; - private final Logger logger; - private boolean isDone; - - WaitForLoadStateHelper(WaitUntilState state, Logger logger) { - expectedState = state; - this.logger = logger; - isDone = loadStates.contains(state); - if (!isDone) { - on(Events.Frame.LOAD_STATE, this); - } + private Response waitForNavigation(UrlMatcher matcher, String url, WaitUntilState waitUntil, Double timeout, Runnable code) { + if (waitUntil == null) { + waitUntil = LOAD; } + final WaitUntilState expectedState = waitUntil; + // java: the code runs outside of the api zone, so that its calls are not hidden as internal. + Waiter waiter = withTitle("Wait for navigation", () -> setupNavigationWaiter(timeout)); - @Override - public void accept(WaitUntilState state) { - logger.log(" load state changed to " + state); - if (expectedState.equals(state)) { - isDone = true; - dispose(); - } - } - - public void dispose() { - off(Events.Frame.LOAD_STATE, this); - } - - public boolean isDone() { - return isDone; - } - - @Override - public Void get() { - return null; - } - } - - private class WaitForNavigationHelper implements Waitable, Consumer { - private final UrlMatcher matcher; - private final WaitUntilState expectedLoadState; - private final Logger logger; - private WaitForLoadStateHelper loadStateHelper; - - private RequestImpl request; - private RuntimeException exception; - - WaitForNavigationHelper(UrlMatcher matcher, WaitUntilState expectedLoadState, Logger logger) { - this.matcher = matcher; - this.expectedLoadState = expectedLoadState; - this.logger = logger; - on(Events.Frame.NAVIGATED, this); - } + String toUrl = url != null ? " to \"" + url + "\"" : ""; + waiter.log("waiting for navigation" + toUrl + " until \"" + loadStateName(waitUntil) + "\""); - @Override - public void accept(JsonObject params) { - String url = params.get("url").getAsString(); - logger.log(" navigated to " + url); - if (!matcher.test(url)) { - return; - } - if (params.has("error")) { - exception = new PlaywrightException(params.get("error").getAsString()); - } else { - if (params.has("newDocument")) { - JsonObject jsonReq = params.getAsJsonObject("newDocument").getAsJsonObject("request"); - if (jsonReq != null) { - request = connection.getExistingObject(jsonReq.get("guid").getAsString()); - } - } - loadStateHelper = new WaitForLoadStateHelper(expectedLoadState, logger); - } - off(Events.Frame.NAVIGATED, this); - } - - @Override - public void dispose() { - off(Events.Frame.NAVIGATED, this); - if (loadStateHelper != null) { - loadStateHelper.dispose(); - } - } - - @Override - public boolean isDone() { - if (exception != null) { + JsonObject navigatedEvent = waiter.waitForEvent(this, Events.Frame.NAVIGATED, event -> { + // Any failed navigation results in a rejection. + if (event.has("error")) { return true; } - if (loadStateHelper != null) { - return loadStateHelper.isDone(); + String eventUrl = event.get("url").getAsString(); + waiter.log(" navigated to \"" + eventUrl + "\""); + return matcher.test(eventUrl); + }, code); + if (navigatedEvent.has("error")) { + WaitableResult failure = new WaitableResult<>(); + failure.completeExceptionally(new PlaywrightException(navigatedEvent.get("error").getAsString())); + waiter.waitForPromise(failure); + } + + if (!loadStates.contains(expectedState)) { + waiter.waitForPromise(waiter.waitForEvent(this, Events.Frame.LOAD_STATE, s -> { + waiter.log(" \"" + loadStateName(s) + "\" event fired"); + return s == expectedState; + })); + } + + RequestImpl request = null; + if (navigatedEvent.has("newDocument")) { + JsonObject jsonReq = navigatedEvent.getAsJsonObject("newDocument").getAsJsonObject("request"); + if (jsonReq != null) { + request = connection.getExistingObject(jsonReq.get("guid").getAsString()); } - return false; } - - @Override - public Response get() { - if (exception != null) { - throw exception; - } - - if (request == null) { - return null; + Response response = null; + if (request != null) { + WaitableResult result = new WaitableResult<>(); + try { + result.complete(request.finalRequest().response()); + } catch (RuntimeException e) { + result.completeExceptionally(e); } - return request.finalRequest().response(); + response = waiter.waitForPromise(result); } + waiter.dispose(); + return response; } @Override - public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) { - return withWaitLoggingTitled("Frame.waitForNavigation", "Wait for navigation", logger -> waitForNavigationImpl(logger, code, options, null)); - } - - Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options) { - return waitForNavigationImpl(logger, code, options, null); + public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { + if (state == null) { + state = LoadState.LOAD; + } + waitForLoadState(convertType(state, WaitUntilState.class), options == null ? null : options.timeout); } - private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options, UrlMatcher matcher) { - if (options == null) { - options = new WaitForNavigationOptions(); - } - if (options.waitUntil == null) { - options.waitUntil = WaitUntilState.LOAD; + private void waitForLoadState(WaitUntilState state, Double timeout) { + if (state == null) { + state = LOAD; } + final WaitUntilState expectedState = state; + withTitle("Wait for load state \"" + loadStateName(state) + "\"", () -> { + Waiter waiter = setupNavigationWaiter(timeout); + try { + if (loadStates.contains(expectedState)) { + waiter.log(" not waiting, \"" + loadStateName(expectedState) + "\" event already fired"); + waiter.throwIfImmediatelyRejected(); + } else { + waiter.waitForPromise(waiter.waitForEvent(this, Events.Frame.LOAD_STATE, s -> { + waiter.log(" \"" + loadStateName(s) + "\" event fired"); + return s == expectedState; + })); + } + } finally { + waiter.dispose(); + } + }); + } - List> waitables = new ArrayList<>(); - if (matcher == null) { - matcher = UrlMatcher.forOneOf(page.context().baseUrl(), options.url, this.connection.localUtils(), false); - } - logger.log("waiting for navigation " + matcher); - waitables.add(new WaitForNavigationHelper(matcher, options.waitUntil, logger)); - waitables.add(page.createWaitForCloseHelper(true)); - waitables.add(page.createWaitableFrameDetach(this)); - waitables.add(page.createWaitableNavigationTimeout(options.timeout)); - return runUntil(code, new WaitableRace<>(waitables)); + private static String loadStateName(WaitUntilState state) { + return state.name().toLowerCase(); } @Override @@ -1006,36 +955,28 @@ public void waitForTimeout(double timeout) { @Override public void waitForURL(String url, WaitForURLOptions options) { - waitForURL(UrlMatcher.forGlob(page.context().baseUrl(), url, this.connection.localUtils(), false), options); + waitForURL(UrlMatcher.forGlob(page.context().baseUrl(), url, this.connection.localUtils(), false), url, options); } @Override public void waitForURL(Pattern url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), options); + waitForURL(new UrlMatcher(url), null, options); } @Override public void waitForURL(Predicate url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), options); - } - - private void waitForURL(UrlMatcher matcher, WaitForURLOptions options) { - withWaitLogging("Frame.waitForURL", logger -> { - waitForURLImpl(logger, matcher, options); - return null; - }); + waitForURL(new UrlMatcher(url), null, options); } - void waitForURLImpl(Logger logger, UrlMatcher matcher, WaitForURLOptions options) { - logger.log("waiting for url " + matcher); + private void waitForURL(UrlMatcher matcher, String url, WaitForURLOptions options) { if (options == null) { options = new WaitForURLOptions(); } if (matcher.test(url())) { - waitForLoadStateImpl(options.waitUntil, convertType(options, WaitForLoadStateOptions.class), logger); + waitForLoadState(options.waitUntil, options.timeout); return; } - waitForNavigationImpl(logger, () -> {}, convertType(options, WaitForNavigationOptions.class), matcher); + waitForNavigation(matcher, url, options.waitUntil, options.timeout, () -> {}); } int queryCount(String selector) { diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Logger.java b/playwright/src/main/java/com/microsoft/playwright/impl/Logger.java deleted file mode 100644 index 2441ed984..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Logger.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -interface Logger { - void log(String message); -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index 1fae316f2..611976d4d 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -247,6 +247,10 @@ private String effectiveCloseReason() { return browserContext.effectiveCloseReason(); } + TargetClosedError closeErrorWithReason() { + return new TargetClosedError(effectiveCloseReason()); + } + @Override public void onClose(Consumer handler) { on(Events.Page.CLOSE, handler); @@ -454,95 +458,78 @@ public ClockImpl clock() { @Override public Page waitForClose(WaitForCloseOptions options, Runnable code) { - return withWaitLogging("Page.waitForClose", "close", logger -> waitForCloseImpl(options, code)); - } - - private Page waitForCloseImpl(WaitForCloseOptions options, Runnable code) { if (options == null) { options = new WaitForCloseOptions(); } - return waitForEventWithTimeout(Events.Page.CLOSE, code, null, options.timeout); + return waitForEvent(Events.Page.CLOSE, null, options.timeout, "waiting for event \"close\"", code); } @Override public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - return withWaitLogging("Page.waitForConsoleMessage", "console", logger -> waitForConsoleMessageImpl(options, code)); - } - - private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions options, Runnable code) { if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(Events.Page.CONSOLE, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.CONSOLE, options.predicate, options.timeout, "waiting for event \"console\"", code); } @Override public Download waitForDownload(WaitForDownloadOptions options, Runnable code) { - return withWaitLogging("Page.waitForDownload", "download", logger -> waitForDownloadImpl(options, code)); - } - - private Download waitForDownloadImpl(WaitForDownloadOptions options, Runnable code) { if (options == null) { options = new WaitForDownloadOptions(); } - return waitForEventWithTimeout(Events.Page.DOWNLOAD, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.DOWNLOAD, options.predicate, options.timeout, "waiting for event \"download\"", code); } @Override public FileChooser waitForFileChooser(WaitForFileChooserOptions options, Runnable code) { - return withWaitLogging("Page.waitForFileChooser", "filechooser", logger -> waitForFileChooserImpl(options, code)); - } - - private FileChooser waitForFileChooserImpl(WaitForFileChooserOptions options, Runnable code) { // TODO: enable/disable file chooser interception if (options == null) { options = new WaitForFileChooserOptions(); } - return waitForEventWithTimeout(Events.Page.FILE_CHOOSER, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.FILE_CHOOSER, options.predicate, options.timeout, "waiting for event \"filechooser\"", code); } @Override public Page waitForPopup(WaitForPopupOptions options, Runnable code) { - return withWaitLogging("Page.waitForPopup", "popup", logger -> waitForPopupImpl(options, code)); - } - - private Page waitForPopupImpl(WaitForPopupOptions options, Runnable code) { if (options == null) { options = new WaitForPopupOptions(); } - return waitForEventWithTimeout(Events.Page.POPUP, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.POPUP, options.predicate, options.timeout, "waiting for event \"popup\"", code); } @Override public WebSocket waitForWebSocket(WaitForWebSocketOptions options, Runnable code) { - return withWaitLogging("Page.waitForWebSocket", "websocket", logger -> waitForWebSocketImpl(options, code)); - } - - private WebSocket waitForWebSocketImpl(WaitForWebSocketOptions options, Runnable code) { if (options == null) { options = new WaitForWebSocketOptions(); } - return waitForEventWithTimeout(Events.Page.WEB_SOCKET, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.WEB_SOCKET, options.predicate, options.timeout, "waiting for event \"websocket\"", code); } @Override public Worker waitForWorker(WaitForWorkerOptions options, Runnable code) { - return withWaitLogging("Page.waitForWorker", "worker", logger -> waitForWorkerImpl(options, code)); - } - - private Worker waitForWorkerImpl(WaitForWorkerOptions options, Runnable code) { if (options == null) { options = new WaitForWorkerOptions(); } - return waitForEventWithTimeout(Events.Page.WORKER, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, "waiting for event \"worker\"", code); } - private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(this, eventType, predicate)); - waitables.add(createWaitForCloseHelper()); - waitables.add(createWaitableTimeout(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); + // _waitForEvent in page.ts + private T waitForEvent(String event, Predicate predicate, Double timeout, String logLine, Runnable code) { + double timeoutMs = timeoutSettings.timeout(timeout); + Waiter waiter = Waiter.createForEvent(this, event); + if (logLine != null) { + waiter.log(logLine); + } + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.Page.CRASH.equals(event)) { + waiter.rejectOnEvent(this, Events.Page.CRASH, () -> new PlaywrightException("Page crashed")); + } + if (!Events.Page.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.Page.CLOSE, () -> closeErrorWithReason()); + } + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } @Override @@ -1415,10 +1402,6 @@ public ViewportSize viewportSize() { return viewport; } - Waitable createWaitableNavigationTimeout(Double timeout) { - return new WaitableTimeout<>(timeoutSettings.navigationTimeout(timeout)); - } - Waitable createWaitableTimeout(Double timeout) { return timeoutSettings.createWaitable(timeout); } @@ -1430,28 +1413,18 @@ public JSHandle waitForFunction(String pageFunction, Object arg, WaitForFunction @Override public void waitForLoadState(LoadState state, WaitForLoadStateOptions options) { - final LoadState loadState = state == null ? LoadState.LOAD : state; - withTitle("Wait for load state \"" + loadState.toString().toLowerCase() + "\"", () -> { - withWaitLogging("Page.waitForLoadState", logger -> { - mainFrame.waitForLoadStateImpl(loadState, convertType(options, Frame.WaitForLoadStateOptions.class), logger); - return null; - }); - }); + mainFrame.waitForLoadState(state, convertType(options, Frame.WaitForLoadStateOptions.class)); } @Override public Response waitForNavigation(WaitForNavigationOptions options, Runnable code) { - return withWaitLoggingTitled("Page.waitForNavigation", "Wait for navigation", logger -> waitForNavigationImpl(logger, code, options)); - } - - private Response waitForNavigationImpl(Logger logger, Runnable code, WaitForNavigationOptions options) { Frame.WaitForNavigationOptions frameOptions = new Frame.WaitForNavigationOptions(); if (options != null) { frameOptions.timeout = options.timeout; frameOptions.waitUntil = options.waitUntil; frameOptions.url = options.url; } - return mainFrame.waitForNavigationImpl(logger, code, frameOptions); + return mainFrame.waitForNavigation(frameOptions, code); } void frameNavigated(FrameImpl frame) { @@ -1459,48 +1432,18 @@ void frameNavigated(FrameImpl frame) { browserContext.notifyFrameNavigated(frame); } - private class WaitableFrameDetach extends WaitableEvent { - WaitableFrameDetach(Frame frameArg) { - super(PageImpl.this, Events.Page.FRAME_DETACHED, detachedFrame -> frameArg.equals(detachedFrame)); - } - - @Override - public Frame get() { - throw new PlaywrightException("Navigating frame was detached"); - } - } - - @SuppressWarnings("unchecked") - Waitable createWaitableFrameDetach(Frame frame) { - // It is safe to cast as WaitableFrameDetach.get() always throws. - return (Waitable) new WaitableFrameDetach(frame); - } - Waitable createWaitForCloseHelper() { - return createWaitForCloseHelper(false); - } - - /** With {@code rejectIfClosed}, it is done at once when the page is already closed, like the navigation waiter of the Node.js client. */ - Waitable createWaitForCloseHelper(boolean rejectIfClosed) { - return new WaitableRace(asList(new WaitablePageClose(rejectIfClosed && isClosed), new WaitablePageCrash())); + return new WaitableRace(asList(new WaitablePageClose(), new WaitablePageCrash())); } private class WaitablePageClose extends WaitableEvent { - private final boolean closedBefore; - - WaitablePageClose(boolean closedBefore) { + WaitablePageClose() { super(PageImpl.this, Events.Page.CLOSE); - this.closedBefore = closedBefore; - } - - @Override - public boolean isDone() { - return closedBefore || super.isDone(); } @Override public T get() { - throw new TargetClosedError(effectiveCloseReason()); + throw closeErrorWithReason(); } } @@ -1531,33 +1474,20 @@ public Request waitForRequest(Predicate predicate, WaitForRequestOption } private Request waitForRequest(UrlMatcher urlMatcher, Predicate predicate, WaitForRequestOptions options, Runnable code) { - return withWaitLogging("Page.waitForRequest", "request", logger -> { - logger.log("waiting for request " + ((urlMatcher == null) ? "matching predicate" : urlMatcher.toString())); - Predicate requestPredicate = predicate; - if (requestPredicate == null) { - requestPredicate = request -> urlMatcher.test(request.url());; - } - return waitForRequestImpl(requestPredicate, options, code); - }); - } - - private Request waitForRequestImpl(Predicate predicate, WaitForRequestOptions options, Runnable code) { if (options == null) { options = new WaitForRequestOptions(); } - return waitForEventWithTimeout(Events.Page.REQUEST, code, predicate, options.timeout); + Predicate requestPredicate = predicate != null ? predicate : request -> urlMatcher.test(request.url()); + String logLine = urlMatcher == null ? null : "waiting for request " + urlMatcher; + return waitForEvent(Events.Page.REQUEST, requestPredicate, options.timeout, logLine, code); } @Override public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Runnable code) { - return withWaitLogging("Page.waitForRequestFinished", "requestfinished", logger -> waitForRequestFinishedImpl(options, code)); - } - - private Request waitForRequestFinishedImpl(WaitForRequestFinishedOptions options, Runnable code) { if (options == null) { options = new WaitForRequestFinishedOptions(); } - return waitForEventWithTimeout(Events.Page.REQUEST_FINISHED, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.REQUEST_FINISHED, options.predicate, options.timeout, "waiting for event \"requestfinished\"", code); } @Override @@ -1576,21 +1506,12 @@ public Response waitForResponse(Predicate predicate, WaitForResponseOp } private Response waitForResponse(UrlMatcher urlMatcher, Predicate predicate, WaitForResponseOptions options, Runnable code) { - return withWaitLogging("Page.waitForResponse", "response", logger -> { - logger.log("waiting for response " + ((urlMatcher == null) ? "matching predicate" : urlMatcher.toString())); - Predicate responsePredicate = predicate; - if (responsePredicate == null) { - responsePredicate = response -> urlMatcher.test(response.url());; - } - return waitForResponseImpl(responsePredicate, options, code); - }); - } - - private Response waitForResponseImpl(Predicate predicate, WaitForResponseOptions options, Runnable code) { if (options == null) { options = new WaitForResponseOptions(); } - return waitForEventWithTimeout(Events.Page.RESPONSE, code, predicate, options.timeout); + Predicate responsePredicate = predicate != null ? predicate : response -> urlMatcher.test(response.url()); + String logLine = urlMatcher == null ? null : "waiting for response " + urlMatcher; + return waitForEvent(Events.Page.RESPONSE, responsePredicate, options.timeout, logLine, code); } @Override @@ -1614,24 +1535,17 @@ public void waitForTimeout(double timeout) { @Override public void waitForURL(String url, WaitForURLOptions options) { - waitForURL(UrlMatcher.forGlob(browserContext.baseUrl(), url, this.connection.localUtils(), false), options); + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override public void waitForURL(Pattern url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), options); + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override public void waitForURL(Predicate url, WaitForURLOptions options) { - waitForURL(new UrlMatcher(url), options); - } - - private void waitForURL(UrlMatcher matcher, WaitForURLOptions options) { - withWaitLogging("Page.waitForURL", logger -> { - mainFrame.waitForURLImpl(logger, matcher, convertType(options, Frame.WaitForURLOptions.class)); - return null; - }); + mainFrame.waitForURL(url, convertType(options, Frame.WaitForURLOptions.class)); } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java b/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java deleted file mode 100644 index 63c394c94..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.microsoft.playwright.impl; - -import com.google.gson.JsonObject; - -import java.util.function.Function; -import java.util.function.Supplier; - -import static com.microsoft.playwright.impl.Utils.createGuid; - -public class WaitForEventLogger implements Supplier, Logger { - private final Function supplier; - private final ChannelOwner channel; - private final String waitId; - private final String apiName; - private final String event; - private final String title; - - WaitForEventLogger(ChannelOwner channelOwner, String apiName, String event, String title, Function supplier) { - this.supplier = supplier; - this.channel = channelOwner; - this.apiName = apiName; - this.event = event; - this.title = title; - this.waitId = createGuid(); - } - - @Override - public T get() { - { - JsonObject info = new JsonObject(); - info.addProperty("phase", "before"); - info.addProperty("event", event == null ? "" : event); - sendWaitInfo(info, title); - } - JsonObject info = new JsonObject(); - info.addProperty("phase", "after"); - try { - return supplier.apply(this); - } catch (RuntimeException e) { - info.addProperty("error", e.getMessage()); - throw e; - } finally { - sendWaitInfo(info); - } - } - - @Override - public void log(String message) { - LoggingSupport.logApiIfEnabled(message); - JsonObject info = new JsonObject(); - info.addProperty("phase", "log"); - info.addProperty("message", message); - sendWaitInfo(info); - } - - private void sendWaitInfo(JsonObject info) { - sendWaitInfo(info, null); - } - - // The title goes with the first message of the wait, as in the Node.js client, where it is the - // title of the api zone; an outer call that has a title of its own keeps it. It is set for that - // message only, so that the calls made from the callback of the wait are not hidden as internal. - private void sendWaitInfo(JsonObject info, String title) { - info.addProperty("waitId", waitId); - // java: wrapApiCall reuses the zone of an outer call, so that call keeps its own title. - try { - channel.wrapApiCall(() -> channel.sendMessageNoReply("__waitInfo__", info), title, false); - } catch (RuntimeException e) { - // Fire-and-forget: never throw to the caller. - } - } -} diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java index c2e06bac2..88b2ad12b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java @@ -201,6 +201,14 @@ private RuntimeException rewriteErrorMessage(RuntimeException e) { return e; } + // java: the number as JavaScript prints it in the timeout messages. + static String formatTimeout(double timeout) { + if (timeout == Math.rint(timeout) && !Double.isInfinite(timeout)) { + return Long.toString((long) timeout); + } + return Double.toString(timeout); + } + static String formatLogRecording(List log) { if (log.isEmpty()) { return ""; diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java index 009f29f81..0f5b9df1f 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WebSocketImpl.java @@ -80,26 +80,18 @@ public void offSocketError(Consumer handler) { @Override public WebSocketFrame waitForFrameReceived(WaitForFrameReceivedOptions options, Runnable code) { - return withWaitLogging("WebSocket.waitForFrameReceived", "framereceived", logger -> waitForFrameReceivedImpl(options, code)); - } - - private WebSocketFrame waitForFrameReceivedImpl(WaitForFrameReceivedOptions options, Runnable code) { if (options == null) { options = new WaitForFrameReceivedOptions(); } - return waitForEventWithTimeout(Events.WebSocket.FRAME_RECEIVED, code, options.predicate, options.timeout); + return waitForEvent(Events.WebSocket.FRAME_RECEIVED, options.predicate, options.timeout, code); } @Override public WebSocketFrame waitForFrameSent(WaitForFrameSentOptions options, Runnable code) { - return withWaitLogging("WebSocket.waitForFrameSent", "framesent", logger -> waitForFrameSentImpl(options, code)); - } - - private WebSocketFrame waitForFrameSentImpl(WaitForFrameSentOptions options, Runnable code) { if (options == null) { options = new WaitForFrameSentOptions(); } - return waitForEventWithTimeout(Events.WebSocket.FRAME_SENT, code, options.predicate, options.timeout); + return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, code); } @Override @@ -112,36 +104,21 @@ public String url() { return initializer.get("url").getAsString(); } - private class WaitableWebSocketClose extends WaitableEvent { - WaitableWebSocketClose() { - super(WebSocketImpl.this, Events.WebSocket.CLOSE); - } - - @Override - public T get() { - throw new PlaywrightException("Socket closed"); - } - } - - private class WaitableWebSocketError extends WaitableEvent { - WaitableWebSocketError() { - super(WebSocketImpl.this, Events.WebSocket.ERROR); + // waitForEvent in network.ts + private WebSocketFrame waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { + double timeoutMs = page.timeoutSettings.timeout(timeout); + Waiter waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.WebSocket.ERROR.equals(event)) { + waiter.rejectOnEvent(this, Events.WebSocket.ERROR, () -> new PlaywrightException("Socket error")); } - - @Override - public T get() { - throw new PlaywrightException("Socket error"); + if (!Events.WebSocket.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.WebSocket.CLOSE, () -> new PlaywrightException("Socket closed")); } - } - - private WebSocketFrame waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(this, eventType, predicate)); - waitables.add(new WaitableWebSocketClose<>()); - waitables.add(new WaitableWebSocketError<>()); - waitables.add(page.createWaitForCloseHelper()); - waitables.add(page.createWaitableTimeout(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); + waiter.rejectOnEvent(page, Events.Page.CLOSE, () -> page.closeErrorWithReason()); + WebSocketFrame result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } @Override diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java index 93c8ff12a..3489ca21a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/WorkerImpl.java @@ -60,36 +60,41 @@ public void offConsole(Consumer handler) { off(Events.Worker.CONSOLE, handler); } - private T waitForEventWithTimeout(String eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(this, eventType, predicate)); - waitables.add(page.createWaitForCloseHelper()); - waitables.add(page.createWaitableTimeout(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); - } - @Override public Worker waitForClose(WaitForCloseOptions options, Runnable code) { - return withWaitLogging("Worker.waitForClose", "close", logger -> waitForCloseImpl(options, code)); + if (options == null) { + options = new WaitForCloseOptions(); + } + return waitForEvent(Events.Worker.CLOSE, null, options.timeout, code); } @Override public ConsoleMessage waitForConsoleMessage(WaitForConsoleMessageOptions options, Runnable code) { - return withWaitLogging("Worker.waitForConsoleMessage", "console", logger -> waitForConsoleMessageImpl(options, code)); - } - - private ConsoleMessage waitForConsoleMessageImpl(WaitForConsoleMessageOptions options, Runnable code) { if (options == null) { options = new WaitForConsoleMessageOptions(); } - return waitForEventWithTimeout(Events.Worker.CONSOLE, code, options.predicate, options.timeout); + return waitForEvent(Events.Worker.CONSOLE, options.predicate, options.timeout, code); } - private Worker waitForCloseImpl(WaitForCloseOptions options, Runnable code) { - if (options == null) { - options = new WaitForCloseOptions(); + TargetClosedError closeErrorWithReason() { + if (page != null) { + return page.closeErrorWithReason(); + } + return new TargetClosedError(); + } + + // waitForEvent in worker.ts + private T waitForEvent(String event, Predicate predicate, Double timeout, Runnable code) { + TimeoutSettings timeoutSettings = page != null ? page.timeoutSettings : new TimeoutSettings(); + double timeoutMs = timeoutSettings.timeout(timeout); + Waiter waiter = Waiter.createForEvent(this, event); + waiter.rejectOnTimeout(timeoutMs, "Timeout " + Waiter.formatTimeout(timeoutMs) + "ms exceeded while waiting for event \"" + event + "\""); + if (!Events.Worker.CLOSE.equals(event)) { + waiter.rejectOnEvent(this, Events.Worker.CLOSE, () -> closeErrorWithReason()); } - return waitForEventWithTimeout(Events.Worker.CLOSE, code, null, options.timeout); + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } @Override From 50f5e5be384827ad445a29fae614ab5f927a99bc Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Sun, 1 Nov 2026 18:46:53 -0800 Subject: [PATCH 10/14] test(waits): log the trimmed url like page.ts, drop the fixmes the Waiter fixed --- .../microsoft/playwright/impl/PageImpl.java | 42 ++++++++++++++----- .../tests/page/TestPageWaitForNavigation.java | 1 - .../tests/page/TestPageWaitForRequest.java | 2 - .../tests/page/TestPageWaitForResponse.java | 1 - 4 files changed, 32 insertions(+), 14 deletions(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java index 611976d4d..e02bdcd7b 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/PageImpl.java @@ -513,6 +513,28 @@ public Worker waitForWorker(WaitForWorkerOptions options, Runnable code) { return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, "waiting for event \"worker\"", code); } + private static String trimUrl(Object param) { + if (param instanceof Pattern) { + Pattern pattern = (Pattern) param; + return "/" + trimStringWithEllipsis(pattern.pattern(), 50) + "/" + Utils.toJsRegexFlags(pattern); + } + if (param instanceof String) { + return "\"" + trimStringWithEllipsis((String) param, 50) + "\""; + } + return null; + } + + private static String trimStringWithEllipsis(String input, int cap) { + if (input.length() <= cap) { + return input; + } + int[] chars = input.codePoints().toArray(); + if (chars.length > cap) { + return new String(chars, 0, cap - 1) + "\u2026"; + } + return input; + } + // _waitForEvent in page.ts private T waitForEvent(String event, Predicate predicate, Double timeout, String logLine, Runnable code) { double timeoutMs = timeoutSettings.timeout(timeout); @@ -1460,25 +1482,25 @@ public T get() { @Override public Request waitForRequest(String urlGlob, WaitForRequestOptions options, Runnable code) { - return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, options, code); + return waitForRequest(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, trimUrl(urlGlob), options, code); } @Override public Request waitForRequest(Pattern urlPattern, WaitForRequestOptions options, Runnable code) { - return waitForRequest(new UrlMatcher(urlPattern), null, options, code); + return waitForRequest(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); } @Override public Request waitForRequest(Predicate predicate, WaitForRequestOptions options, Runnable code) { - return waitForRequest(null, predicate, options, code); + return waitForRequest(null, predicate, null, options, code); } - private Request waitForRequest(UrlMatcher urlMatcher, Predicate predicate, WaitForRequestOptions options, Runnable code) { + private Request waitForRequest(UrlMatcher urlMatcher, Predicate predicate, String trimmedUrl, WaitForRequestOptions options, Runnable code) { if (options == null) { options = new WaitForRequestOptions(); } Predicate requestPredicate = predicate != null ? predicate : request -> urlMatcher.test(request.url()); - String logLine = urlMatcher == null ? null : "waiting for request " + urlMatcher; + String logLine = trimmedUrl == null ? null : "waiting for request " + trimmedUrl; return waitForEvent(Events.Page.REQUEST, requestPredicate, options.timeout, logLine, code); } @@ -1492,25 +1514,25 @@ public Request waitForRequestFinished(WaitForRequestFinishedOptions options, Run @Override public Response waitForResponse(String urlGlob, WaitForResponseOptions options, Runnable code) { - return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, options, code); + return waitForResponse(UrlMatcher.forGlob(browserContext.baseUrl(), urlGlob, this.connection.localUtils(), false), null, trimUrl(urlGlob), options, code); } @Override public Response waitForResponse(Pattern urlPattern, WaitForResponseOptions options, Runnable code) { - return waitForResponse(new UrlMatcher(urlPattern), null, options, code); + return waitForResponse(new UrlMatcher(urlPattern), null, trimUrl(urlPattern), options, code); } @Override public Response waitForResponse(Predicate predicate, WaitForResponseOptions options, Runnable code) { - return waitForResponse(null, predicate, options, code); + return waitForResponse(null, predicate, null, options, code); } - private Response waitForResponse(UrlMatcher urlMatcher, Predicate predicate, WaitForResponseOptions options, Runnable code) { + private Response waitForResponse(UrlMatcher urlMatcher, Predicate predicate, String trimmedUrl, WaitForResponseOptions options, Runnable code) { if (options == null) { options = new WaitForResponseOptions(); } Predicate responsePredicate = predicate != null ? predicate : response -> urlMatcher.test(response.url()); - String logLine = urlMatcher == null ? null : "waiting for response " + urlMatcher; + String logLine = trimmedUrl == null ? null : "waiting for response " + trimmedUrl; return waitForEvent(Events.Page.RESPONSE, responsePredicate, options.timeout, logLine, code); } diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForNavigation.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForNavigation.java index 109e1e155..0bbb0516d 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForNavigation.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForNavigation.java @@ -261,7 +261,6 @@ void shouldWorkOnFrame(Page page, TestServer server) { } @PlaywrightTest - @Fixme("java: the message is 'Navigating frame was detached' without the call log 'waiting for navigation until \"load\"'") @DisplayName("WA-109 should fail when frame detaches") void shouldFailWhenFrameDetaches(Page page, TestServer server) throws Exception { page.navigate(server.PREFIX + "/frames/one-frame.html"); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForRequest.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForRequest.java index a294ad8dc..9b486ea9d 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForRequest.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForRequest.java @@ -64,7 +64,6 @@ void shouldWorkWithPredicate(Page page, TestServer server) { @PlaywrightTest @DisplayName("WA-123 should respect timeout") - @Fixme("java: the message is 'Timeout 1ms exceeded' without the event name") void shouldRespectTimeout(Page page) { TimeoutError error = assertThrows(TimeoutError.class, () -> page.waitForRequest(r -> false, new Page.WaitForRequestOptions().setTimeout(1), () -> {})); @@ -81,7 +80,6 @@ void shouldRespectDefaultTimeout(Page page) { @PlaywrightTest @DisplayName("WA-125 should log the url") - @Fixme("java: the message is 'Timeout 1000ms exceeded' without the wait log") void shouldLogTheUrl(Page page) { PlaywrightException error = assertThrows(PlaywrightException.class, () -> page.waitForRequest( "long-long-long-long-long-long-long-long-long-long-long-long-long-long.css", diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForResponse.java b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForResponse.java index c0671465b..4b0aa5181 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForResponse.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/page/TestPageWaitForResponse.java @@ -73,7 +73,6 @@ void shouldRespectDefaultTimeout(Page page) { @PlaywrightTest @DisplayName("WA-132 should log the url") - @Fixme("java: the message is 'Timeout 1000ms exceeded' without the wait log") void shouldLogTheUrl(Page page) { PlaywrightException error1 = assertThrows(PlaywrightException.class, () -> page.waitForResponse("foo.css", new Page.WaitForResponseOptions().setTimeout(1000), () -> {})); From f3cbf17a5f17791578b0d8240befa1be0bc94061 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Mon, 16 Nov 2026 18:01:01 -0800 Subject: [PATCH 11/14] fix(protocol): restore the supportsLoneSurrogates flag and the protocol import lost in the restack --- .../src/main/java/com/microsoft/playwright/impl/Connection.java | 1 + .../src/main/java/com/microsoft/playwright/impl/Errors.java | 1 + 2 files changed, 2 insertions(+) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java index 3ad4d435e..1d7a11360 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -51,6 +51,7 @@ class Root extends ChannelOwner { PlaywrightImpl initialize() { RootInitializeParams params = new RootInitializeParams(); params.sdkLanguage = "java"; + params.supportsLoneSurrogates = true; return new RootChannel(this).initialize(params, NO_TIMEOUT).playwright; } } diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java index d21601d6f..b0e4100e9 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -17,6 +17,7 @@ // Port of packages/playwright-core/src/client/errors.ts package com.microsoft.playwright.impl; +import com.microsoft.playwright.impl.protocol.*; import com.microsoft.playwright.PlaywrightException; import com.microsoft.playwright.TimeoutError; From f6d18474055b492496b94fc5422f7fa4914a9a2f Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 17:55:22 -0800 Subject: [PATCH 12/14] fix(events): ignore a failed updateSubscription like channelOwner.ts A closed connection made off() throw from the dispose of a wait and replaced the error of the wait. --- .../microsoft/playwright/impl/ChannelOwner.java | 6 +++++- .../playwright/TestBrowserTypeConnect.java | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index 29f8fe24a..a967f2b67 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -75,7 +75,11 @@ void updateSubscription(String event, boolean enabled) { JsonObject params = new JsonObject(); params.addProperty("event", protocolEvent); params.addProperty("enabled", enabled); - sendMessageAsync("updateSubscription", params); + try { + sendMessageAsync("updateSubscription", params); + } catch (PlaywrightException e) { + // java: .catch(() => {}) upstream, the send throws synchronously when the connection is closed. + } } } diff --git a/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java b/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java index 9052e384a..d576fb4bd 100644 --- a/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java +++ b/playwright/src/test/java/com/microsoft/playwright/TestBrowserTypeConnect.java @@ -32,6 +32,7 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; +import java.util.function.Consumer; import java.util.stream.Collectors; import static com.microsoft.playwright.Utils.*; @@ -224,6 +225,21 @@ void shouldRejectNavigationWhenBrowserCloses(BrowserType browserType, Server ser assertTrue(e.getMessage().contains("Browser has been closed")); } + @PlaywrightTest + void shouldKeepCloseReasonInNetworkWaiterAndNotThrowOnOffAfterDisconnect(BrowserType browserType, Server server, BrowserServer browserServer) { + Browser remote = browserType.connect(browserServer.wsEndpoint); + Page page = remote.newPage(); + + PlaywrightException e = assertThrows(PlaywrightException.class, () -> { + page.waitForRequest(server.EMPTY_PAGE, () -> remote.close(new Browser.CloseOptions().setReason("custom reason"))); + }); + assertTrue(e.getMessage().contains("custom reason"), e.getMessage()); + + Consumer listener = r -> {}; + page.onRequest(listener); + page.offRequest(listener); + } + @PlaywrightTest void shouldEmitCloseEventsOnPagesAndContexts(BrowserType browserType) throws InterruptedException { BrowserServer server = BrowserServer.launch(browserType); From e0e333fc263b3d1fb29bae567aef3a27fb64c9ef Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Tue, 17 Nov 2026 19:07:59 -0800 Subject: [PATCH 13/14] fix(waits): the outcome of a wait wins over the error of a closed pipe On Firefox the pipe closes before the pages report their close, and the pump threw 'Browser closed' from the wait instead of the close error of the waiter. --- .../com/microsoft/playwright/impl/ChannelOwner.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java index a967f2b67..a52b5e8ae 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/ChannelOwner.java @@ -270,7 +270,15 @@ T runUntil(Runnable code, Waitable waitable) { try { code.run(); while (!waitable.isDone()) { - connection.processOneMessage(); + try { + connection.processOneMessage(); + } catch (PlaywrightException e) { + // java: a closed pipe throws from the pump right after it dispatched the close events; the outcome + // of the waitable wins, as the promise settled by those events does upstream. + if (!waitable.isDone()) { + throw e; + } + } } return waitable.get(); } finally { From c8972c5f41fea2c1308c142e301b1978fe4d3c34 Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Wed, 18 Nov 2026 09:18:54 -0800 Subject: [PATCH 14/14] fix(connect): time out while waiting for the Playwright initialization connect() waited forever once the websocket was open. The three fixmes for it passed whenever the websocket took longer than the timeout to open, which failed the run. --- .../playwright/impl/BrowserTypeImpl.java | 18 ++++++++++- .../microsoft/playwright/impl/Connection.java | 32 +++++++++++++++++++ .../tests/library/TestBrowsertypeConnect.java | 4 +-- 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java index e52831a2f..971834010 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java @@ -22,6 +22,7 @@ import com.microsoft.playwright.Browser; import com.microsoft.playwright.BrowserType; import com.microsoft.playwright.PlaywrightException; +import com.microsoft.playwright.TimeoutError; import com.microsoft.playwright.options.ClientCertificate; import java.io.IOException; @@ -85,9 +86,24 @@ public Browser connect(String wsEndpoint, ConnectOptions options) { timeout = 0.0; } + long deadline = timeout == 0 ? 0 : System.nanoTime() + (long) (timeout * 1_000_000); JsonPipe pipe = connection.localUtils().channel.connect(params, timeout).pipe; Connection connection = new Connection(pipe, this.connection.env, this.connection.localUtils()); - PlaywrightImpl playwright = connection.initializePlaywright(); + PlaywrightImpl playwright; + if (deadline == 0) { + playwright = connection.initializePlaywright(); + } else { + try { + playwright = connection.initializePlaywright(deadline, timeout); + } catch (TimeoutError e) { + try { + connection.close(); + } catch (IOException ioe) { + ioe.printStackTrace(System.err); + } + throw e; + } + } if (!playwright.initializer.has("preLaunchedBrowser")) { try { connection.close(); diff --git a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java index 1d7a11360..a8f5f586a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -34,6 +34,7 @@ import java.io.IOException; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -54,6 +55,31 @@ PlaywrightImpl initialize() { params.supportsLoneSurrogates = true; return new RootChannel(this).initialize(params, NO_TIMEOUT).playwright; } + + // java: the deadline of raceAgainstDeadline in connect.ts, the wait pumps the connection until then. + PlaywrightImpl initialize(long deadlineNanos, double timeout) { + RootInitializeParams params = new RootInitializeParams(); + params.sdkLanguage = "java"; + params.supportsLoneSurrogates = true; + WaitableResult result = sendMessageAsync("initialize", params); + Waitable deadline = new Waitable() { + @Override + public boolean isDone() { + return System.nanoTime() > deadlineNanos; + } + + @Override + public JsonElement get() { + throw new TimeoutError("Timeout " + Waiter.formatTimeout(timeout) + "ms exceeded"); + } + + @Override + public void dispose() { + } + }; + JsonElement json = runUntil(() -> {}, new WaitableRace<>(Arrays.asList(result, deadline))); + return connection.protocolGson().fromJson(json, RootInitializeResult.class).playwright; + } } class DummyChannelOwner extends ChannelOwner { @@ -189,6 +215,12 @@ public PlaywrightImpl initializePlaywright() { return playwright; } + // java: connect.ts races the initialization against the deadline of connect(). + PlaywrightImpl initializePlaywright(long deadlineNanos, double timeout) { + playwright = rootObject.initialize(deadlineNanos, timeout); + return playwright; + } + // java: upstream has getObjectWithKnownName(guid) for the same lookup; this one throws for an unknown guid. public T getExistingObject(String guid) { @SuppressWarnings("unchecked") T result = (T) objects.get(guid); diff --git a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java index 1c2faecfe..d7e9e283e 100644 --- a/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java +++ b/playwright/src/test/java/com/microsoft/playwright/tests/library/TestBrowsertypeConnect.java @@ -491,7 +491,7 @@ void shouldTimeoutInSocketWhileConnecting(Connect connect, TestServer server) { @PlaywrightTest @DisplayName("BT-045 should timeout in connect while connecting") - @Fixme(value = "java: connect() has no timeout once the websocket is open, it waits forever for the Playwright initialization", timeoutMillis = 15000) + @Fixme("java: the error message has no 'browserType.connect:' prefix") void shouldTimeoutInConnectWhileConnecting(Connect connect, TestServer server) { PlaywrightException e = assertThrows(PlaywrightException.class, () -> connect.connect("ws://localhost:" + server.PORT + "/ws", new BrowserType.ConnectOptions().setTimeout(100))); @@ -500,7 +500,6 @@ void shouldTimeoutInConnectWhileConnecting(Connect connect, TestServer server) { @PlaywrightTest @DisplayName("BT-046 should send extra headers with connect request") - @Fixme(value = "java: connect() has no timeout once the websocket is open, it waits forever for the Playwright initialization", timeoutMillis = 15000) void shouldSendExtraHeadersWithConnectRequest(Connect connect, TestServer server) throws Exception { CompletableFuture requestPromise = server.waitForWebSocketConnectionRequest(); try { @@ -537,7 +536,6 @@ void shouldSendExtraHeadersWithConnectRequestInObjectForm(BrowserType browserTyp @PlaywrightTest @DisplayName("BT-048 should send default User-Agent and X-Playwright-Browser headers with connect request") - @Fixme(value = "java: connect() has no timeout once the websocket is open, it waits forever for the Playwright initialization", timeoutMillis = 15000) void shouldSendDefaultUserAgentAndXPlaywrightBrowserHeadersWithConnectRequest(Connect connect, BrowserName browserName, TestServer server, Playwright playwright) throws Exception { // Java: getUserAgent() is a function of the driver; global fetch sends the same User-Agent. CompletableFuture userAgentRequest = server.waitForRequest("/empty.html");