From 7ca3574b1bec8e2d2094d2b1c4b97149e13f4530 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Wed, 11 Nov 2026 22:39:17 +0900 Subject: [PATCH 1/8] WebDriverBiDi: move isAlive() onto the interface --- .../java/org/archive/net/webdriver/LocalWebDriverBiDi.java | 4 +--- .../main/java/org/archive/net/webdriver/WebDriverBiDi.java | 5 +++++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java index cec07e09..df988df2 100644 --- a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java @@ -175,9 +175,7 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { return future; } - /** - * Returns true if the browser process is running and the WebDriver connection is still open. - */ + @Override public boolean isAlive() { return process.isAlive() && !webSocket.isInputClosed() && !webSocket.isOutputClosed(); } diff --git a/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java index 7dee12b8..272620bb 100644 --- a/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/WebDriverBiDi.java @@ -22,6 +22,11 @@ package org.archive.net.webdriver; public interface WebDriverBiDi { T module(Class moduleClass); + /** + * Returns true if the browser is running and the WebDriver connection is still open. + */ + boolean isAlive(); + default Browser browser() { return module(Browser.class); } From 7369ec2980e5a154a90d218544b1712c2329414e Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Wed, 11 Nov 2026 22:42:03 +0900 Subject: [PATCH 2/8] BrowserProcessor: move per-browser state into a nested Browser class --- .../crawler/processor/BrowserProcessor.java | 180 ++++++++++-------- .../processor/BrowserProcessorTest.java | 2 +- 2 files changed, 97 insertions(+), 85 deletions(-) diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index 560950e6..6c9e4bfb 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -86,7 +86,7 @@ public class BrowserProcessor extends Processor { protected final CrawlController crawlController; protected MitmProxy proxy; protected final FetchHTTP2 fetcher; - protected volatile LocalWebDriverBiDi webdriver; + protected Browser browser; protected final ApplicationEventPublisher eventPublisher; protected final Map pages = new ConcurrentHashMap<>(); protected final Map pageIdsByContext = new ConcurrentHashMap<>(); @@ -97,7 +97,6 @@ public class BrowserProcessor extends Processor { protected String executable; protected List options = List.of("--headless"); protected int concurrency = 20; - protected Semaphore semaphore; public BrowserProcessor(FetchHTTP2 fetcher, CrawlController crawlController, ApplicationEventPublisher eventPublisher, UriErrorLoggerModule uriErrorLoggerModule) { @@ -117,13 +116,7 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error stopping proxy server", e); } } - if (webdriver != null) { - try { - webdriver.close(); - } catch (Exception e) { - logger.log(ERROR, "Error closing WebDriverBiDi", e); - } - } + if (browser != null) browser.close(); } @Override @@ -141,7 +134,7 @@ public class BrowserProcessor extends Processor { @Override public void innerProcess(CrawlURI curi) { try { - semaphore.acquire(); + browser.tabs.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; @@ -149,7 +142,7 @@ public class BrowserProcessor extends Processor { try { visit(curi); } finally { - semaphore.release(); + browser.tabs.release(); } } @@ -179,7 +172,7 @@ public class BrowserProcessor extends Processor { private void visit(CrawlURI curi) { for (int attempt = 0; ; attempt++) { - LocalWebDriverBiDi driver = webdriver; + LocalWebDriverBiDi driver = browser.driver; try { visit(curi, driver); return; @@ -189,7 +182,7 @@ public class BrowserProcessor extends Processor { } catch (WebDriverException e) { if (attempt == 0 && !driver.isAlive()) { logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); - if (restartBrowser(driver)) continue; // retry once with the new browser + if (browser.restart(driver)) continue; // retry once with the new browser } logger.log(WARNING, "WebDriver exception visiting " + curi, e); return; @@ -197,31 +190,6 @@ public class BrowserProcessor extends Processor { } } - /** - * Replaces a dead browser with a freshly launched one. Threads that lose the race to restart - * still return true so they retry against the browser the winner launched. - * - * @return true if a live browser is now available, false if the restart failed or the - * processor is stopping - */ - private synchronized boolean restartBrowser(LocalWebDriverBiDi deadDriver) { - if (!isRunning) return false; - if (webdriver != deadDriver) return true; // another thread already restarted it - try { - deadDriver.close(); - } catch (Exception e) { - logger.log(WARNING, "Error closing dead browser", e); - } - try { - webdriver = createWebDriver(); - browserRestarts.incrementAndGet(); - return true; - } catch (Exception e) { - logger.log(ERROR, "Failed to restart browser", e); - return false; - } - } - private void visit(CrawlURI curi, LocalWebDriverBiDi driver) throws InterruptedException { String pageId = UUID.randomUUID().toString(); var tab = driver.browsingContext().create(BrowsingContext.CreateType.tab).context(); @@ -278,7 +246,6 @@ public class BrowserProcessor extends Processor { if (isRunning) return; super.start(); - semaphore = new Semaphore(concurrency); extractorChain.setProcessors(crawlController.getFetchChain().getProcessors().stream() .filter(processor -> processor instanceof Extractor).toList()); Path scratchDir = crawlController.getScratchDir().getFile().toPath(); @@ -300,57 +267,13 @@ public class BrowserProcessor extends Processor { throw new RuntimeException(e); } try { - this.webdriver = createWebDriver(); + browser = new Browser(); } catch (Exception e) { logger.log(ERROR, "Error starting browser", e); throw new RuntimeException(e); } } - private LocalWebDriverBiDi createWebDriver() throws Exception { - Path scratchDir = crawlController.getScratchDir().getFile().toPath(); - Path profileDir = scratchDir.resolve("profile"); - Files.createDirectories(profileDir); - - // Firefox doesn't seem to allow setting prefs via capabilities with bidi - // so drop them in user.js instead - Files.writeString(profileDir.resolve("user.js"), """ - // send localhost requests via the proxy too (for tests and local crawling) - user_pref('network.proxy.allow_hijacking_localhost', true); - - // disable downloads by setting to something that can't be created as a directory - user_pref('browser.download.dir', '/dev/null'); - user_pref('browser.download.folderList', 2); - """); - - int proxyPort = proxy.getPort(); - var alwaysMatch = Map.of("acceptInsecureCerts", true, - "proxy", new Session.ProxyConfiguration("manual", - "127.0.0.1:" + proxyPort, "127.0.0.1:" + proxyPort)); - - List> firstMatch = List.of( - Map.of("browserName", "chrome", - "goog:chromeOptions", Map.of( - "args", List.of("headless=new", "user-data-dir=" + profileDir, - "proxy-bypass-list=<-loopback>"), - "prefs", Map.of("download_restrictions", 3))), - // Fallback for other browsers - Map.of() - ); - var capabilities = new Session.CapabilitiesRequest(alwaysMatch, firstMatch); - - var driver = new LocalWebDriverBiDi(executable, options, capabilities, profileDir); - try { - driver.session().subscribe(List.of("browsingContext.contextCreated", - "network.beforeRequestSent"), null); - driver.on(Network.BeforeRequestSent.class, event -> handleBeforeRequestSent(driver, event)); - } catch (Exception e) { - driver.close(); - throw e; - } - return driver; - } - private void handleBeforeRequestSent(LocalWebDriverBiDi driver, Network.BeforeRequestSent event) { if (event.request().url().startsWith("data:") || !event.isBlocked()) return; List requestHeaders = event.request().headers(); @@ -586,6 +509,95 @@ public class BrowserProcessor extends Processor { } } + /** + * Launches a browser and restarts it if it dies. + */ + protected class Browser { + protected final Semaphore tabs = new Semaphore(concurrency); + protected volatile LocalWebDriverBiDi driver; + + Browser() throws Exception { + driver = createWebDriver(); + } + + /** + * Replaces a dead browser with a freshly launched one. Threads that lose the race to restart + * still return true so they retry against the browser the winner launched. + * + * @return true if a live browser is now available, false if the restart failed or the + * processor is stopping + */ + synchronized boolean restart(LocalWebDriverBiDi deadDriver) { + if (!isRunning) return false; + if (driver != deadDriver) return true; // another thread already restarted it + try { + deadDriver.close(); + } catch (Exception e) { + logger.log(WARNING, "Error closing dead browser", e); + } + try { + driver = createWebDriver(); + browserRestarts.incrementAndGet(); + return true; + } catch (Exception e) { + logger.log(ERROR, "Failed to restart browser", e); + return false; + } + } + + synchronized void close() { + try { + driver.close(); + } catch (Exception e) { + logger.log(ERROR, "Error closing WebDriverBiDi", e); + } + } + + private LocalWebDriverBiDi createWebDriver() throws Exception { + Path scratchDir = crawlController.getScratchDir().getFile().toPath(); + Path profileDir = scratchDir.resolve("profile"); + Files.createDirectories(profileDir); + + // Firefox doesn't seem to allow setting prefs via capabilities with bidi + // so drop them in user.js instead + Files.writeString(profileDir.resolve("user.js"), """ + // send localhost requests via the proxy too (for tests and local crawling) + user_pref('network.proxy.allow_hijacking_localhost', true); + + // disable downloads by setting to something that can't be created as a directory + user_pref('browser.download.dir', '/dev/null'); + user_pref('browser.download.folderList', 2); + """); + + int proxyPort = proxy.getPort(); + var alwaysMatch = Map.of("acceptInsecureCerts", true, + "proxy", new Session.ProxyConfiguration("manual", + "127.0.0.1:" + proxyPort, "127.0.0.1:" + proxyPort)); + + List> firstMatch = List.of( + Map.of("browserName", "chrome", + "goog:chromeOptions", Map.of( + "args", List.of("headless=new", "user-data-dir=" + profileDir, + "proxy-bypass-list=<-loopback>"), + "prefs", Map.of("download_restrictions", 3))), + // Fallback for other browsers + Map.of() + ); + var capabilities = new Session.CapabilitiesRequest(alwaysMatch, firstMatch); + + var driver = new LocalWebDriverBiDi(executable, options, capabilities, profileDir); + try { + driver.session().subscribe(List.of("browsingContext.contextCreated", + "network.beforeRequestSent"), null); + driver.on(Network.BeforeRequestSent.class, event -> handleBeforeRequestSent(driver, event)); + } catch (Exception e) { + driver.close(); + throw e; + } + return driver; + } + } + /** * A CrawlURI that's currently loaded as a page in a browser. */ diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index 3d3896c2..8fa58f60 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -105,7 +105,7 @@ class BrowserProcessorTest { @Test public void testBrowserRestart() throws IOException, InterruptedException { long restartsBefore = browserProcessor.browserRestarts.get(); - browserProcessor.webdriver.close(); // simulate the browser dying + browserProcessor.browser.driver.close(); // simulate the browser dying CrawlURI crawlURI = newCrawlURI(baseUrl); fetcher.process(crawlURI); From ad8e3fb51bff4b37562da4f1e11485134c7456f7 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Wed, 11 Nov 2026 22:44:25 +0900 Subject: [PATCH 3/8] BrowserProcessor: support several browsers --- .../crawler/processor/BrowserProcessor.java | 146 +++++++++++++----- .../processor/BrowserProcessorTest.java | 57 +++++-- 2 files changed, 154 insertions(+), 49 deletions(-) diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index 6c9e4bfb..0fd00747 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -62,7 +62,7 @@ import java.nio.file.Path; import java.time.Duration; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Semaphore; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; @@ -86,17 +86,18 @@ public class BrowserProcessor extends Processor { protected final CrawlController crawlController; protected MitmProxy proxy; protected final FetchHTTP2 fetcher; - protected Browser browser; + protected final List pool = new CopyOnWriteArrayList<>(); + private final Object tabsLock = new Object(); protected final ApplicationEventPublisher eventPublisher; protected final Map pages = new ConcurrentHashMap<>(); protected final Map pageIdsByContext = new ConcurrentHashMap<>(); protected final ProcessorChain extractorChain = new ProcessorChain(); protected final AtomicLong subresourcesRecorded = new AtomicLong(); - protected final AtomicLong browserRestarts = new AtomicLong(); protected List behaviors; protected String executable; protected List options = List.of("--headless"); protected int concurrency = 20; + protected List browsers = List.of("local"); public BrowserProcessor(FetchHTTP2 fetcher, CrawlController crawlController, ApplicationEventPublisher eventPublisher, UriErrorLoggerModule uriErrorLoggerModule) { @@ -116,7 +117,12 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error stopping proxy server", e); } } - if (browser != null) browser.close(); + synchronized (tabsLock) { + tabsLock.notifyAll(); + } + for (Browser browser : pool) { + browser.close(); + } } @Override @@ -134,15 +140,58 @@ public class BrowserProcessor extends Processor { @Override public void innerProcess(CrawlURI curi) { try { - browser.tabs.acquire(); + for (int attempt = 0; ; attempt++) { + Browser browser = acquireTabSlot(curi.getClassKey()); + if (browser == null) return; // stopping + LocalWebDriverBiDi driver = browser.driver; + try { + visit(curi, driver); + return; + } catch (WebDriverException e) { + if (attempt == 0 && !driver.isAlive()) { + logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); + if (browser.restart(driver)) continue; // retry once with the new browser + } + logger.log(WARNING, "WebDriver exception visiting " + curi, e); + return; + } finally { + releaseTabSlot(browser); + } + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return; } - try { - visit(curi); - } finally { - browser.tabs.release(); + } + + /** + * Waits for a browser with a free tab slot, preferring the one the queue key hashes to so that a site + * keeps the same browser's cookies and cache. + * + * @return the browser, or null if the processor is stopping + */ + private Browser acquireTabSlot(String queueKey) throws InterruptedException { + synchronized (tabsLock) { + while (isRunning) { + Browser browser = pool.get(Math.floorMod(Objects.hashCode(queueKey), pool.size())); + if (browser.openTabs >= concurrency) { + browser = pool.stream().filter(b -> b.openTabs < concurrency) + .min(Comparator.comparingInt(b -> b.openTabs)).orElse(null); + } + if (browser != null) { + browser.openTabs++; + browser.pagesVisited++; + return browser; + } + tabsLock.wait(); + } + return null; + } + } + + private void releaseTabSlot(Browser browser) { + synchronized (tabsLock) { + browser.openTabs--; + tabsLock.notifyAll(); } } @@ -163,33 +212,20 @@ public class BrowserProcessor extends Processor { builder.append(super.report()); builder.append(" Pages visited: ").append(getURICount()).append("\n"); builder.append(" Subresources recorded: ").append(subresourcesRecorded.get()).append("\n"); - builder.append(" Browser restarts: ").append(browserRestarts.get()).append("\n"); + synchronized (tabsLock) { + for (Browser browser : pool) { + builder.append(" Browser ").append(browser.id).append(": ") + .append(browser.openTabs).append(" open tabs, ") + .append(browser.pagesVisited).append(" pages visited, ") + .append(browser.restarts).append(" restarts\n"); + } + } for (var behavior : behaviors) { builder.append(behavior.report()); } return builder.toString(); } - private void visit(CrawlURI curi) { - for (int attempt = 0; ; attempt++) { - LocalWebDriverBiDi driver = browser.driver; - try { - visit(curi, driver); - return; - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } catch (WebDriverException e) { - if (attempt == 0 && !driver.isAlive()) { - logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); - if (browser.restart(driver)) continue; // retry once with the new browser - } - logger.log(WARNING, "WebDriver exception visiting " + curi, e); - return; - } - } - } - private void visit(CrawlURI curi, LocalWebDriverBiDi driver) throws InterruptedException { String pageId = UUID.randomUUID().toString(); var tab = driver.browsingContext().create(BrowsingContext.CreateType.tab).context(); @@ -244,6 +280,12 @@ public class BrowserProcessor extends Processor { public void start() { if (isRunning) return; + if (browsers.isEmpty()) throw new IllegalArgumentException("browsers must not be empty"); + for (String browser : browsers) { + if (!browser.equals("local")) { + throw new IllegalArgumentException("Unsupported browser '" + browser + "': only 'local' is supported"); + } + } super.start(); extractorChain.setProcessors(crawlController.getFetchChain().getProcessors().stream() @@ -266,8 +308,14 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error starting proxy server", e); throw new RuntimeException(e); } + pool.clear(); + for (int i = 0; i < browsers.size(); i++) { + pool.add(new Browser(i)); + } try { - browser = new Browser(); + for (Browser browser : pool) { + browser.launch(); + } } catch (Exception e) { logger.log(ERROR, "Error starting browser", e); throw new RuntimeException(e); @@ -362,12 +410,25 @@ public class BrowserProcessor extends Processor { } /** - * Maximum number of web pages that can be open in the browser at once. + * Maximum number of web pages that can be open in each browser at once. */ public void setConcurrency(int concurrency) { this.concurrency = concurrency; } + public List getBrowsers() { + return browsers; + } + + /** + * Browsers to open pages in, one per entry. The only supported value is currently {@code local}, which + * launches {@link #setExecutable(String) executable} on this machine. Pages from the same queue are opened in + * the same browser while it has a free tab, so that a site keeps one browser's cookies and cache. + */ + public void setBrowsers(List browsers) { + this.browsers = browsers; + } + /** * Records the request and response for a subresource the browser loads via the MITM proxy. */ @@ -510,13 +571,21 @@ public class BrowserProcessor extends Processor { } /** - * Launches a browser and restarts it if it dies. + * Launches a browser and restarts it if it dies. Tracks how many of its + * {@link #setConcurrency tab slots} are in use. */ protected class Browser { - protected final Semaphore tabs = new Semaphore(concurrency); + protected final int id; protected volatile LocalWebDriverBiDi driver; + protected int openTabs; // guarded by tabsLock + protected long pagesVisited; // guarded by tabsLock + protected volatile int restarts; - Browser() throws Exception { + Browser(int id) { + this.id = id; + } + + synchronized void launch() throws Exception { driver = createWebDriver(); } @@ -537,7 +606,7 @@ public class BrowserProcessor extends Processor { } try { driver = createWebDriver(); - browserRestarts.incrementAndGet(); + restarts++; return true; } catch (Exception e) { logger.log(ERROR, "Failed to restart browser", e); @@ -546,6 +615,7 @@ public class BrowserProcessor extends Processor { } synchronized void close() { + if (driver == null) return; try { driver.close(); } catch (Exception e) { @@ -555,7 +625,7 @@ public class BrowserProcessor extends Processor { private LocalWebDriverBiDi createWebDriver() throws Exception { Path scratchDir = crawlController.getScratchDir().getFile().toPath(); - Path profileDir = scratchDir.resolve("profile"); + Path profileDir = scratchDir.resolve("profile-" + id); Files.createDirectories(profileDir); // Firefox doesn't seem to allow setting prefs via capabilities with bidi diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index 8fa58f60..dd456e69 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -41,7 +41,6 @@ class BrowserProcessorTest { private static String baseUrl; private static volatile int serverRequests; private static ArrayList subrequests; - private static CrawlController crawlController; private final Set recorders = new HashSet<>(); @TempDir static Path tempDir; @@ -104,20 +103,42 @@ class BrowserProcessorTest { @Test public void testBrowserRestart() throws IOException, InterruptedException { - long restartsBefore = browserProcessor.browserRestarts.get(); - browserProcessor.browser.driver.close(); // simulate the browser dying + int restartsBefore = browserProcessor.pool.get(0).restarts; + browserProcessor.pool.get(0).driver.close(); // simulate the browser dying CrawlURI crawlURI = newCrawlURI(baseUrl); fetcher.process(crawlURI); assertEquals(200, crawlURI.getFetchStatus()); browserProcessor.innerProcess(crawlURI); - assertEquals(restartsBefore + 1, browserProcessor.browserRestarts.get(), + assertEquals(restartsBefore + 1, browserProcessor.pool.get(0).restarts, "browser should have been restarted"); assertTrue(crawlURI.getAnnotations().contains("browser"), "page should have been visited by the restarted browser"); } + @Test + public void testSeveralBrowsers() throws IOException, InterruptedException { + var processor = newBrowserProcessor("several", List.of("local", "local")); + processor.start(); + try { + // queue keys "b" and "a" hash to browsers 0 and 1 + visit(processor, "b"); + visit(processor, "a"); + assertEquals(1, processor.pool.get(0).pagesVisited); + assertEquals(1, processor.pool.get(1).pagesVisited); + + processor.pool.get(1).driver.close(); // simulate the browser dying + CrawlURI crawlURI = visit(processor, "a"); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited after the restart"); + assertEquals(0, processor.pool.get(0).restarts); + assertEquals(1, processor.pool.get(1).restarts); + } finally { + processor.stop(); + } + } + @Test public void testDownload() throws IOException, InterruptedException { CrawlURI crawlURI = newCrawlURI(baseUrl + "download.bin"); @@ -199,6 +220,15 @@ class BrowserProcessorTest { assertEquals(requestsBefore, serverRequests, "request should not have been forwarded"); } + private CrawlURI visit(BrowserProcessor processor, String queueKey) throws IOException, InterruptedException { + CrawlURI crawlURI = newCrawlURI(baseUrl); + crawlURI.setClassKey(queueKey); + fetcher.process(crawlURI); + assertEquals(200, crawlURI.getFetchStatus()); + processor.innerProcess(crawlURI); + return crawlURI; + } + private CrawlURI newCrawlURI(String uri) throws URIException { CrawlURI curi = new CrawlURI(UURIFactory.getInstance(uri)); Recorder recorder = new Recorder(tempDir.toFile(), "fetcher"); @@ -310,14 +340,18 @@ class BrowserProcessorTest { fetcher = new FetchHTTP2(new DefaultServerCache(), null); fetcher.setUserAgentProvider(new CrawlMetadata()); fetcher.start(); - crawlController = new CrawlController(); - crawlController.getScratchDir().setPath(tempDir.toString()); + subrequests = new ArrayList<>(); + browserProcessor = newBrowserProcessor("default", List.of("local")); + browserProcessor.start(); + } + + private static BrowserProcessor newBrowserProcessor(String name, List browsers) { + var crawlController = new CrawlController(); + crawlController.getScratchDir().setPath(tempDir.resolve(name).toString()); FetchChain fetchChain = new FetchChain(); fetchChain.setProcessors(List.of()); crawlController.setFetchChain(fetchChain); - subrequests = new ArrayList<>(); - DispositionChain dispositionChain = new DispositionChain(); dispositionChain.setProcessors(List.of(new Processor() { @Override @@ -331,9 +365,10 @@ class BrowserProcessorTest { } })); crawlController.setDispositionChain(dispositionChain); - browserProcessor = new BrowserProcessor(fetcher, crawlController, event -> {}, null); - browserProcessor.setExecutable(System.getProperty("browserExecutable")); - browserProcessor.start(); + var processor = new BrowserProcessor(fetcher, crawlController, event -> {}, null); + processor.setBrowsers(browsers); + processor.setExecutable(System.getProperty("browserExecutable")); + return processor; } @AfterAll From d7f82bce4da067fae8c16c91ae9aad27682d7c27 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Wed, 11 Nov 2026 22:47:42 +0900 Subject: [PATCH 4/8] BrowserProcessor: launch browsers in parallel and retry failed launches with backoff --- .../crawler/processor/BrowserProcessor.java | 154 +++++++++++++----- .../processor/BrowserProcessorTest.java | 47 ++++++ 2 files changed, 161 insertions(+), 40 deletions(-) diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index 0fd00747..ffc0d8cf 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -19,6 +19,7 @@ package org.archive.crawler.processor; +import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.commons.lang3.StringUtils; import org.archive.crawler.event.CrawlURIDispositionEvent; import org.archive.crawler.framework.CrawlController; @@ -61,8 +62,13 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; @@ -87,7 +93,8 @@ public class BrowserProcessor extends Processor { protected MitmProxy proxy; protected final FetchHTTP2 fetcher; protected final List pool = new CopyOnWriteArrayList<>(); - private final Object tabsLock = new Object(); + protected ScheduledExecutorService launcher; + protected final Object tabsLock = new Object(); protected final ApplicationEventPublisher eventPublisher; protected final Map pages = new ConcurrentHashMap<>(); protected final Map pageIdsByContext = new ConcurrentHashMap<>(); @@ -98,6 +105,7 @@ public class BrowserProcessor extends Processor { protected List options = List.of("--headless"); protected int concurrency = 20; protected List browsers = List.of("local"); + protected int minBrowsers = 1; public BrowserProcessor(FetchHTTP2 fetcher, CrawlController crawlController, ApplicationEventPublisher eventPublisher, UriErrorLoggerModule uriErrorLoggerModule) { @@ -110,6 +118,7 @@ public class BrowserProcessor extends Processor { public synchronized void stop() { if (!isRunning) return; super.stop(); + if (launcher != null) launcher.shutdownNow(); if (proxy != null) { try { proxy.stop(); @@ -148,11 +157,13 @@ public class BrowserProcessor extends Processor { visit(curi, driver); return; } catch (WebDriverException e) { - if (attempt == 0 && !driver.isAlive()) { + if (!driver.isAlive()) { logger.log(WARNING, "Browser died while visiting " + curi + ", restarting it", e); - if (browser.restart(driver)) continue; // retry once with the new browser + browser.restart(driver); + if (attempt == 0) continue; // retry once, possibly on another browser + } else { + logger.log(WARNING, "WebDriver exception visiting " + curi, e); } - logger.log(WARNING, "WebDriver exception visiting " + curi, e); return; } finally { releaseTabSlot(browser); @@ -173,8 +184,8 @@ public class BrowserProcessor extends Processor { synchronized (tabsLock) { while (isRunning) { Browser browser = pool.get(Math.floorMod(Objects.hashCode(queueKey), pool.size())); - if (browser.openTabs >= concurrency) { - browser = pool.stream().filter(b -> b.openTabs < concurrency) + if (!browser.hasFreeTabSlot()) { + browser = pool.stream().filter(Browser::hasFreeTabSlot) .min(Comparator.comparingInt(b -> b.openTabs)).orElse(null); } if (browser != null) { @@ -215,9 +226,14 @@ public class BrowserProcessor extends Processor { synchronized (tabsLock) { for (Browser browser : pool) { builder.append(" Browser ").append(browser.id).append(": ") + .append(browser.up ? "up, " : "down, ") .append(browser.openTabs).append(" open tabs, ") .append(browser.pagesVisited).append(" pages visited, ") - .append(browser.restarts).append(" restarts\n"); + .append(browser.restarts).append(" restarts"); + if (browser.lastFailure != null) { + builder.append(", last failure: ").append(browser.lastFailure); + } + builder.append("\n"); } } for (var behavior : behaviors) { @@ -286,6 +302,10 @@ public class BrowserProcessor extends Processor { throw new IllegalArgumentException("Unsupported browser '" + browser + "': only 'local' is supported"); } } + if (minBrowsers > browsers.size()) { + throw new IllegalArgumentException("minBrowsers is " + minBrowsers + " but only " + browsers.size() + + " browsers are configured"); + } super.start(); extractorChain.setProcessors(crawlController.getFetchChain().getProcessors().stream() @@ -308,17 +328,20 @@ public class BrowserProcessor extends Processor { logger.log(ERROR, "Error starting proxy server", e); throw new RuntimeException(e); } + launcher = Executors.newScheduledThreadPool(browsers.size(), new ThreadFactoryBuilder() + .setNameFormat("BrowserProcessor-launcher-%d").setDaemon(true).build()); pool.clear(); for (int i = 0; i < browsers.size(); i++) { pool.add(new Browser(i)); } - try { - for (Browser browser : pool) { - browser.launch(); - } - } catch (Exception e) { - logger.log(ERROR, "Error starting browser", e); - throw new RuntimeException(e); + CompletableFuture.allOf(pool.stream() + .map(browser -> CompletableFuture.runAsync(browser::launch, launcher)) + .toArray(CompletableFuture[]::new)).join(); + long up = pool.stream().filter(browser -> browser.up).count(); + if (up < minBrowsers) { + stop(); + throw new IllegalStateException("Only " + up + " of " + pool.size() + " browsers started but minBrowsers is " + + minBrowsers + ", see the log for the errors"); } } @@ -416,6 +439,18 @@ public class BrowserProcessor extends Processor { this.concurrency = concurrency; } + public int getMinBrowsers() { + return minBrowsers; + } + + /** + * Minimum number of browsers that must launch for the processor to start. Browsers that fail to launch, or + * crash and fail to relaunch, are retried in the background with an increasing delay. + */ + public void setMinBrowsers(int minBrowsers) { + this.minBrowsers = minBrowsers; + } + public List getBrowsers() { return browsers; } @@ -575,52 +610,75 @@ public class BrowserProcessor extends Processor { * {@link #setConcurrency tab slots} are in use. */ protected class Browser { + private static final long INITIAL_RETRY_DELAY_SECONDS = 30; + private static final long MAX_RETRY_DELAY_SECONDS = 600; protected final int id; protected volatile LocalWebDriverBiDi driver; + protected volatile boolean up; + protected volatile String lastFailure; + protected volatile int restarts; protected int openTabs; // guarded by tabsLock protected long pagesVisited; // guarded by tabsLock - protected volatile int restarts; + private long retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; // guarded by this Browser(int id) { this.id = id; } - synchronized void launch() throws Exception { - driver = createWebDriver(); + private boolean hasFreeTabSlot() { + return up && openTabs < concurrency; } /** - * Replaces a dead browser with a freshly launched one. Threads that lose the race to restart - * still return true so they retry against the browser the winner launched. - * - * @return true if a live browser is now available, false if the restart failed or the - * processor is stopping + * Launches the browser, or if that fails schedules another attempt after a delay. */ - synchronized boolean restart(LocalWebDriverBiDi deadDriver) { - if (!isRunning) return false; - if (driver != deadDriver) return true; // another thread already restarted it + void launch() { + LocalWebDriverBiDi newDriver; try { - deadDriver.close(); + newDriver = createWebDriver(); } catch (Exception e) { - logger.log(WARNING, "Error closing dead browser", e); + synchronized (this) { + if (!isRunning) return; + lastFailure = e.toString(); + logger.log(ERROR, "Failed to launch browser " + id + ", retrying in " + retryDelaySeconds + "s", e); + schedule(this::launch, retryDelaySeconds); + retryDelaySeconds = Math.min(retryDelaySeconds * 2, MAX_RETRY_DELAY_SECONDS); + } + return; } - try { - driver = createWebDriver(); - restarts++; - return true; - } catch (Exception e) { - logger.log(ERROR, "Failed to restart browser", e); - return false; + synchronized (this) { + if (!isRunning) { + closeQuietly(newDriver); + return; + } + driver = newDriver; + up = true; + lastFailure = null; + retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; + } + synchronized (tabsLock) { + tabsLock.notifyAll(); } } - synchronized void close() { - if (driver == null) return; - try { - driver.close(); - } catch (Exception e) { - logger.log(ERROR, "Error closing WebDriverBiDi", e); + /** + * Marks the browser down and launches a replacement, unless another thread already has. + */ + void restart(LocalWebDriverBiDi deadDriver) { + synchronized (this) { + if (driver != deadDriver || !up) return; + up = false; + restarts++; } + schedule(() -> { + closeQuietly(deadDriver); + launch(); + }, 0); + } + + synchronized void close() { + up = false; + if (driver != null) closeQuietly(driver); } private LocalWebDriverBiDi createWebDriver() throws Exception { @@ -668,6 +726,22 @@ public class BrowserProcessor extends Processor { } } + private void schedule(Runnable task, long delaySeconds) { + try { + launcher.schedule(task, delaySeconds, TimeUnit.SECONDS); + } catch (RejectedExecutionException e) { + // stopping + } + } + + private static void closeQuietly(LocalWebDriverBiDi driver) { + try { + driver.close(); + } catch (Exception e) { + logger.log(WARNING, "Error closing browser", e); + } + } + /** * A CrawlURI that's currently loaded as a page in a browser. */ diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index dd456e69..0153cf89 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -22,6 +22,7 @@ import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.zip.GZIPOutputStream; @@ -120,6 +121,7 @@ class BrowserProcessorTest { @Test public void testSeveralBrowsers() throws IOException, InterruptedException { var processor = newBrowserProcessor("several", List.of("local", "local")); + processor.setMinBrowsers(2); processor.start(); try { // queue keys "b" and "a" hash to browsers 0 and 1 @@ -132,6 +134,7 @@ class BrowserProcessorTest { CrawlURI crawlURI = visit(processor, "a"); assertTrue(crawlURI.getAnnotations().contains("browser"), "page should have been visited after the restart"); + awaitUp(processor, 1); assertEquals(0, processor.pool.get(0).restarts); assertEquals(1, processor.pool.get(1).restarts); } finally { @@ -139,6 +142,50 @@ class BrowserProcessorTest { } } + @Test + public void testStartWithBrowserThatFailsToLaunch() throws IOException, InterruptedException { + preventLaunch("one-fails", 1); + var processor = newBrowserProcessor("one-fails", List.of("local", "local")); + processor.start(); + try { + assertTrue(processor.pool.get(0).up); + assertFalse(processor.pool.get(1).up); + String report = processor.report(); + assertTrue(report.contains("Browser 1: down") && report.contains("FileAlreadyExistsException"), report); + + CrawlURI crawlURI = visit(processor, "a"); // hashes to browser 1 + assertTrue(crawlURI.getAnnotations().contains("browser")); + assertEquals(1, processor.pool.get(0).pagesVisited); + } finally { + processor.stop(); + } + } + + @Test + public void testStartFailsIfNoBrowserLaunches() throws IOException { + preventLaunch("none-start", 0); + preventLaunch("none-start", 1); + var processor = newBrowserProcessor("none-start", List.of("local", "local")); + assertThrows(IllegalStateException.class, processor::start); + assertFalse(processor.isRunning()); + } + + private static void awaitUp(BrowserProcessor processor, int browserId) throws InterruptedException { + synchronized (processor.tabsLock) { + while (!processor.pool.get(browserId).up) { + processor.tabsLock.wait(); + } + } + } + + /** + * Puts a file where the browser's profile directory should be so launching it fails. + */ + private static void preventLaunch(String processorName, int browserId) throws IOException { + Path scratchDir = Files.createDirectories(tempDir.resolve(processorName)); + Files.createFile(scratchDir.resolve("profile-" + browserId)); + } + @Test public void testDownload() throws IOException, InterruptedException { CrawlURI crawlURI = newCrawlURI(baseUrl + "download.bin"); From 9cefc32df072009c7164f0ce6b25eab4943c1f24 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Thu, 12 Nov 2026 00:15:04 +0900 Subject: [PATCH 5/8] LocalWebDriverBiDi: kill the browser if it stops answering --- .../net/webdriver/BrowsingContext.java | 11 ++++++ .../net/webdriver/LocalWebDriverBiDi.java | 27 ++++++++++++++ .../processor/BrowserProcessorTest.java | 36 +++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java b/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java index 7ddb1f48..b1c4b88a 100644 --- a/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java +++ b/commons/src/main/java/org/archive/net/webdriver/BrowsingContext.java @@ -19,6 +19,9 @@ package org.archive.net.webdriver; +import java.util.List; +import java.util.concurrent.CompletableFuture; + // https://w3c.github.io/webdriver-bidi/#module-browsingContext public interface BrowsingContext extends BiDiModule { CreateResult create(CreateType type); @@ -27,6 +30,8 @@ public interface BrowsingContext extends BiDiModule { void close(Context context); + CompletableFuture getTreeAsync(long maxDepth); + enum CreateType {tab, window} enum ReadinessState {none, interactive, complete} @@ -34,6 +39,12 @@ public interface BrowsingContext extends BiDiModule { record CreateResult(Context context) { } + record GetTreeResult(List contexts) { + } + + record Info(Context context, String url) { + } + record Load(Context context, Navigation navigation, long timestamp, String url) implements BiDiEvent { } diff --git a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java index df988df2..10c73d0e 100644 --- a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java @@ -180,6 +180,29 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { return process.isAlive() && !webSocket.isInputClosed() && !webSocket.isOutputClosed(); } + private boolean isResponsive() { + try { + // not session.status, as ChromeDriver answers that itself without asking the browser + browsingContext().getTreeAsync(0).get(5, TimeUnit.SECONDS); + return true; + } catch (TimeoutException e) { + return false; + } catch (ExecutionException e) { + return true; // it answered, even if with an error + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return true; + } + } + + private void kill() { + // ChromeDriver's browser is its child and would survive it, keeping the profile locked + process.descendants().forEach(ProcessHandle::destroyForcibly); + process.destroyForcibly(); + webSocket.abort(); + failPendingCommands(new WebDriverException("Browser stopped responding")); + } + private void failPendingCommands(Throwable failure) { for (Long id : commands.keySet()) { var future = commands.remove(id); @@ -231,6 +254,10 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { if (e.getCause() instanceof RuntimeException re) throw re; throw e; } catch (TimeoutException e) { + if (isAlive() && !isResponsive()) { + logger.log(System.Logger.Level.WARNING, "Browser stopped responding, killing it"); + kill(); + } throw new WebDriverTimeoutException(prefix + methodName + " took more than " + timeout + " seconds"); } } diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index 0153cf89..a69b56d0 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -118,6 +118,42 @@ class BrowserProcessorTest { "page should have been visited by the restarted browser"); } + @Test + public void testUnresponsiveBrowserRestart() throws IOException, InterruptedException { + var processor = newBrowserProcessor("unresponsive", List.of("local")); + processor.start(); + try { + String profileDir = tempDir.resolve("unresponsive/profile-0").toString(); + ProcessHandle browserProcess = ProcessHandle.current().children() + .filter(p -> p.info().commandLine().orElse("").contains(profileDir)) + .findFirst().orElseThrow(); + processor.setBehaviors(List.of(page -> { + if (browserProcess.isAlive()) { + suspend(browserProcess); + page.eval("() => 1"); + } + })); + + CrawlURI crawlURI = visit(processor, null); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited by the restarted browser"); + assertEquals(1, processor.pool.get(0).restarts); + assertFalse(browserProcess.isAlive(), "suspended browser should have been killed"); + } finally { + processor.stop(); + } + } + + private static void suspend(ProcessHandle process) { + var command = new ArrayList<>(List.of("kill", "-STOP", String.valueOf(process.pid()))); + process.descendants().forEach(p -> command.add(String.valueOf(p.pid()))); + try { + assertEquals(0, new ProcessBuilder(command).start().waitFor()); + } catch (IOException | InterruptedException e) { + throw new RuntimeException(e); + } + } + @Test public void testSeveralBrowsers() throws IOException, InterruptedException { var processor = newBrowserProcessor("several", List.of("local", "local")); From 0f8644fd654889c38b96179e00ba3cfd7feaaed8 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Thu, 12 Nov 2026 13:12:41 +0900 Subject: [PATCH 6/8] LocalWebDriverBiDi: make the command timeout configurable --- .../net/webdriver/LocalWebDriverBiDi.java | 17 ++++++++++++++--- .../crawler/processor/BrowserProcessorTest.java | 2 ++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java index 10c73d0e..ded6b59c 100644 --- a/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java +++ b/commons/src/main/java/org/archive/net/webdriver/LocalWebDriverBiDi.java @@ -32,6 +32,7 @@ import java.net.URI; import java.net.http.HttpClient; import java.net.http.WebSocket; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; @@ -58,6 +59,7 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { private final Thread shutdownHook; private final Object sendLock = new Object(); private CompletableFuture sendChain = CompletableFuture.completedFuture(null); + private volatile Duration commandTimeout = Duration.ofSeconds(30); private static final int LAUNCH_TIMEOUT_SECONDS = 60; private static final String[] BROWSERS = new String[]{ "firefox", "/Applications/Firefox.app/Contents/MacOS/firefox", "chromedriver"}; @@ -175,6 +177,14 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { return future; } + /** + * How long to wait for the reply to a command before throwing {@link WebDriverTimeoutException}. + * Commands that return a {@link CompletableFuture} aren't affected. + */ + public void setCommandTimeout(Duration commandTimeout) { + this.commandTimeout = commandTimeout; + } + @Override public boolean isAlive() { return process.isAlive() && !webSocket.isInputClosed() && !webSocket.isOutputClosed(); @@ -247,9 +257,10 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { parameterizedType.getActualTypeArguments()[0] instanceof Class typeClass) { yield future.thenApply(result -> BiDiJson.fromJson(result, typeClass)); } else { - int timeout = 30; + Duration timeout = commandTimeout; try { - yield BiDiJson.fromJson(future.get(timeout, TimeUnit.SECONDS), method.getReturnType()); + yield BiDiJson.fromJson(future.get(timeout.toMillis(), TimeUnit.MILLISECONDS), + method.getReturnType()); } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException re) throw re; throw e; @@ -258,7 +269,7 @@ public class LocalWebDriverBiDi implements WebDriverBiDi, Closeable { logger.log(System.Logger.Level.WARNING, "Browser stopped responding, killing it"); kill(); } - throw new WebDriverTimeoutException(prefix + methodName + " took more than " + timeout + " seconds"); + throw new WebDriverTimeoutException(prefix + methodName + " took more than " + timeout.toSeconds() + " seconds"); } } } diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index a69b56d0..4ab1cb23 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -24,6 +24,7 @@ import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Duration; import java.util.*; import java.util.zip.GZIPOutputStream; @@ -129,6 +130,7 @@ class BrowserProcessorTest { .findFirst().orElseThrow(); processor.setBehaviors(List.of(page -> { if (browserProcess.isAlive()) { + processor.pool.get(0).driver.setCommandTimeout(Duration.ofSeconds(2)); suspend(browserProcess); page.eval("() => 1"); } From 51668638b08b6db81d1966511421176546fbacfb Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Thu, 12 Nov 2026 15:29:43 +0900 Subject: [PATCH 7/8] BrowserProcessor: track each browser's state with an enum instead of a flag --- .../crawler/processor/BrowserProcessor.java | 17 +++++++++-------- .../crawler/processor/BrowserProcessorTest.java | 6 +++--- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index ffc0d8cf..7d5ffb2e 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -226,7 +226,7 @@ public class BrowserProcessor extends Processor { synchronized (tabsLock) { for (Browser browser : pool) { builder.append(" Browser ").append(browser.id).append(": ") - .append(browser.up ? "up, " : "down, ") + .append(browser.state.name().toLowerCase()).append(", ") .append(browser.openTabs).append(" open tabs, ") .append(browser.pagesVisited).append(" pages visited, ") .append(browser.restarts).append(" restarts"); @@ -337,7 +337,7 @@ public class BrowserProcessor extends Processor { CompletableFuture.allOf(pool.stream() .map(browser -> CompletableFuture.runAsync(browser::launch, launcher)) .toArray(CompletableFuture[]::new)).join(); - long up = pool.stream().filter(browser -> browser.up).count(); + long up = pool.stream().filter(browser -> browser.state == Browser.State.UP).count(); if (up < minBrowsers) { stop(); throw new IllegalStateException("Only " + up + " of " + pool.size() + " browsers started but minBrowsers is " @@ -612,9 +612,10 @@ public class BrowserProcessor extends Processor { protected class Browser { private static final long INITIAL_RETRY_DELAY_SECONDS = 30; private static final long MAX_RETRY_DELAY_SECONDS = 600; + protected enum State { UP, DOWN } protected final int id; protected volatile LocalWebDriverBiDi driver; - protected volatile boolean up; + protected volatile State state = State.DOWN; protected volatile String lastFailure; protected volatile int restarts; protected int openTabs; // guarded by tabsLock @@ -626,7 +627,7 @@ public class BrowserProcessor extends Processor { } private boolean hasFreeTabSlot() { - return up && openTabs < concurrency; + return state == State.UP && openTabs < concurrency; } /** @@ -652,7 +653,7 @@ public class BrowserProcessor extends Processor { return; } driver = newDriver; - up = true; + state = State.UP; lastFailure = null; retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; } @@ -666,8 +667,8 @@ public class BrowserProcessor extends Processor { */ void restart(LocalWebDriverBiDi deadDriver) { synchronized (this) { - if (driver != deadDriver || !up) return; - up = false; + if (driver != deadDriver || state != State.UP) return; + state = State.DOWN; restarts++; } schedule(() -> { @@ -677,7 +678,7 @@ public class BrowserProcessor extends Processor { } synchronized void close() { - up = false; + state = State.DOWN; if (driver != null) closeQuietly(driver); } diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index 4ab1cb23..a2c42955 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -186,8 +186,8 @@ class BrowserProcessorTest { var processor = newBrowserProcessor("one-fails", List.of("local", "local")); processor.start(); try { - assertTrue(processor.pool.get(0).up); - assertFalse(processor.pool.get(1).up); + assertEquals(BrowserProcessor.Browser.State.UP, processor.pool.get(0).state); + assertEquals(BrowserProcessor.Browser.State.DOWN, processor.pool.get(1).state); String report = processor.report(); assertTrue(report.contains("Browser 1: down") && report.contains("FileAlreadyExistsException"), report); @@ -210,7 +210,7 @@ class BrowserProcessorTest { private static void awaitUp(BrowserProcessor processor, int browserId) throws InterruptedException { synchronized (processor.tabsLock) { - while (!processor.pool.get(browserId).up) { + while (processor.pool.get(browserId).state != BrowserProcessor.Browser.State.UP) { processor.tabsLock.wait(); } } From dc070b4af12baa3bd930cc69b3adc0f0b744f878 Mon Sep 17 00:00:00 2001 From: Alex Osborne Date: Thu, 12 Nov 2026 15:32:13 +0900 Subject: [PATCH 8/8] BrowserProcessor: close idle browsers and relaunch them when a page needs one Many small jobs in one JVM would otherwise each hold browsers open for as long as the job runs or sits paused. --- .../crawler/processor/BrowserProcessor.java | 57 ++++++++++++++++++- .../processor/BrowserProcessorTest.java | 32 +++++++++-- 2 files changed, 82 insertions(+), 7 deletions(-) diff --git a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java index 7d5ffb2e..3791e3f2 100644 --- a/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java +++ b/engine/src/main/java/org/archive/crawler/processor/BrowserProcessor.java @@ -106,6 +106,7 @@ public class BrowserProcessor extends Processor { protected int concurrency = 20; protected List browsers = List.of("local"); protected int minBrowsers = 1; + protected int browserIdleTimeoutSeconds = 300; public BrowserProcessor(FetchHTTP2 fetcher, CrawlController crawlController, ApplicationEventPublisher eventPublisher, UriErrorLoggerModule uriErrorLoggerModule) { @@ -184,11 +185,15 @@ public class BrowserProcessor extends Processor { synchronized (tabsLock) { while (isRunning) { Browser browser = pool.get(Math.floorMod(Objects.hashCode(queueKey), pool.size())); - if (!browser.hasFreeTabSlot()) { + if (browser.state == Browser.State.IDLE) browser.wake(); + if (browser.state != Browser.State.WAKING && !browser.hasFreeTabSlot()) { browser = pool.stream().filter(Browser::hasFreeTabSlot) .min(Comparator.comparingInt(b -> b.openTabs)).orElse(null); + if (browser == null) { + pool.stream().filter(b -> b.state == Browser.State.IDLE).findFirst().ifPresent(Browser::wake); + } } - if (browser != null) { + if (browser != null && browser.hasFreeTabSlot()) { browser.openTabs++; browser.pagesVisited++; return browser; @@ -202,6 +207,7 @@ public class BrowserProcessor extends Processor { private void releaseTabSlot(Browser browser) { synchronized (tabsLock) { browser.openTabs--; + if (browser.openTabs == 0) browser.idleSince = System.nanoTime(); tabsLock.notifyAll(); } } @@ -343,6 +349,11 @@ public class BrowserProcessor extends Processor { throw new IllegalStateException("Only " + up + " of " + pool.size() + " browsers started but minBrowsers is " + minBrowsers + ", see the log for the errors"); } + if (browserIdleTimeoutSeconds > 0) { + long checkSeconds = Math.min(browserIdleTimeoutSeconds, 60); + launcher.scheduleWithFixedDelay(() -> pool.forEach(Browser::closeIfIdle), + checkSeconds, checkSeconds, TimeUnit.SECONDS); + } } private void handleBeforeRequestSent(LocalWebDriverBiDi driver, Network.BeforeRequestSent event) { @@ -451,6 +462,18 @@ public class BrowserProcessor extends Processor { this.minBrowsers = minBrowsers; } + public int getBrowserIdleTimeoutSeconds() { + return browserIdleTimeoutSeconds; + } + + /** + * Closes a browser that has had no open pages for at least this many seconds, and launches it again when a + * page needs it. Zero keeps browsers open until the processor stops. + */ + public void setBrowserIdleTimeoutSeconds(int browserIdleTimeoutSeconds) { + this.browserIdleTimeoutSeconds = browserIdleTimeoutSeconds; + } + public List getBrowsers() { return browsers; } @@ -612,7 +635,7 @@ public class BrowserProcessor extends Processor { protected class Browser { private static final long INITIAL_RETRY_DELAY_SECONDS = 30; private static final long MAX_RETRY_DELAY_SECONDS = 600; - protected enum State { UP, DOWN } + protected enum State { UP, IDLE, WAKING, DOWN } protected final int id; protected volatile LocalWebDriverBiDi driver; protected volatile State state = State.DOWN; @@ -620,6 +643,7 @@ public class BrowserProcessor extends Processor { protected volatile int restarts; protected int openTabs; // guarded by tabsLock protected long pagesVisited; // guarded by tabsLock + private volatile long idleSince; private long retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; // guarded by this Browser(int id) { @@ -640,11 +664,15 @@ public class BrowserProcessor extends Processor { } catch (Exception e) { synchronized (this) { if (!isRunning) return; + state = State.DOWN; lastFailure = e.toString(); logger.log(ERROR, "Failed to launch browser " + id + ", retrying in " + retryDelaySeconds + "s", e); schedule(this::launch, retryDelaySeconds); retryDelaySeconds = Math.min(retryDelaySeconds * 2, MAX_RETRY_DELAY_SECONDS); } + synchronized (tabsLock) { + tabsLock.notifyAll(); + } return; } synchronized (this) { @@ -653,6 +681,7 @@ public class BrowserProcessor extends Processor { return; } driver = newDriver; + idleSince = System.nanoTime(); state = State.UP; lastFailure = null; retryDelaySeconds = INITIAL_RETRY_DELAY_SECONDS; @@ -677,6 +706,28 @@ public class BrowserProcessor extends Processor { }, 0); } + /** + * Launches the browser again after it was closed for being idle. + */ + synchronized void wake() { + if (state != State.IDLE) return; + state = State.WAKING; + schedule(this::launch, 0); + } + + void closeIfIdle() { + LocalWebDriverBiDi idleDriver; + synchronized (tabsLock) { + synchronized (this) { + if (state != State.UP || openTabs > 0 || System.nanoTime() - idleSince + < TimeUnit.SECONDS.toNanos(browserIdleTimeoutSeconds)) return; + state = State.IDLE; + idleDriver = driver; + } + } + closeQuietly(idleDriver); + } + synchronized void close() { state = State.DOWN; if (driver != null) closeQuietly(driver); diff --git a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java index a2c42955..bbe82591 100644 --- a/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java +++ b/engine/src/test/java/org/archive/crawler/processor/BrowserProcessorTest.java @@ -26,6 +26,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.*; +import java.util.concurrent.TimeUnit; import java.util.zip.GZIPOutputStream; import static java.lang.System.Logger.Level.DEBUG; @@ -124,10 +125,7 @@ class BrowserProcessorTest { var processor = newBrowserProcessor("unresponsive", List.of("local")); processor.start(); try { - String profileDir = tempDir.resolve("unresponsive/profile-0").toString(); - ProcessHandle browserProcess = ProcessHandle.current().children() - .filter(p -> p.info().commandLine().orElse("").contains(profileDir)) - .findFirst().orElseThrow(); + ProcessHandle browserProcess = browserProcess("unresponsive", 0); processor.setBehaviors(List.of(page -> { if (browserProcess.isAlive()) { processor.pool.get(0).driver.setCommandTimeout(Duration.ofSeconds(2)); @@ -146,6 +144,32 @@ class BrowserProcessorTest { } } + @Test + public void testIdleBrowserIsClosedAndRelaunched() throws Exception { + var processor = newBrowserProcessor("idle", List.of("local")); + processor.setBrowserIdleTimeoutSeconds(1); + processor.start(); + try { + browserProcess("idle", 0).onExit().get(10, TimeUnit.SECONDS); + assertEquals(BrowserProcessor.Browser.State.IDLE, processor.pool.get(0).state); + + CrawlURI crawlURI = visit(processor, null); + assertTrue(crawlURI.getAnnotations().contains("browser"), + "page should have been visited by the relaunched browser"); + assertEquals(0, processor.pool.get(0).restarts); + assertNull(processor.pool.get(0).lastFailure); + } finally { + processor.stop(); + } + } + + private static ProcessHandle browserProcess(String processorName, int browserId) { + String profileDir = tempDir.resolve(processorName + "/profile-" + browserId).toString(); + return ProcessHandle.current().children() + .filter(p -> p.info().commandLine().orElse("").contains(profileDir)) + .findFirst().orElseThrow(); + } + private static void suspend(ProcessHandle process) { var command = new ArrayList<>(List.of("kill", "-STOP", String.valueOf(process.pid()))); process.descendants().forEach(p -> command.add(String.valueOf(p.pid())));