|
| 1 | +package com.seleniumboot.wait; |
| 2 | + |
| 3 | +import com.seleniumboot.network.NetworkMock; |
| 4 | +import org.openqa.selenium.TimeoutException; |
| 5 | +import org.openqa.selenium.WebDriver; |
| 6 | +import org.openqa.selenium.bidi.HasBiDi; |
| 7 | +import org.openqa.selenium.bidi.module.Network; |
| 8 | +import org.openqa.selenium.chromium.ChromiumDriver; |
| 9 | +import org.openqa.selenium.devtools.DevTools; |
| 10 | +import org.openqa.selenium.devtools.v153.network.model.LoadingFailed; |
| 11 | +import org.openqa.selenium.devtools.v153.network.model.LoadingFinished; |
| 12 | +import org.openqa.selenium.devtools.v153.network.model.RequestWillBeSent; |
| 13 | +import org.openqa.selenium.devtools.v153.network.model.ResponseReceived; |
| 14 | + |
| 15 | +import java.time.Duration; |
| 16 | +import java.time.Instant; |
| 17 | +import java.util.Optional; |
| 18 | +import java.util.concurrent.CompletableFuture; |
| 19 | +import java.util.concurrent.ExecutionException; |
| 20 | +import java.util.concurrent.TimeUnit; |
| 21 | +import java.util.concurrent.atomic.AtomicInteger; |
| 22 | + |
| 23 | +/** |
| 24 | + * Backs {@link WaitEngine#waitForNetworkIdle} and {@link WaitEngine#waitForResponse}. |
| 25 | + * |
| 26 | + * <p>CDP (Chrome/Edge) and BiDi (Firefox, or any other {@code HasBiDi} driver) wiring is |
| 27 | + * covered by manual verification against real browsers, not unit tests — same convention |
| 28 | + * as {@link NetworkMock}. {@link IdleState}, the poll condition both paths feed, is pure |
| 29 | + * and unit-tested directly. |
| 30 | + */ |
| 31 | +final class NetworkActivityTracker { |
| 32 | + |
| 33 | + private NetworkActivityTracker() { |
| 34 | + } |
| 35 | + |
| 36 | + static void awaitIdle(WebDriver driver, Duration quietFor, Duration timeout) { |
| 37 | + IdleState state = new IdleState(); |
| 38 | + if (driver instanceof ChromiumDriver chromium) { |
| 39 | + try (DevTools devTools = chromium.getDevTools()) { |
| 40 | + devTools.createSession(); |
| 41 | + devTools.send(org.openqa.selenium.devtools.v153.network.Network.enable( |
| 42 | + Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); |
| 43 | + devTools.addListener(org.openqa.selenium.devtools.v153.network.Network.requestWillBeSent(), |
| 44 | + (RequestWillBeSent event) -> state.requestStarted()); |
| 45 | + devTools.addListener(org.openqa.selenium.devtools.v153.network.Network.loadingFinished(), |
| 46 | + (LoadingFinished event) -> state.requestEnded()); |
| 47 | + devTools.addListener(org.openqa.selenium.devtools.v153.network.Network.loadingFailed(), |
| 48 | + (LoadingFailed event) -> state.requestEnded()); |
| 49 | + pollUntilIdle(state, quietFor, timeout); |
| 50 | + } |
| 51 | + } else if (driver instanceof HasBiDi) { |
| 52 | + try (Network network = new Network(driver)) { |
| 53 | + network.onBeforeRequestSent(event -> state.requestStarted()); |
| 54 | + network.onResponseCompleted(event -> state.requestEnded()); |
| 55 | + network.onFetchError(event -> state.requestEnded()); |
| 56 | + pollUntilIdle(state, quietFor, timeout); |
| 57 | + } |
| 58 | + } else { |
| 59 | + throw unsupported(driver); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + static int awaitResponse(WebDriver driver, String urlPattern, Duration timeout) { |
| 64 | + ResponseLatch latch = new ResponseLatch(); |
| 65 | + if (driver instanceof ChromiumDriver chromium) { |
| 66 | + try (DevTools devTools = chromium.getDevTools()) { |
| 67 | + devTools.createSession(); |
| 68 | + devTools.send(org.openqa.selenium.devtools.v153.network.Network.enable( |
| 69 | + Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty())); |
| 70 | + devTools.addListener(org.openqa.selenium.devtools.v153.network.Network.responseReceived(), |
| 71 | + (ResponseReceived event) -> { |
| 72 | + String url = event.getResponse().getUrl(); |
| 73 | + if (NetworkMock.matches(urlPattern, url)) { |
| 74 | + latch.complete(event.getResponse().getStatus()); |
| 75 | + } |
| 76 | + }); |
| 77 | + return latch.await(timeout); |
| 78 | + } |
| 79 | + } else if (driver instanceof HasBiDi) { |
| 80 | + try (Network network = new Network(driver)) { |
| 81 | + network.onResponseCompleted(event -> { |
| 82 | + String url = event.getResponseData().getUrl(); |
| 83 | + if (NetworkMock.matches(urlPattern, url)) { |
| 84 | + latch.complete(event.getResponseData().getStatus()); |
| 85 | + } |
| 86 | + }); |
| 87 | + return latch.await(timeout); |
| 88 | + } |
| 89 | + } else { |
| 90 | + throw unsupported(driver); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private static void pollUntilIdle(IdleState state, Duration quietFor, Duration timeout) { |
| 95 | + Instant deadline = Instant.now().plus(timeout); |
| 96 | + while (Instant.now().isBefore(deadline)) { |
| 97 | + if (state.isIdle(quietFor)) return; |
| 98 | + sleep(100); |
| 99 | + } |
| 100 | + throw new TimeoutException("waitForNetworkIdle: timed out after " + timeout |
| 101 | + + " with " + state.inFlightCount() + " request(s) still in flight"); |
| 102 | + } |
| 103 | + |
| 104 | + private static void sleep(long millis) { |
| 105 | + try { |
| 106 | + Thread.sleep(millis); |
| 107 | + } catch (InterruptedException e) { |
| 108 | + Thread.currentThread().interrupt(); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + private static UnsupportedOperationException unsupported(WebDriver driver) { |
| 113 | + return new UnsupportedOperationException( |
| 114 | + "waitForNetworkIdle/waitForResponse need CDP (Chrome/Edge) or BiDi support; got " |
| 115 | + + driver.getClass().getSimpleName()); |
| 116 | + } |
| 117 | + |
| 118 | + // ------------------------------------------------------------------ |
| 119 | + // Pure, unit-tested pieces |
| 120 | + // ------------------------------------------------------------------ |
| 121 | + |
| 122 | + /** In-flight request counter + last-activity timestamp. Idle = none in flight, quiet long enough. */ |
| 123 | + static final class IdleState { |
| 124 | + private final AtomicInteger inFlight = new AtomicInteger(); |
| 125 | + private volatile long lastActivityNanos = System.nanoTime(); |
| 126 | + |
| 127 | + void requestStarted() { |
| 128 | + inFlight.incrementAndGet(); |
| 129 | + lastActivityNanos = System.nanoTime(); |
| 130 | + } |
| 131 | + |
| 132 | + void requestEnded() { |
| 133 | + inFlight.decrementAndGet(); |
| 134 | + lastActivityNanos = System.nanoTime(); |
| 135 | + } |
| 136 | + |
| 137 | + boolean isIdle(Duration quietFor) { |
| 138 | + return inFlight.get() <= 0 && (System.nanoTime() - lastActivityNanos) >= quietFor.toNanos(); |
| 139 | + } |
| 140 | + |
| 141 | + int inFlightCount() { |
| 142 | + return inFlight.get(); |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + /** Resolves once a matching response is observed, or times out. */ |
| 147 | + static final class ResponseLatch { |
| 148 | + private final CompletableFuture<Integer> future = new CompletableFuture<>(); |
| 149 | + |
| 150 | + void complete(int status) { |
| 151 | + future.complete(status); |
| 152 | + } |
| 153 | + |
| 154 | + int await(Duration timeout) { |
| 155 | + try { |
| 156 | + return future.get(timeout.toMillis(), TimeUnit.MILLISECONDS); |
| 157 | + } catch (java.util.concurrent.TimeoutException e) { |
| 158 | + throw new TimeoutException("waitForResponse: no matching response within " + timeout); |
| 159 | + } catch (InterruptedException e) { |
| 160 | + Thread.currentThread().interrupt(); |
| 161 | + throw new TimeoutException("waitForResponse: interrupted while waiting", e); |
| 162 | + } catch (ExecutionException e) { |
| 163 | + throw new RuntimeException("waitForResponse: listener failed", e.getCause()); |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | +} |
0 commit comments