fix(browserskill): release connection capacity when members disconnect

BROWSERSKILL_MAX_CONNECTIONS counted every member a node had served in the
last 90 days: disconnected devices stayed in the device map until their
authorization expired, and devices created by a refused lease claim or a
pre-pairing select had a zero expiry and were never evicted. Once 32 distinct
members had connected, the next one was refused even with one member online.

Capacity now counts live and handshaking members only. Idle devices of other
members are evicted on the next acquisition; interrupted tasks are durable and
reload paused on reconnection. A handshake reserves its device so it cannot be
evicted mid-connect, and a full node reports the capacity error explicitly.

The daemon dial and WebSocket upgrade no longer run under the device lock,
which every other member's device acquisition waits on while holding the
manager lock. The upgrade gains a handshake timeout, and a connection whose
device was revoked, re-paired or evicted while dialing is discarded.
main
wizardchen 2026-09-21 20:05:16 +08:00 committed by lyingbug
parent 4640a1ea0c
commit da049f04e0
2 changed files with 146 additions and 20 deletions

View File

@ -92,8 +92,18 @@ type device struct {
tasks map[string]*task
expires time.Time
recordID string
// connecting counts extension handshakes holding this device against
// eviction; attaching excludes a second handshake while dialing unlocked.
connecting int
attaching bool
}
// idleLocked reports whether the device only caches reloadable state.
// Interrupted tasks are durable and reload as paused on the next connection.
func (d *device) idleLocked() bool { return d.conn == nil && d.connecting == 0 && !d.attaching }
var errCapacity = errors.New("local browser connection capacity reached")
// Manager owns transient browser connections; authorization and interruption
// markers are durable. Other replicas route commands to the lease owner.
type Manager struct {
@ -244,6 +254,13 @@ func (m *Manager) Pair(ctx context.Context, s Scope, origin string) (string, err
// ensureDevice shares the daemon, but never shares authorization or task maps.
func (m *Manager) ensureDevice(ctx context.Context, s Scope) (*device, error) {
return m.acquireDevice(ctx, s, false)
}
// acquireDevice optionally reserves the device for an extension handshake;
// the caller must release a reservation by decrementing d.connecting.
// Capacity counts live members only: other members' idle devices are evicted.
func (m *Manager) acquireDevice(ctx context.Context, s Scope, reserve bool) (*device, error) {
runtime, err := m.ensureDaemon(ctx)
if err != nil {
return nil, err
@ -253,19 +270,21 @@ func (m *Manager) ensureDevice(ctx context.Context, s Scope) (*device, error) {
if m.closed || runtime.exited() {
return nil, errors.New("BrowserSkill daemon unavailable")
}
self := s.key()
for key, old := range m.devices {
old.mu.Lock()
if old.runtime != runtime || (!old.expires.IsZero() && time.Now().After(old.expires)) {
if old.runtime != runtime || (!old.expires.IsZero() && time.Now().After(old.expires)) ||
(key != self && old.idleLocked()) {
delete(m.devices, key)
disconnectDeviceLocked(old)
old.expires = time.Time{}
}
old.mu.Unlock()
}
d := m.devices[s.key()]
d := m.devices[self]
if d == nil {
if len(m.devices) >= m.maxConnections {
return nil, errors.New("local browser connection capacity reached")
return nil, errCapacity
}
rows, err := m.store.tasks(ctx, s)
if err != nil {
@ -276,7 +295,12 @@ func (m *Manager) ensureDevice(ctx context.Context, s Scope) (*device, error) {
d.tasks[row.Session] = &task{selected: true, paused: true}
}
m.devices[s.key()] = d
m.devices[self] = d
}
if reserve {
d.mu.Lock()
d.connecting++
d.mu.Unlock()
}
return d, nil
}
@ -366,11 +390,17 @@ func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "device authorization invalid; pair again", http.StatusUnauthorized)
return
}
d, err := m.ensureDevice(authCtx, record.scope())
d, err := m.acquireDevice(authCtx, record.scope(), true)
if errors.Is(err, errCapacity) {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
if err != nil {
http.Error(w, "browser runtime unavailable", http.StatusServiceUnavailable)
return
}
// Idle once this handler returns, so the next member's connection can evict it.
defer func() { d.mu.Lock(); d.connecting--; d.mu.Unlock() }()
leaseKey := randomID()
if err = m.store.claim(authCtx, record, m.nodeID, m.internalURL, leaseKey); err != nil {
http.Error(w, "browser connection owned elsewhere; retry shortly", http.StatusConflict)
@ -382,30 +412,32 @@ func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_ = m.store.release(ctx, record.ID, leaseKey)
}()
d.mu.Lock()
if d.conn != nil {
if d.conn != nil || d.attaching {
d.mu.Unlock()
http.Error(w, "browser already connected", http.StatusConflict)
return
}
d.recordID = record.ID
d.expires = record.ExpiresAt
// Hold the device lock across the bounded connect/upgrade to exclude a second connector.
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
target := fmt.Sprintf("ws://127.0.0.1:%d", d.runtime.port)
up, _, err := websocket.DefaultDialer.DialContext(ctx, target, http.Header{"Origin": []string{origin}})
// Dial and upgrade unlocked: a slow peer must not stall other members'
// lookups, which lock every device while holding the manager lock.
d.attaching = true
attachGeneration := d.generation
d.mu.Unlock()
up, conn, err := m.attach(w, r, d, origin, protocols)
d.mu.Lock()
d.attaching = false
if err != nil {
d.mu.Unlock()
http.Error(w, "daemon unavailable", http.StatusServiceUnavailable)
return
}
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }, Subprotocols: protocols}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if d.generation != attachGeneration {
// Revoked, re-paired or evicted after a daemon restart while dialing.
d.mu.Unlock()
_ = conn.Close()
_ = up.Close()
return
}
d.recordID = record.ID
d.expires = record.ExpiresAt
d.conn = conn
d.upstream = up
d.ready = false
@ -486,6 +518,36 @@ func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
<-done
}
// attach dials the shared daemon, then upgrades the extension connection.
// On failure the extension has already received an HTTP error response.
func (m *Manager) attach(
w http.ResponseWriter,
r *http.Request,
d *device,
origin string,
protocols []string,
) (up, conn *websocket.Conn, err error) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
target := fmt.Sprintf("ws://127.0.0.1:%d", d.runtime.port)
up, _, err = websocket.DefaultDialer.DialContext(ctx, target, http.Header{"Origin": []string{origin}})
if err != nil {
http.Error(w, "daemon unavailable", http.StatusServiceUnavailable)
return nil, nil, err
}
upgrader := websocket.Upgrader{
CheckOrigin: func(*http.Request) bool { return true },
Subprotocols: protocols,
HandshakeTimeout: 5 * time.Second,
}
conn, err = upgrader.Upgrade(w, r, nil)
if err != nil {
_ = up.Close()
return nil, nil, err
}
return up, conn, nil
}
func relayHandshake(conn, up *websocket.Conn, browserID string) ([]byte, error) {
deadline := time.Now().Add(5 * time.Second)
_ = conn.SetReadDeadline(deadline)
@ -915,6 +977,10 @@ func (m *Manager) Control(ctx context.Context, s Scope, session, action string)
if d == nil && action == "stop" && m.store != nil {
return m.store.clearTask(ctx, s, session)
}
if d == nil && action == "pause" {
// Idle devices are evicted; nothing runs and durable tasks reload paused.
return nil
}
if d == nil {
return errors.New("pair a browser first")
}

View File

@ -373,7 +373,8 @@ func TestConcurrentPairingSharesOneDaemon(t *testing.T) {
const count = 12
results := make(chan error, count)
for i := 0; i < count; i++ {
go func(i int) { _, err := m.ensureDevice(ctx, Scope{1, fmt.Sprint(i)}); results <- err }(i)
// Reserved as in-progress extension handshakes, so none is idle.
go func(i int) { _, err := m.acquireDevice(ctx, Scope{1, fmt.Sprint(i)}, true); results <- err }(i)
}
for i := 0; i < count; i++ {
require.NoError(t, <-results)
@ -384,7 +385,7 @@ func TestConcurrentPairingSharesOneDaemon(t *testing.T) {
}
m.maxConnections = count
_, err := m.ensureDevice(ctx, Scope{1, "over-limit"})
require.ErrorContains(t, err, "capacity")
require.ErrorIs(t, err, errCapacity)
if err := m.Revoke(ctx, Scope{1, "0"}); err != nil {
t.Fatal(err)
}
@ -392,6 +393,64 @@ func TestConcurrentPairingSharesOneDaemon(t *testing.T) {
require.NoError(t, err)
}
// Capacity counts live members, not every member this node has ever served.
func TestDisconnectedMembersReleaseCapacity(t *testing.T) {
m, ctx := sharedTestManager(t)
m.maxConnections = 2
alice, bob, carol := Scope{1, "alice"}, Scope{1, "bob"}, Scope{1, "carol"}
fixture := connectSharedFixture(ctx, t, m, alice, "", "alice-browser")
require.NoError(t, m.Control(ctx, alice, "chat", "start"))
d := m.get(alice)
require.NoError(t, fixture.ws.Close())
require.Eventually(t, func() bool {
d.mu.Lock()
defer d.mu.Unlock()
return d.idleLocked()
}, 5*time.Second, 20*time.Millisecond)
// An unpaired selection is idle as well and must not pin a slot.
require.NoError(t, m.Control(ctx, carol, "chat", "select"))
connectSharedFixture(ctx, t, m, bob, "", "bob-browser")
require.Nil(t, m.get(alice))
require.Nil(t, m.get(carol))
// Alice's interrupted task is durable and reloads paused on reconnection.
status, err := m.GetStatus(ctx, alice, "chat")
require.NoError(t, err)
require.True(t, status.Selected)
require.True(t, status.Paused)
require.NoError(t, m.Control(ctx, alice, "chat", "pause"))
connectSharedFixture(ctx, t, m, alice, "", "alice-browser")
status = m.Status(alice, "chat")
require.True(t, status.Connected)
require.True(t, status.Selected)
require.True(t, status.Paused)
}
// A handshake reserves its device; a failed lease claim must not leak it.
func TestFailedLeaseClaimDoesNotPinCapacity(t *testing.T) {
m, ctx := sharedTestManager(t)
m.maxConnections = 1
alice := Scope{1, "alice"}
link, err := m.Pair(ctx, alice, "")
require.NoError(t, err)
parts := strings.Split(redeemTestPair(ctx, t, m, link), "#")
record, err := m.store.account(ctx, alice)
require.NoError(t, err)
require.NoError(t, m.store.claim(ctx, record, "other-node", "http://other:8080", randomID()))
header := http.Header{"Origin": []string{"chrome-extension://" + strings.Repeat("a", 32)}}
dialer := websocket.Dialer{Subprotocols: []string{AuthProtocol + parts[1]}}
_, response, err := dialer.DialContext(ctx, parts[0], header)
require.Error(t, err)
require.Equal(t, http.StatusConflict, response.StatusCode)
_ = response.Body.Close()
_, err = m.ensureDevice(ctx, Scope{1, "bob"})
require.NoError(t, err, "the refused handshake must leave an evictable device")
require.Nil(t, m.get(alice))
}
func TestSharedDaemonCrashKeepsAuthorizationAndPausesTasks(t *testing.T) {
m, ctx := sharedTestManager(t)
scope := Scope{1, "alice"}
@ -430,7 +489,8 @@ exec "$WEKNORA_BSK_NATIVE" "$@"
m.binary = wrapper
t.Cleanup(func() { _ = os.WriteFile(gate+"/release", nil, 0o600) })
pending := make(chan error, 1)
go func() { _, err := m.ensureDevice(ctx, Scope{1, "alice"}); pending <- err }()
// Reserved like a pending extension handshake so Bob cannot evict it.
go func() { _, err := m.acquireDevice(ctx, Scope{1, "alice"}, true); pending <- err }()
require.Eventually(
t,
func() bool {