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/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 41e77105d..854213eb5 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; @@ -54,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() { @@ -144,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 @@ -336,24 +315,25 @@ public Credentials credentials() { return credentials; } - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, 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(EventType.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 @@ -525,7 +505,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)); } @@ -550,8 +530,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); } @@ -563,7 +543,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 @@ -680,7 +660,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 @@ -704,19 +684,15 @@ 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(EventType.CONSOLE, code, options.predicate, options.timeout); + return waitForEvent(Events.BrowserContext.CONSOLE, options.predicate, options.timeout, code); } - private class WaitableContextClose extends WaitableEvent { + private class WaitableContextClose extends WaitableEvent { WaitableContextClose() { - super(BrowserContextImpl.this.listeners, EventType.CLOSE); + super(BrowserContextImpl.this, Events.BrowserContext.CLOSE); } @Override @@ -773,15 +749,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 @@ -800,10 +776,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()); @@ -815,7 +791,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); } @@ -830,20 +806,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(); @@ -855,10 +831,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(); @@ -867,18 +843,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")); @@ -892,9 +868,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(); @@ -909,7 +885,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 cc0dccf18..5a0c23e26 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserImpl.java @@ -35,11 +35,11 @@ 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. final Set contexts = new LinkedHashSet<>(); - private final ListenerCollection listeners = new ListenerCollection<>(); boolean isConnectedOverWebSocket; private boolean isConnected = true; BrowserTypeImpl browserType; @@ -47,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) { @@ -60,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 @@ -91,7 +86,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); } @@ -363,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/BrowserTypeImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/BrowserTypeImpl.java index 5ea7b91ab..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; @@ -51,7 +52,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; @@ -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(); + Connection connection = new Connection(pipe, this.connection.env, this.connection.localUtils()); + 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(); @@ -124,7 +140,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 +222,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/CDPSessionImpl.java b/playwright/src/main/java/com/microsoft/playwright/impl/CDPSessionImpl.java index 6f28c69be..2e785a0cc 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) { @@ -79,14 +72,17 @@ 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) { - listeners.add(event, handler); + @SuppressWarnings("rawtypes") + public void on(String event, Consumer handler) { + super.on(event, handler); } @Override - public void off(String event, Consumer handler) { - listeners.remove(event, handler); + @SuppressWarnings("rawtypes") + public void off(String event, Consumer handler) { + super.off(event, handler); } @Override 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..a52b5e8ae 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; @@ -23,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<>(); @@ -34,44 +36,80 @@ 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; + } + + 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); + try { + sendMessageAsync("updateSubscription", params); + } catch (PlaywrightException e) { + // java: .catch(() => {}) upstream, the send throws synchronously when the connection is closed. + } } } - void disposeChannelOwner(boolean wasGarbageCollected) { - // Clean up from parent and connection. - if (parent != null) { - parent.objects.remove(guid); + // 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); } - connection.unregisterObject(guid); - wasCollected = wasGarbageCollected; - // Dispose all children. - for (ChannelOwner child : new ArrayList<>(objects.values())) { - child.disposeChannelOwner(wasGarbageCollected); + } + + @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); } - objects.clear(); } void adopt(ChannelOwner child) { @@ -80,43 +118,93 @@ void adopt(ChannelOwner child) { child.parent = this; } - T withWaitLogging(String apiName, Function code) { - return new WaitForEventLogger<>(this, apiName, null, null, code).get(); + 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 = "gc".equals(reason); + + // Dispose all children. + for (ChannelOwner object : new ArrayList<>(objects.values())) { + object.dispose(reason); + } + objects.clear(); } - /** 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(); + // 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; } - T withWaitLoggingTitled(String apiName, String title, Function code) { - return new WaitForEventLogger<>(this, apiName, null, title, code).get(); + 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) { - withTitle(title, () -> { - code.run(); - return null; - }); + wrapApiCall(code, title, false); } T withTitle(String title, Supplier code) { - String previousTitle = connection.setTitle(title); - try { - return code.get(); - } finally { - connection.setTitle(previousTitle); - } + return wrapApiCall(code, title, false); } + // 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 +226,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 +237,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,16 +265,20 @@ 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(); 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 { @@ -197,12 +286,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 { + 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 41d1ff6f3..a8f5f586a 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Connection.java @@ -13,25 +13,28 @@ * 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; 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; @@ -40,233 +43,303 @@ 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='" + Connection.errorToString(error) + '\'' + - '}'; + PlaywrightImpl initialize() { + RootInitializeParams params = new RootInitializeParams(); + params.sdkLanguage = "java"; + 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 { + 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: connect.ts races the initialization against the deadline of connect(). + PlaywrightImpl initializePlaywright(long deadlineNanos, double timeout) { + playwright = rootObject.initialize(deadlineNanos, timeout); + return playwright; } - 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(); + // 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 WaitableResult sendMessageAsync(String guid, String method, JsonObject params) { - return internalSendMessage(guid, method, params, null, true, true); + void registerObject(String guid, ChannelOwner object) { + objects.put(guid, object); } - // Fire-and-forget: the server never replies. - public void sendMessageNoReply(String guid, String method, JsonObject params) { - internalSendMessage(guid, method, params, null, false, false); + void unregisterObject(String guid) { + objects.remove(guid); } - 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); + void setIsTracing(boolean tracing) { + if (tracing) { + ++tracingCount; + } else { + --tracingCount; + } + } + + // 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); } - JsonArray stack = null; - if (titleReported) { + 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); + } + 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; - } - - /** Gson that serializes channel owners as {guid} and resolves them back through this connection (see channelOwner.ts, connection.ts upstream). */ - Gson protocolGson() { - return protocolGson; + return expectsReply ? result : completed(); } - 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 +351,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,22 +484,30 @@ 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' + - '}'; + 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(); } - static String errorToString(SerializedError error) { - if (error.error != null) { - return errorToString(error.error); + 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 "SerializedError{" + - "value=" + error.value + - '}'; + return prefix.toString(); } private static String formatCallLog(JsonArray log) { @@ -374,179 +533,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 { - 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); - } - 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/Errors.java b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java new file mode 100644 index 000000000..b0e4100e9 --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Errors.java @@ -0,0 +1,87 @@ +/* + * 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.impl.protocol.*; +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/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); + } +} 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"; + } +} 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..c490036ef 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); @@ -822,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) { - internalListeners.add(InternalEventType.LOADSTATE, 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() { - internalListeners.remove(InternalEventType.LOADSTATE, 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; - internalListeners.add(InternalEventType.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); - } - internalListeners.remove(InternalEventType.NAVIGATED, this); - } - - @Override - public void dispose() { - internalListeners.remove(InternalEventType.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 @@ -1008,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) { @@ -1122,13 +1061,13 @@ protected void handleEvent(String event, JsonObject params) { loadStates.add(state); if (parentFrame == null && page != null) { if (state == LOAD) { - page.listeners.notify(PageImpl.EventType.LOAD, page); + page.emit(Events.Page.LOAD, page); page.browserContext.notifyPageLoad(page); } else if (state == DOMCONTENTLOADED) { - page.listeners.notify(PageImpl.EventType.DOMCONTENTLOADED, page); + page.emit(Events.Page.DOM_CONTENT_LOADED, page); } } - internalListeners.notify(InternalEventType.LOADSTATE, state); + emit(Events.Frame.LOAD_STATE, state); } JsonElement remove = params.get("remove"); if (remove != null) { @@ -1140,7 +1079,7 @@ protected void handleEvent(String event, JsonObject params) { if (!params.has("error") && page != null) { page.frameNavigated(this); } - internalListeners.notify(InternalEventType.NAVIGATED, params); + emit(Events.Frame.NAVIGATED, params); } } 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..a204a45a8 100644 --- a/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java +++ b/playwright/src/main/java/com/microsoft/playwright/impl/JsonPipe.java @@ -31,8 +31,6 @@ public class JsonPipe extends ChannelOwner implements Transport { private final Queue incoming = new LinkedList<>(); - private ListenerCollection listeners = new ListenerCollection<>(); - private enum EventType { CLOSE } private boolean isClosed; private String closeReason = "Browser has been closed"; @@ -86,12 +84,16 @@ public void close() throws IOException { } } + String closeReason() { + return 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); } @@ -107,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 b0cce97d5..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/ListenerCollection.java +++ /dev/null @@ -1,91 +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 com.microsoft.playwright.PlaywrightException; - -import java.util.*; -import java.util.function.Consumer; - -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; - } - - 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 (eventSubscriptions == null) { - return; - } - String protocolEvent = eventSubscriptions.get(eventType); - if (protocolEvent == null) { - return; - } - 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/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 ae532e651..e02bdcd7b 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; @@ -83,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; @@ -105,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; @@ -168,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); @@ -208,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(); @@ -218,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(); @@ -246,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)) { @@ -255,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); } @@ -272,204 +247,208 @@ private String effectiveCloseReason() { return browserContext.effectiveCloseReason(); } + TargetClosedError closeErrorWithReason() { + return new TargetClosedError(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 @@ -479,95 +458,100 @@ 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(EventType.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(EventType.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(EventType.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(EventType.FILECHOOSER, 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(EventType.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(EventType.WEBSOCKET, 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(EventType.WORKER, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.WORKER, options.predicate, options.timeout, "waiting for event \"worker\"", code); } - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); - waitables.add(createWaitForCloseHelper()); - waitables.add(createWaitableTimeout(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); + 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); + 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 @@ -821,7 +805,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 @@ -1171,7 +1155,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)); } @@ -1196,8 +1180,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); } @@ -1209,7 +1193,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 @@ -1396,7 +1380,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 @@ -1440,10 +1424,6 @@ public ViewportSize viewportSize() { return viewport; } - Waitable createWaitableNavigationTimeout(Double timeout) { - return new WaitableTimeout<>(timeoutSettings.navigationTimeout(timeout)); - } - Waitable createWaitableTimeout(Double timeout) { return timeoutSettings.createWaitable(timeout); } @@ -1455,83 +1435,43 @@ 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) { - listeners.notify(EventType.FRAMENAVIGATED, frame); + emit(Events.Page.FRAME_NAVIGATED, frame); browserContext.notifyFrameNavigated(frame); } - private class WaitableFrameDetach extends WaitableEvent { - WaitableFrameDetach(Frame frameArg) { - super(PageImpl.this.listeners, EventType.FRAMEDETACHED, 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); + return new WaitableRace(asList(new WaitablePageClose(), new WaitablePageCrash())); } - /** 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())); - } - - private class WaitablePageClose extends WaitableEvent { - private final boolean closedBefore; - - WaitablePageClose(boolean closedBefore) { - super(PageImpl.this.listeners, EventType.CLOSE); - this.closedBefore = closedBefore; - } - - @Override - public boolean isDone() { - return closedBefore || super.isDone(); + private class WaitablePageClose extends WaitableEvent { + WaitablePageClose() { + super(PageImpl.this, Events.Page.CLOSE); } @Override public T get() { - throw new TargetClosedError(effectiveCloseReason()); + throw closeErrorWithReason(); } } - private class WaitablePageCrash extends WaitableEvent { + private class WaitablePageCrash extends WaitableEvent { WaitablePageCrash() { - super(PageImpl.this.listeners, EventType.CRASH); + super(PageImpl.this, Events.Page.CRASH); } @Override @@ -1542,80 +1482,58 @@ 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); - } - - 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); - }); + return waitForRequest(null, predicate, null, options, code); } - private Request waitForRequestImpl(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(); } - return waitForEventWithTimeout(EventType.REQUEST, code, predicate, options.timeout); + Predicate requestPredicate = predicate != null ? predicate : request -> urlMatcher.test(request.url()); + String logLine = trimmedUrl == null ? null : "waiting for request " + trimmedUrl; + 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(EventType.REQUESTFINISHED, code, options.predicate, options.timeout); + return waitForEvent(Events.Page.REQUEST_FINISHED, options.predicate, options.timeout, "waiting for event \"requestfinished\"", code); } @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) { - 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) { + private Response waitForResponse(UrlMatcher urlMatcher, Predicate predicate, String trimmedUrl, WaitForResponseOptions options, Runnable code) { if (options == null) { options = new WaitForResponseOptions(); } - return waitForEventWithTimeout(EventType.RESPONSE, code, predicate, options.timeout); + Predicate responsePredicate = predicate != null ? predicate : response -> urlMatcher.test(response.url()); + String logLine = trimmedUrl == null ? null : "waiting for response " + trimmedUrl; + return waitForEvent(Events.Page.RESPONSE, responsePredicate, options.timeout, logLine, code); } @Override @@ -1639,24 +1557,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/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/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; - } } 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 b0e3aa035..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); } @@ -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(); 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 deleted file mode 100644 index 530100255..000000000 --- a/playwright/src/main/java/com/microsoft/playwright/impl/WaitForEventLogger.java +++ /dev/null @@ -1,96 +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); - Connection connection = channel.connection; - boolean setTitle = title != null && connection.title() == null; - if (setTitle) { - connection.setTitle(title); - } - try { - channel.sendMessageNoReply("__waitInfo__", info); - } catch (RuntimeException e) { - // Fire-and-forget: never throw to the caller. - } finally { - if (setTitle) { - connection.setTitle(null); - } - } - } -} 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/Waiter.java b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java new file mode 100644 index 000000000..88b2ad12b --- /dev/null +++ b/playwright/src/main/java/com/microsoft/playwright/impl/Waiter.java @@ -0,0 +1,257 @@ +/* + * 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; + } + + // 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 ""; + } + 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); + } +} 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..0f5b9df1f 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,66 +40,58 @@ 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 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(EventType.FRAMERECEIVED, 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(EventType.FRAMESENT, code, options.predicate, options.timeout); + return waitForEvent(Events.WebSocket.FRAME_SENT, options.predicate, options.timeout, code); } @Override @@ -120,36 +104,21 @@ public String url() { return initializer.get("url").getAsString(); } - private class WaitableWebSocketClose extends WaitableEvent { - WaitableWebSocketClose() { - super(WebSocketImpl.this.listeners, EventType.CLOSE); - } - - @Override - public T get() { - throw new PlaywrightException("Socket closed"); - } - } - - private class WaitableWebSocketError extends WaitableEvent { - WaitableWebSocketError() { - super(WebSocketImpl.this.listeners, EventType.SOCKETERROR); + // 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(EventType eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, 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 @@ -162,7 +131,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 +141,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..3489ca21a 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,54 +42,59 @@ 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); - } - - private T waitForEventWithTimeout(EventType eventType, Runnable code, Predicate predicate, Double timeout) { - List> waitables = new ArrayList<>(); - waitables.add(new WaitableEvent<>(listeners, eventType, predicate)); - waitables.add(page.createWaitForCloseHelper()); - waitables.add(page.createWaitableTimeout(timeout)); - return runUntil(code, new WaitableRace<>(waitables)); + off(Events.Worker.CONSOLE, handler); } @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(EventType.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(EventType.CLOSE, code, null, options.timeout); + T result = waiter.waitForEvent(this, event, predicate, code); + waiter.dispose(); + return result; } @Override @@ -125,7 +124,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); } } } 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); 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..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"); @@ -677,7 +675,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()); 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), () -> {}));