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.
This commit is contained in:
Alex Osborne committed 2026-11-12 15:47:09 +09:00
1 parent 51668638b0
commit dc070b4af1
2 files changed
+82 -7

No files matched your search

@@ -106,6 +106,7 @@ public class BrowserProcessor extends Processor {
protected int concurrency = 20;
protected List<String> 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<String> 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);
@@ -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())));