Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

improve resource cleanup and lifecycle management

L62aa9009573e
diff --git a/handlers.go b/handlers.go
index a240bef6..1adb60c9 100644
--- a/handlers.go
+++ b/handlers.go
@@ -180,6 +180,7 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
URL string `json:"url"`
NewTab bool `json:"newTab"`
WaitTitle float64 `json:"waitTitle"` // seconds to wait for title (default 2, max 30)
+ Timeout float64 `json:"timeout"` // per-request navigate timeout in seconds (default: BRIDGE_NAV_TIMEOUT)
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
jsonErr(w, 400, fmt.Errorf("decode: %w", err))
@@ -199,6 +200,15 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
titleWait = time.Duration(req.WaitTitle * float64(time.Second))
}
+ // Per-request navigate timeout (default: global navigateTimeout, max 120s).
+ navTimeout := navigateTimeout
+ if req.Timeout > 0 {
+ if req.Timeout > 120 {
+ req.Timeout = 120
+ }
+ navTimeout = time.Duration(req.Timeout * float64(time.Second))
+ }
+
if req.NewTab {
newTargetID, newCtx, _, err := b.CreateTab(req.URL)
if err != nil {
@@ -206,7 +216,7 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(newCtx, navigateTimeout)
+ tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
@@ -224,7 +234,7 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
return
}
- tCtx, tCancel := context.WithTimeout(ctx, navigateTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, navTimeout)
defer tCancel()
go cancelOnClientDone(r.Context(), tCancel)
@@ -319,5 +329,20 @@ func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {
}
}
+// ── POST /shutdown ─────────────────────────────────────────
+
+func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {
+ return func(w http.ResponseWriter, r *http.Request) {
+ slog.Info("shutdown requested via API")
+ jsonResp(w, 200, map[string]any{"status": "shutting down"})
+
+ // Trigger shutdown in background so the response gets sent first.
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ shutdownFn()
+ }()
+ }
+}
+
// Shared helpers (jsonResp, jsonErr, cancelOnClientDone, waitForTitle)
// are defined in middleware.go and cdp.go respectively.
diff --git a/main.go b/main.go
index f940f99e..4193563f 100644
--- a/main.go
+++ b/main.go
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"os/signal"
+ "sync"
"syscall"
"github.com/chromedp/cdproto/emulation"
@@ -50,6 +51,15 @@ func main() {
slog.Error("cannot create profile dir", "err", err)
os.Exit(1)
}
+
+ // Remove stale Chrome lock files from unclean shutdowns.
+ for _, lockName := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
+ lockPath := fmt.Sprintf("%s/%s", profileDir, lockName)
+ if err := os.Remove(lockPath); err == nil {
+ slog.Warn("removed stale lock", "file", lockName)
+ }
+ }
+
slog.Info("launching Chrome", "profile", profileDir, "headless", headless)
opts := []chromedp.ExecAllocatorOption{
@@ -102,10 +112,10 @@ func main() {
markCleanExit()
bridge.allocCtx, allocCancel = chromedp.NewExecAllocator(context.Background(), opts...)
}
- defer allocCancel()
+ // allocCancel and browserCancel are called explicitly during shutdown
+ // (both signal and /shutdown endpoint) — not deferred here.
browserCtx, browserCancel := chromedp.NewContext(bridge.allocCtx)
- defer browserCancel()
// Inject stealth script with a session-stable seed (stays constant across page loads)
stealthSeed := rand.Intn(1000000000)
@@ -171,20 +181,39 @@ func main() {
srv := &http.Server{Addr: ":" + port, Handler: loggingMiddleware(corsMiddleware(authMiddleware(mux)))}
- // Graceful shutdown
+ // Shutdown orchestration — used by both signal handler and /shutdown endpoint.
+ shutdownOnce := &sync.Once{}
+ doShutdown := func() {
+ shutdownOnce.Do(func() {
+ slog.Info("shutting down, saving state...")
+ cleanupCancel()
+ bridge.SaveState()
+ markCleanExit()
+
+ // Shut down HTTP server first so no new requests come in.
+ shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), shutdownTimeout)
+ defer shutdownDone()
+ if err := srv.Shutdown(shutdownCtx); err != nil {
+ slog.Error("shutdown http", "err", err)
+ }
+
+ // Explicitly close Chrome by canceling the browser and allocator contexts.
+ // This sends CDP Browser.close and kills the Chrome process.
+ browserCancel()
+ allocCancel()
+ slog.Info("chrome closed")
+ })
+ }
+
+ // Wire up /shutdown endpoint (requires auth like all other endpoints).
+ mux.HandleFunc("POST /shutdown", bridge.handleShutdown(doShutdown))
+
+ // Signal handler.
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
- slog.Info("shutting down, saving state...")
- cleanupCancel()
- bridge.SaveState()
- markCleanExit()
- shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), shutdownTimeout)
- defer shutdownDone()
- if err := srv.Shutdown(shutdownCtx); err != nil {
- slog.Error("shutdown", "err", err)
- }
+ doShutdown()
}()
slog.Info("🦀 PINCH! PINCH!", "port", port, "cdp", cdpURL)