Skip to content

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

refactor: extract shared proxy, add OrchestratorAware, cap backoff, align routes

Djain91220d57f406795
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 6f9ac5d0..8788601d 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -18,6 +18,7 @@ import (
"github.com/pinchtab/pinchtab/internal/handlers"
"github.com/pinchtab/pinchtab/internal/orchestrator"
"github.com/pinchtab/pinchtab/internal/profiles"
+ "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
@@ -73,10 +74,7 @@ func runDashboard(cfg *config.RuntimeConfig) {
slog.Warn("unknown strategy, falling back to default", "strategy", cfg.Strategy, "err", err)
} else {
// Inject orchestrator dependency.
- type orchSetter interface {
- SetOrchestrator(o *orchestrator.Orchestrator)
- }
- if setter, ok := strat.(orchSetter); ok {
+ if setter, ok := strat.(strategy.OrchestratorAware); ok {
setter.SetOrchestrator(orch)
}
strat.RegisterRoutes(mux)
@@ -218,69 +216,6 @@ func runDashboard(cfg *config.RuntimeConfig) {
}
}
-// proxyRequest forwards an HTTP request to a target URL.
-// For WebSocket upgrades (screencast), it does a WebSocket proxy.
-func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
- if r.URL.RawQuery != "" {
- targetURL += "?" + r.URL.RawQuery
- }
-
- if isWebSocketUpgrade(r) {
- handlers.ProxyWebSocket(w, r, targetURL)
- return
- }
-
- client := &http.Client{Timeout: 30 * time.Second}
- proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
- return
- }
-
- for k, vv := range r.Header {
- for _, v := range vv {
- proxyReq.Header.Add(k, v)
- }
- }
-
- resp, err := client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for k, vv := range resp.Header {
- for _, v := range vv {
- w.Header().Add(k, v)
- }
- }
- w.WriteHeader(resp.StatusCode)
-
- buf := make([]byte, 32*1024)
- for {
- n, err := resp.Body.Read(buf)
- if n > 0 {
- _, _ = w.Write(buf[:n])
- if f, ok := w.(http.Flusher); ok {
- f.Flush()
- }
- }
- if err != nil {
- break
- }
- }
-}
-
-func isWebSocketUpgrade(r *http.Request) bool {
- for _, v := range r.Header["Upgrade"] {
- if strings.EqualFold(v, "websocket") {
- return true
- }
- }
- return false
-}
-
// periodicHealthCheck logs instance and Chrome process status every 30 seconds
func periodicHealthCheck(orch *orchestrator.Orchestrator) {
ticker := time.NewTicker(30 * time.Second)
@@ -327,7 +262,7 @@ func registerDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
web.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxyRequest(w, r, target+"/tabs")
+ proxy.HTTP(w, r, target+"/tabs")
})
proxyEndpoints := []string{
@@ -349,7 +284,7 @@ func registerDefaultProxyRoutes(mux *http.ServeMux, orch *orchestrator.Orchestra
return
}
path := r.URL.Path
- proxyRequest(w, r, target+path)
+ proxy.HTTP(w, r, target+path)
})
}
}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
new file mode 100644
index 00000000..1829014d
--- /dev/null
+++ b/internal/proxy/proxy.go
@@ -0,0 +1,82 @@
+// Package proxy provides a shared HTTP reverse-proxy helper used by
+// strategies and the dashboard fallback routes. It consolidates the
+// previously duplicated proxyHTTP / proxyRequest functions into one
+// place with a shared http.Client and WebSocket upgrade support.
+package proxy
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+// DefaultClient is the shared HTTP client for proxy requests.
+// A 60-second timeout accommodates lazy Chrome initialization (8-20s)
+// and tab navigation (up to 60s for NavigateTimeout in bridge config).
+var DefaultClient = &http.Client{Timeout: 60 * time.Second}
+
+// HTTP forwards an HTTP request to targetURL, streaming the response
+// back to w. If the request is a WebSocket upgrade, it delegates to
+// handlers.ProxyWebSocket instead.
+func HTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
+ if r.URL.RawQuery != "" {
+ targetURL += "?" + r.URL.RawQuery
+ }
+
+ if isWebSocketUpgrade(r) {
+ handlers.ProxyWebSocket(w, r, targetURL)
+ return
+ }
+
+ proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
+ return
+ }
+ for k, vv := range r.Header {
+ for _, v := range vv {
+ proxyReq.Header.Add(k, v)
+ }
+ }
+
+ resp, err := DefaultClient.Do(proxyReq)
+ if err != nil {
+ web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ return
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ for k, vv := range resp.Header {
+ for _, v := range vv {
+ w.Header().Add(k, v)
+ }
+ }
+ w.WriteHeader(resp.StatusCode)
+
+ buf := make([]byte, 32*1024)
+ for {
+ n, readErr := resp.Body.Read(buf)
+ if n > 0 {
+ _, _ = w.Write(buf[:n])
+ if f, ok := w.(http.Flusher); ok {
+ f.Flush()
+ }
+ }
+ if readErr != nil {
+ break
+ }
+ }
+}
+
+func isWebSocketUpgrade(r *http.Request) bool {
+ for _, v := range r.Header["Upgrade"] {
+ if strings.EqualFold(v, "websocket") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go
new file mode 100644
index 00000000..3318a55f
--- /dev/null
+++ b/internal/proxy/proxy_test.go
@@ -0,0 +1,118 @@
+package proxy
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func fakeBridge(t *testing.T) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "proxied": true,
+ "path": r.URL.Path,
+ "query": r.URL.RawQuery,
+ })
+ }))
+}
+
+func TestHTTP_ForwardsRequest(t *testing.T) {
+ srv := fakeBridge(t)
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/snapshot", nil)
+ rec := httptest.NewRecorder()
+ HTTP(rec, req, srv.URL+"/snapshot")
+
+ if rec.Code != 200 {
+ t.Errorf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var resp map[string]any
+ _ = json.Unmarshal(rec.Body.Bytes(), &resp)
+ if resp["path"] != "/snapshot" {
+ t.Errorf("expected path /snapshot, got %v", resp["path"])
+ }
+}
+
+func TestHTTP_ForwardsQueryParams(t *testing.T) {
+ srv := fakeBridge(t)
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/screenshot?raw=true", nil)
+ rec := httptest.NewRecorder()
+ HTTP(rec, req, srv.URL+"/screenshot")
+
+ if rec.Code != 200 {
+ t.Errorf("expected 200, got %d", rec.Code)
+ }
+
+ var resp map[string]any
+ _ = json.Unmarshal(rec.Body.Bytes(), &resp)
+ if resp["query"] != "raw=true" {
+ t.Errorf("expected query raw=true, got %v", resp["query"])
+ }
+}
+
+func TestHTTP_UnreachableReturns502(t *testing.T) {
+ req := httptest.NewRequest("GET", "/snapshot", nil)
+ rec := httptest.NewRecorder()
+ HTTP(rec, req, "http://localhost:1/snapshot")
+
+ if rec.Code != 502 {
+ t.Errorf("expected 502, got %d", rec.Code)
+ }
+}
+
+func TestHTTP_CopiesResponseHeaders(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Custom", "test-value")
+ w.WriteHeader(201)
+ }))
+ defer srv.Close()
+
+ req := httptest.NewRequest("GET", "/test", nil)
+ rec := httptest.NewRecorder()
+ HTTP(rec, req, srv.URL+"/test")
+
+ if rec.Code != 201 {
+ t.Errorf("expected 201, got %d", rec.Code)
+ }
+ if rec.Header().Get("X-Custom") != "test-value" {
+ t.Errorf("expected X-Custom header, got %q", rec.Header().Get("X-Custom"))
+ }
+}
+
+func TestHTTP_UsesSharedClient(t *testing.T) {
+ if DefaultClient == nil {
+ t.Fatal("DefaultClient should not be nil")
+ }
+ if DefaultClient.Timeout != 60*1e9 { // 60 seconds in nanoseconds
+ t.Errorf("expected 60s timeout, got %s", DefaultClient.Timeout)
+ }
+}
+
+func TestIsWebSocketUpgrade(t *testing.T) {
+ tests := []struct {
+ name string
+ header http.Header
+ want bool
+ }{
+ {"no upgrade", http.Header{}, false},
+ {"websocket", http.Header{"Upgrade": {"websocket"}}, true},
+ {"WebSocket", http.Header{"Upgrade": {"WebSocket"}}, true},
+ {"other", http.Header{"Upgrade": {"h2c"}}, false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ r := httptest.NewRequest("GET", "/", nil)
+ r.Header = tt.header
+ if got := isWebSocketUpgrade(r); got != tt.want {
+ t.Errorf("isWebSocketUpgrade() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/strategy/autorestart/autorestart.go b/internal/strategy/autorestart/autorestart.go
index 616adb87..f23fe293 100644
--- a/internal/strategy/autorestart/autorestart.go
+++ b/internal/strategy/autorestart/autorestart.go
@@ -18,6 +18,7 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -25,6 +26,7 @@ import (
const (
defaultMaxRestarts = 3
defaultInitBackoff = 2 * time.Second
+ defaultMaxBackoff = 60 * time.Second
defaultStableAfter = 5 * time.Minute
defaultProfileName = "default"
healthPollInterval = 500 * time.Millisecond
@@ -41,6 +43,7 @@ func init() {
type AutorestartConfig struct {
MaxRestarts int // Max consecutive restarts before giving up (0 = use default 3)
InitBackoff time.Duration // Initial backoff between restarts (0 = use default 2s)
+ MaxBackoff time.Duration // Maximum backoff cap (0 = use default 60s)
StableAfter time.Duration // Reset counter after running this long (0 = use default 5m)
ProfileName string // Profile to launch (empty = "default")
Headless bool // Chrome headless mode
@@ -81,6 +84,9 @@ func New(cfg AutorestartConfig) *Strategy {
if cfg.InitBackoff <= 0 {
cfg.InitBackoff = defaultInitBackoff
}
+ if cfg.MaxBackoff <= 0 {
+ cfg.MaxBackoff = defaultMaxBackoff
+ }
if cfg.StableAfter <= 0 {
cfg.StableAfter = defaultStableAfter
}
@@ -140,17 +146,14 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
s.orch.RegisterHandlers(mux)
shorthandRoutes := []string{
- "POST /navigate", "GET /navigate",
"GET /snapshot", "GET /screenshot", "GET /text",
- "GET /pdf", "POST /pdf",
- "POST /action", "POST /actions", "POST /evaluate",
- "POST /find",
+ "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
"GET /download", "POST /upload",
- "POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /stealth/status", "POST /fingerprint/rotate",
"GET /screencast", "GET /screencast/tabs",
- "POST /macro",
+ "POST /find", "POST /macro",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToManaged)
@@ -260,6 +263,9 @@ func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {
count := s.restartCount
maxRestarts := s.config.MaxRestarts
backoff := s.config.InitBackoff * time.Duration(1<<uint(count-1))
+ if backoff > s.config.MaxBackoff {
+ backoff = s.config.MaxBackoff
+ }
s.mu.Unlock()
if count > maxRestarts {
@@ -394,7 +400,7 @@ func (s *Strategy) proxyToManaged(w http.ResponseWriter, r *http.Request) {
web.Error(w, 503, err)
return
}
- proxyHTTP(w, r, target+r.URL.Path)
+ proxy.HTTP(w, r, target+r.URL.Path)
}
// ensureRunning returns the URL of the managed instance if running.
@@ -414,56 +420,9 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxyHTTP(w, r, target+"/tabs")
+ proxy.HTTP(w, r, target+"/tabs")
}
func (s *Strategy) handleStatus(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, s.State())
}
-
-// proxyHTTP forwards a request to the target URL.
-func proxyHTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
- if r.URL.RawQuery != "" {
- targetURL += "?" + r.URL.RawQuery
- }
-
- client := &http.Client{Timeout: 60 * time.Second}
- proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
- return
- }
- for k, vv := range r.Header {
- for _, v := range vv {
- proxyReq.Header.Add(k, v)
- }
- }
-
- resp, err := client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for k, vv := range resp.Header {
- for _, v := range vv {
- w.Header().Add(k, v)
- }
- }
- w.WriteHeader(resp.StatusCode)
-
- buf := make([]byte, 32*1024)
- for {
- n, readErr := resp.Body.Read(buf)
- if n > 0 {
- _, _ = w.Write(buf[:n])
- if f, ok := w.(http.Flusher); ok {
- f.Flush()
- }
- }
- if readErr != nil {
- break
- }
- }
-}
diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.go
index 27e62150..67645425 100644
--- a/internal/strategy/autorestart/autorestart_test.go
+++ b/internal/strategy/autorestart/autorestart_test.go
@@ -12,6 +12,7 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/proxy"
)
// fakeBridge creates a test server that mimics a bridge instance.
@@ -314,7 +315,7 @@ func TestStrategy_HandleTabs_NoInstances(t *testing.T) {
req := httptest.NewRequest("GET", "/tabs", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/tabs")
+ proxy.HTTP(rec, req, srv.URL+"/tabs")
if rec.Code != 200 {
t.Errorf("expected 200, got %d", rec.Code)
@@ -327,7 +328,7 @@ func TestProxyHTTP_ForwardsRequest(t *testing.T) {
req := httptest.NewRequest("GET", "/snapshot", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/snapshot")
+ proxy.HTTP(rec, req, srv.URL+"/snapshot")
if rec.Code != 200 {
t.Errorf("expected 200, got %d: %s", rec.Code, rec.Body.String())
@@ -346,7 +347,7 @@ func TestProxyHTTP_ForwardsQueryParams(t *testing.T) {
req := httptest.NewRequest("GET", "/screenshot?raw=true", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/screenshot")
+ proxy.HTTP(rec, req, srv.URL+"/screenshot")
if rec.Code != 200 {
t.Errorf("expected 200, got %d", rec.Code)
@@ -356,7 +357,7 @@ func TestProxyHTTP_ForwardsQueryParams(t *testing.T) {
func TestProxyHTTP_UnreachableReturns502(t *testing.T) {
req := httptest.NewRequest("GET", "/snapshot", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, "http://localhost:1/snapshot")
+ proxy.HTTP(rec, req, "http://localhost:1/snapshot")
if rec.Code != 502 {
t.Errorf("expected 502, got %d", rec.Code)
@@ -410,28 +411,46 @@ func TestStrategy_State_CrashedStatus(t *testing.T) {
func TestStrategy_ExponentialBackoff(t *testing.T) {
s := New(AutorestartConfig{
InitBackoff: 100 * time.Millisecond,
+ MaxBackoff: 500 * time.Millisecond,
})
- // Simulate increasing backoff values
+ // Simulate increasing backoff values with cap
tests := []struct {
restartCount int
wantBackoff time.Duration
}{
- {0, 100 * time.Millisecond}, // 100ms * 2^0
- {1, 200 * time.Millisecond}, // 100ms * 2^1
- {2, 400 * time.Millisecond}, // 100ms * 2^2
- {3, 800 * time.Millisecond}, // 100ms * 2^3
- {4, 1600 * time.Millisecond}, // 100ms * 2^4
+ {0, 100 * time.Millisecond}, // 100ms * 2^0
+ {1, 200 * time.Millisecond}, // 100ms * 2^1
+ {2, 400 * time.Millisecond}, // 100ms * 2^2
+ {3, 500 * time.Millisecond}, // capped at 500ms (would be 800ms)
+ {4, 500 * time.Millisecond}, // capped at 500ms (would be 1600ms)
}
for _, tt := range tests {
backoff := s.config.InitBackoff * time.Duration(1<<uint(tt.restartCount))
+ if backoff > s.config.MaxBackoff {
+ backoff = s.config.MaxBackoff
+ }
if backoff != tt.wantBackoff {
t.Errorf("restartCount=%d: expected backoff=%s, got %s", tt.restartCount, tt.wantBackoff, backoff)
}
}
}
+func TestStrategy_BackoffCap_Default(t *testing.T) {
+ s := New(AutorestartConfig{})
+ if s.config.MaxBackoff != defaultMaxBackoff {
+ t.Errorf("expected default MaxBackoff=%s, got %s", defaultMaxBackoff, s.config.MaxBackoff)
+ }
+}
+
+func TestStrategy_BackoffCap_Custom(t *testing.T) {
+ s := New(AutorestartConfig{MaxBackoff: 30 * time.Second})
+ if s.config.MaxBackoff != 30*time.Second {
+ t.Errorf("expected MaxBackoff=30s, got %s", s.config.MaxBackoff)
+ }
+}
+
func TestStrategy_HandleCrash_RestartingEvent(t *testing.T) {
var eventsMu sync.Mutex
var events []string
diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.go
index 66ff0772..f17e45cf 100644
--- a/internal/strategy/explicit/explicit.go
+++ b/internal/strategy/explicit/explicit.go
@@ -10,6 +10,7 @@ import (
"net/http"
"github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -64,7 +65,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
return
}
- proxyHTTP(w, r, target+r.URL.Path)
+ proxy.HTTP(w, r, target+r.URL.Path)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
@@ -73,51 +74,5 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxyHTTP(w, r, target+"/tabs")
-}
-
-func proxyHTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
- if r.URL.RawQuery != "" {
- targetURL += "?" + r.URL.RawQuery
- }
-
- client := &http.Client{}
- proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
- return
- }
- for k, vv := range r.Header {
- for _, v := range vv {
- proxyReq.Header.Add(k, v)
- }
- }
-
- resp, err := client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for k, vv := range resp.Header {
- for _, v := range vv {
- w.Header().Add(k, v)
- }
- }
- w.WriteHeader(resp.StatusCode)
-
- buf := make([]byte, 32*1024)
- for {
- n, readErr := resp.Body.Read(buf)
- if n > 0 {
- _, _ = w.Write(buf[:n])
- if f, ok := w.(http.Flusher); ok {
- f.Flush()
- }
- }
- if readErr != nil {
- break
- }
- }
+ proxy.HTTP(w, r, target+"/tabs")
}
diff --git a/internal/strategy/simple/simple.go b/internal/strategy/simple/simple.go
index 346f9e78..51e059a7 100644
--- a/internal/strategy/simple/simple.go
+++ b/internal/strategy/simple/simple.go
@@ -16,6 +16,7 @@ import (
"time"
"github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/proxy"
"github.com/pinchtab/pinchtab/internal/strategy"
"github.com/pinchtab/pinchtab/internal/web"
)
@@ -49,17 +50,14 @@ func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {
// Shorthand endpoints — all proxy to first running instance.
shorthandRoutes := []string{
- "POST /navigate", "GET /navigate",
"GET /snapshot", "GET /screenshot", "GET /text",
- "GET /pdf", "POST /pdf",
- "POST /action", "POST /actions", "POST /evaluate",
- "POST /find",
+ "POST /navigate", "POST /action", "POST /actions", "POST /evaluate",
+ "POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /cookies", "POST /cookies",
"GET /download", "POST /upload",
- "POST /tab", "POST /tab/lock", "POST /tab/unlock",
"GET /stealth/status", "POST /fingerprint/rotate",
"GET /screencast", "GET /screencast/tabs",
- "POST /macro",
+ "POST /find", "POST /macro",
}
for _, route := range shorthandRoutes {
mux.HandleFunc(route, s.proxyToFirst)
@@ -75,7 +73,7 @@ func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {
web.Error(w, 503, err)
return
}
- proxyHTTP(w, r, target+r.URL.Path)
+ proxy.HTTP(w, r, target+r.URL.Path)
}
func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
@@ -84,7 +82,7 @@ func (s *Strategy) handleTabs(w http.ResponseWriter, r *http.Request) {
web.JSON(w, 200, map[string]any{"tabs": []any{}})
return
}
- proxyHTTP(w, r, target+"/tabs")
+ proxy.HTTP(w, r, target+"/tabs")
}
// ensureRunning returns the URL of a running instance, auto-launching one if needed.
@@ -123,50 +121,3 @@ func (s *Strategy) ensureRunning() (string, error) {
return "", fmt.Errorf("instance launched but did not become ready in time")
}
-
-// proxyHTTP forwards a request to the target URL.
-func proxyHTTP(w http.ResponseWriter, r *http.Request, targetURL string) {
- if r.URL.RawQuery != "" {
- targetURL += "?" + r.URL.RawQuery
- }
-
- client := &http.Client{Timeout: 60 * time.Second}
- proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
- return
- }
- for k, vv := range r.Header {
- for _, v := range vv {
- proxyReq.Header.Add(k, v)
- }
- }
-
- resp, err := client.Do(proxyReq)
- if err != nil {
- web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
- return
- }
- defer func() { _ = resp.Body.Close() }()
-
- for k, vv := range resp.Header {
- for _, v := range vv {
- w.Header().Add(k, v)
- }
- }
- w.WriteHeader(resp.StatusCode)
-
- buf := make([]byte, 32*1024)
- for {
- n, readErr := resp.Body.Read(buf)
- if n > 0 {
- _, _ = w.Write(buf[:n])
- if f, ok := w.(http.Flusher); ok {
- f.Flush()
- }
- }
- if readErr != nil {
- break
- }
- }
-}
diff --git a/internal/strategy/simple/simple_test.go b/internal/strategy/simple/simple_test.go
index 897604ba..6a71a005 100644
--- a/internal/strategy/simple/simple_test.go
+++ b/internal/strategy/simple/simple_test.go
@@ -5,6 +5,8 @@ import (
"net/http"
"net/http/httptest"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/proxy"
)
// fakeBridge creates a test server that mimics a bridge instance.
@@ -22,7 +24,7 @@ func TestProxyHTTP_ForwardsRequest(t *testing.T) {
req := httptest.NewRequest("GET", "/snapshot", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/snapshot")
+ proxy.HTTP(rec, req, srv.URL+"/snapshot")
if rec.Code != 200 {
t.Errorf("expected 200, got %d: %s", rec.Code, rec.Body.String())
@@ -41,7 +43,7 @@ func TestProxyHTTP_ForwardsQueryParams(t *testing.T) {
req := httptest.NewRequest("GET", "/screenshot?raw=true", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/screenshot")
+ proxy.HTTP(rec, req, srv.URL+"/screenshot")
if rec.Code != 200 {
t.Errorf("expected 200, got %d", rec.Code)
@@ -51,7 +53,7 @@ func TestProxyHTTP_ForwardsQueryParams(t *testing.T) {
func TestProxyHTTP_UnreachableReturns502(t *testing.T) {
req := httptest.NewRequest("GET", "/snapshot", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, "http://localhost:1/snapshot")
+ proxy.HTTP(rec, req, "http://localhost:1/snapshot")
if rec.Code != 502 {
t.Errorf("expected 502, got %d", rec.Code)
@@ -84,7 +86,7 @@ func TestStrategy_HandleTabs_NoInstances(t *testing.T) {
req := httptest.NewRequest("GET", "/tabs", nil)
rec := httptest.NewRecorder()
- proxyHTTP(rec, req, srv.URL+"/tabs")
+ proxy.HTTP(rec, req, srv.URL+"/tabs")
if rec.Code != 200 {
t.Errorf("expected 200, got %d", rec.Code)
diff --git a/internal/strategy/strategy.go b/internal/strategy/strategy.go
index 24a4c6e3..3cf24c60 100644
--- a/internal/strategy/strategy.go
+++ b/internal/strategy/strategy.go
@@ -7,6 +7,8 @@ import (
"fmt"
"net/http"
"sync"
+
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
)
// Orchestrator is the interface strategies need from the orchestrator.
@@ -16,6 +18,13 @@ type Orchestrator interface {
FirstRunningURL() string
}
+// OrchestratorAware is implemented by strategies that need a reference to
+// the concrete orchestrator. The dashboard checks for this interface after
+// constructing a strategy and injects the orchestrator before Start().
+type OrchestratorAware interface {
+ SetOrchestrator(o *orchestrator.Orchestrator)
+}
+
// Strategy defines a browser allocation approach.
type Strategy interface {
// Name returns the strategy identifier.
diff --git a/internal/strategy/strategy_test.go b/internal/strategy/strategy_test.go
index fbb6fea1..5951c5bd 100644
--- a/internal/strategy/strategy_test.go
+++ b/internal/strategy/strategy_test.go
@@ -64,3 +64,15 @@ func TestRegistry_Names(t *testing.T) {
t.Error("simple-autorestart not in names")
}
}
+
+func TestOrchestratorAware_AllStrategies(t *testing.T) {
+ for _, name := range []string{"explicit", "simple", "simple-autorestart"} {
+ s, err := strategy.New(name)
+ if err != nil {
+ t.Fatalf("strategy %q not registered: %v", name, err)
+ }
+ if _, ok := s.(strategy.OrchestratorAware); !ok {
+ t.Errorf("strategy %q does not implement OrchestratorAware", name)
+ }
+ }
+}