Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -362,11 +362,16 @@ public void sendMessage(String method, Object params, Double timeout) {

// java: pumps the connection until the waitable is done; upstream awaits promises.
<T> T runUntil(Runnable code, Waitable<T> waitable) {
return runUntil(code, waitable, true);
}

// java: a route action waits for its reply without entering another route handler.
<T> T runUntil(Runnable code, Waitable<T> waitable, boolean dispatchRoutes) {
try {
code.run();
while (!waitable.isDone()) {
try {
connection.processOneMessage();
connection.processOneMessage(dispatchRoutes);
} 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -116,6 +118,7 @@ public class Connection extends EventEmitter {

// java: everything below has no counterpart in connection.ts.
private final Transport transport;
private final Deque<Message> deferredRouteEvents = new ArrayDeque<>();
private final StackTraceCollector stackTraceCollector;
private final Gson protocolGson = gson().newBuilder()
.registerTypeAdapterFactory(new ChannelOwnerAdapterFactory())
Expand Down Expand Up @@ -557,13 +560,26 @@ JsonElement sendMessage(ChannelOwner object, String method, JsonObject params, C

// java: upstream receives messages through onmessage(); here the pump polls the transport.
boolean processOneMessage() {
return processOneMessage(true);
}

// java: route-action waits defer route events so queued requests do not nest on the Java stack.
boolean processOneMessage(boolean dispatchRoutes) {
if (dispatchRoutes && !deferredRouteEvents.isEmpty()) {
dispatch(deferredRouteEvents.removeFirst());
return true;
}
JsonObject message = transport.poll(Duration.ofMillis(10));
if (message == null) {
return false;
}
Gson gson = gson();
Message messageObj = gson.fromJson(message, Message.class);
dispatch(messageObj);
if (!dispatchRoutes && messageObj.id == null && "route".equals(messageObj.method)) {
deferredRouteEvents.addLast(messageObj);
} else {
dispatch(messageObj);
}
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@ <T> T safeRace(Waitable<T> promise, T defaultValue) {
return await(race(Collections.singletonList(promise), true, defaultValue));
}

// java: route actions keep synchronous replies and close races, but must not recursively dispatch routes.
<T> T safeRaceWithoutRouteEvents(Waitable<T> promise) {
return await(race(Collections.singletonList(promise), true, null), false);
}

private <T> Waitable<T> race(List<Waitable<T>> promises, boolean safe, T defaultValue) {
WaitableResult<PlaywrightException> terminatePromise = new WaitableResult<>();
StackTraceElement[] frames = new Exception().getStackTrace();
Expand Down Expand Up @@ -135,8 +140,12 @@ private static PlaywrightException cloneError(PlaywrightException error, StackTr

// java: await of a race; the finally block of _race disposes it.
private <T> T await(Waitable<T> race) {
return await(race, true);
}

private <T> T await(Waitable<T> race, boolean dispatchRoutes) {
try {
return owner.runUntil(() -> {}, race);
return owner.runUntil(() -> {}, race, dispatchRoutes);
} finally {
race.dispose();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ private void raceWithTargetClose(WaitableResult<JsonElement> promise) {
// When page closes or crashes, we catch any potential rejects from this Route.
// Note that page could be missing when routing popup's initial request that
// does not have a Page initialized just yet.
request().targetClosedScope().safeRace(promise);
// java: waiting for an acknowledgment must not dispatch the next route on this stack.
request().targetClosedScope().safeRaceWithoutRouteEvents(promise);
}

WaitableResult<Boolean> startHandling() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ void shouldWorkWithRedirectsForSubresources(Page page, Server server, BrowserNam

@PlaywrightTest
void shouldWorkWithEqualRequests(Page page, Server server) {
// https://github.com/microsoft/playwright-java/issues/2068
page.navigate(server.EMPTY_PAGE);
AtomicInteger responseCount = new AtomicInteger(1);
server.setRoute("/zzz", exchange -> {
Expand All @@ -436,8 +437,10 @@ void shouldWorkWithEqualRequests(Page page, Server server) {
});

boolean[] spinner = {false};
int[] intercepted = {0};
// Cancel 2nd request.
page.route("**/*", route -> {
++intercepted[0];
if (spinner[0]) {
route.abort();
} else {
Expand All @@ -450,6 +453,9 @@ void shouldWorkWithEqualRequests(Page page, Server server) {
results.add(page.evaluate("() => fetch('/zzz').then(response => response.text()).catch(e => 'FAILED')"));
}
assertEquals(asList("11", "FAILED", "22"), results);
assertEquals(3000, page.evaluate("() => Promise.allSettled(Array.from({length: 3000}, " +
"() => fetch('/zzz').then(response => response.text()))).then(results => results.length)"));
assertEquals(3003, intercepted[0]);
}

@PlaywrightTest
Expand Down
Loading