Skip to content

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

refactor: one isolated context per containment check instead of one per node resolve (PIN-166)

Luigi Agosti43441bb6b22e
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.go
index 8f4ee47d..0ada4e14 100644
--- a/internal/bridge/action_resolve.go
+++ b/internal/bridge/action_resolve.go
@@ -85,6 +85,12 @@ func IsolatedNodeObjectID(ctx context.Context, backendNodeID int64) (string, err
return cdptk.IsolatedNodeObjectID(ctx, backendNodeID)
}
+// IsolatedNodeObjectIDs resolves several nodes against one isolated context, for an
+// operation whose handles are compared in a single call.
+func IsolatedNodeObjectIDs(ctx context.Context, backendNodeIDs ...int64) ([]string, error) {
+ return cdptk.IsolatedNodeObjectIDs(ctx, backendNodeIDs...)
+}
+
func frameDocumentObjectID(ctx context.Context, frameID string) (string, error) {
execID, err := isolatedExecutionContextID(ctx, frameID)
if err != nil {
@@ -367,14 +373,11 @@ func BackendNodeWithinScope(ctx context.Context, scopeBackendNodeID, targetBacke
return false, nil
}
- scopeObjectID, err := IsolatedNodeObjectID(ctx, scopeBackendNodeID)
- if err != nil {
- return false, fmt.Errorf("resolve scope node: %w", err)
- }
- targetObjectID, err := IsolatedNodeObjectID(ctx, targetBackendNodeID)
+ objectIDs, err := IsolatedNodeObjectIDs(ctx, scopeBackendNodeID, targetBackendNodeID)
if err != nil {
- return false, fmt.Errorf("resolve target node: %w", err)
+ return false, fmt.Errorf("resolve scope and target nodes: %w", err)
}
+ scopeObjectID, targetObjectID := objectIDs[0], objectIDs[1]
var contains bool
err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
diff --git a/internal/bridge/isolated_world_batch_test.go b/internal/bridge/isolated_world_batch_test.go
new file mode 100644
index 00000000..5e21da35
--- /dev/null
+++ b/internal/bridge/isolated_world_batch_test.go
@@ -0,0 +1,234 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+)
+
+const containmentFixtureHTML = `<body>
+<div id="dlg" role="dialog" aria-modal="true" style="position:fixed;inset:20px;background:#fff">
+<button id="inside">Confirm</button>
+</div>
+<button id="outside">Background</button>
+</body>`
+
+// cdpCounter counts the protocol messages the browser SENDS, per method, from
+// chromedp's own debug stream. Counting at the wire is the only place the saving
+// is real: the same operation still runs the same Go code either way.
+type cdpCounter struct {
+ mu sync.Mutex
+ counting bool
+ byMethod map[string]int
+}
+
+func (c *cdpCounter) debugf(format string, args ...any) {
+ if len(args) == 0 {
+ return
+ }
+ if !strings.Contains(format, "->") {
+ return
+ }
+ var line []byte
+ switch payload := args[len(args)-1].(type) {
+ case []byte:
+ line = payload
+ case string:
+ line = []byte(payload)
+ default:
+ return
+ }
+ var msg struct {
+ Method string `json:"method"`
+ }
+ if err := json.Unmarshal(line, &msg); err != nil || msg.Method == "" {
+ return
+ }
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if !c.counting {
+ return
+ }
+ c.byMethod[msg.Method]++
+}
+
+func (c *cdpCounter) start() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.counting = true
+ c.byMethod = map[string]int{}
+}
+
+func (c *cdpCounter) stop() map[string]int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.counting = false
+ out := make(map[string]int, len(c.byMethod))
+ for method, count := range c.byMethod {
+ out[method] = count
+ }
+ return out
+}
+
+func newCountedContainmentFixture(t *testing.T) (context.Context, *cdpCounter) {
+ t.Helper()
+
+ counter := &cdpCounter{byMethod: map[string]int{}}
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(testbrowser.Path(t)),
+ chromedp.UserDataDir(t.TempDir()),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc, chromedp.WithDebugf(counter.debugf))
+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ })
+
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(containmentFixtureHTML))
+ if err := chromedp.Run(ctx,
+ chromedp.Navigate(dataURL),
+ chromedp.WaitVisible("#inside", chromedp.ByID),
+ ); err != nil {
+ t.Fatal(err)
+ }
+ return ctx, counter
+}
+
+// TestOneContainmentCheckCostsOneIsolatedContext pins the message count for the
+// logical operation, filtered to the methods the check itself issues so an
+// unrelated CDP call elsewhere cannot red it. The count is what stops the
+// per-node resolve growing back: the frame tree read and the world creation are
+// per-operation, only DOM.resolveNode is per node.
+func TestOneContainmentCheckCostsOneIsolatedContext(t *testing.T) {
+ ctx, counter := newCountedContainmentFixture(t)
+
+ dialogNodeID, open, err := TopmostModalNodeID(ctx, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !open {
+ t.Fatal("fixture dialog was not detected")
+ }
+ insideNodeID, err := ResolveCSSToNodeID(ctx, "#inside")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ counter.start()
+ within, err := BackendNodeWithinScope(ctx, dialogNodeID, insideNodeID)
+ counted := counter.stop()
+ if err != nil {
+ t.Fatalf("BackendNodeWithinScope: %v", err)
+ }
+ if !within {
+ t.Fatal("button inside the dialog reported as outside it")
+ }
+
+ want := map[string]int{
+ "Page.getFrameTree": 1,
+ "Page.createIsolatedWorld": 1,
+ "DOM.resolveNode": 2,
+ "Runtime.callFunctionOn": 1,
+ }
+ total := 0
+ for method, wantCount := range want {
+ if counted[method] != wantCount {
+ t.Errorf("%s issued %d times, want %d", method, counted[method], wantCount)
+ }
+ total += counted[method]
+ }
+ if total != 5 {
+ t.Errorf("one containment check issued %d of its own CDP messages, want 5 (%v)", total, counted)
+ }
+}
+
+func TestBackendNodeWithinScopeStillAnswersBothWays(t *testing.T) {
+ ctx, _ := newCountedContainmentFixture(t)
+
+ dialogNodeID, open, err := TopmostModalNodeID(ctx, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !open {
+ t.Fatal("fixture dialog was not detected")
+ }
+
+ for _, tc := range []struct {
+ selector string
+ want bool
+ }{
+ {"#inside", true},
+ {"#outside", false},
+ {"#dlg", true},
+ } {
+ nodeID, err := ResolveCSSToNodeID(ctx, tc.selector)
+ if err != nil {
+ t.Fatalf("resolve %s: %v", tc.selector, err)
+ }
+ got, err := BackendNodeWithinScope(ctx, dialogNodeID, nodeID)
+ if err != nil {
+ t.Fatalf("BackendNodeWithinScope(%s): %v", tc.selector, err)
+ }
+ if got != tc.want {
+ t.Errorf("BackendNodeWithinScope(%s) = %v, want %v", tc.selector, got, tc.want)
+ }
+ }
+}
+
+// TestBackendNodeWithinScopeResolvesItsNodesOnce is the browserless half of the
+// count: CI installs no browser, so the wire assertion above never runs there. A
+// second resolve inside this function is exactly the regrowth the card is about,
+// and it is visible in the AST without a browser.
+func TestBackendNodeWithinScopeResolvesItsNodesOnce(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "action_resolve.go", nil, 0)
+ if err != nil {
+ t.Fatalf("parse action_resolve.go: %v", err)
+ }
+
+ var body *ast.FuncDecl
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if ok && fn.Name.Name == "BackendNodeWithinScope" {
+ body = fn
+ break
+ }
+ }
+ if body == nil {
+ t.Fatal("BackendNodeWithinScope is gone from action_resolve.go; this guard names it")
+ }
+
+ calls := map[string]int{}
+ ast.Inspect(body, func(node ast.Node) bool {
+ call, ok := node.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if ident, ok := call.Fun.(*ast.Ident); ok {
+ calls[ident.Name]++
+ }
+ return true
+ })
+
+ if calls["IsolatedNodeObjectIDs"] != 1 {
+ t.Errorf("BackendNodeWithinScope calls IsolatedNodeObjectIDs %d times, want exactly 1: one isolated context serves the whole check", calls["IsolatedNodeObjectIDs"])
+ }
+ if calls["IsolatedNodeObjectID"] != 0 {
+ t.Errorf("BackendNodeWithinScope calls the single-node IsolatedNodeObjectID %d times; each call recomputes the top-frame context", calls["IsolatedNodeObjectID"])
+ }
+}
diff --git a/internal/cdptk/isolated_world.go b/internal/cdptk/isolated_world.go
index dd823ec7..a5c79bda 100644
--- a/internal/cdptk/isolated_world.go
+++ b/internal/cdptk/isolated_world.go
@@ -30,11 +30,40 @@ const isolatedWorldName = "pinchtab-node-scope"
// context gets an error rather than a main-world handle, so the boundary fails
// closed.
func IsolatedNodeObjectID(ctx context.Context, backendNodeID int64) (string, error) {
- execID, err := topFrameIsolatedContextID(ctx)
+ objectIDs, err := IsolatedNodeObjectIDs(ctx, backendNodeID)
if err != nil {
return "", err
}
+ return objectIDs[0], nil
+}
+
+// IsolatedNodeObjectIDs resolves several backend node ids against ONE isolated
+// context, so an operation comparing two nodes pays for the frame tree read and
+// the world creation once instead of once per node. Handles it returns are
+// therefore usable in the same Runtime.callFunctionOn, which a per-node resolve
+// only guaranteed by accident.
+func IsolatedNodeObjectIDs(ctx context.Context, backendNodeIDs ...int64) ([]string, error) {
+ if len(backendNodeIDs) == 0 {
+ return nil, fmt.Errorf("no backend node ids to resolve")
+ }
+
+ execID, err := topFrameIsolatedContextID(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ objectIDs := make([]string, 0, len(backendNodeIDs))
+ for _, backendNodeID := range backendNodeIDs {
+ objectID, err := resolveNodeInContext(ctx, backendNodeID, execID)
+ if err != nil {
+ return nil, err
+ }
+ objectIDs = append(objectIDs, objectID)
+ }
+ return objectIDs, nil
+}
+func resolveNodeInContext(ctx context.Context, backendNodeID, execID int64) (string, error) {
var raw json.RawMessage
if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{