Skip to content

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

fix: sweep abandoned agent sessions so their instance bindings are released

Luigi Agostibe84568463e1
diff --git a/internal/server/server.go b/internal/server/server.go
index 59faa3ef..4ff2d794 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -2,9 +2,11 @@ package server
import (
"context"
+ "errors"
"fmt"
"io"
"log/slog"
+ "net"
"net/http"
"os"
"os/signal"
@@ -35,6 +37,29 @@ import (
_ "github.com/pinchtab/pinchtab/internal/strategy/simple"
)
+var exitProcess = os.Exit
+
+// fatalStartup reports a startup failure on stderr and exits. Startup failures
+// must not travel through slog: the non-verbose default replaces the logger
+// with a discard handler, which would leave the process exiting in silence.
+func fatalStartup(stage string, err error) {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("pinchtab: %s: %v", stage, err)))
+ for _, hint := range startupFatalHints(err) {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.MutedStyle, " "+hint))
+ }
+ exitProcess(1)
+}
+
+func startupFatalHints(err error) []string {
+ if !errors.Is(err, syscall.EADDRINUSE) {
+ return nil
+ }
+ return []string{
+ "Another process is already listening on that address.",
+ "Check for a running service with `pinchtab daemon`, or stop it with `pinchtab server stop`.",
+ }
+}
+
func RunDashboard(cfg *config.RuntimeConfig, version string) {
if !cfg.VerboseStartup {
slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
@@ -47,8 +72,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
profilesDir := cfg.ProfilesBaseDir
if err := os.MkdirAll(profilesDir, 0755); err != nil {
- slog.Error("cannot create profiles dir", "err", err)
- os.Exit(1)
+ fatalStartup("cannot create profiles dir", err)
}
profMgr := profiles.NewProfileManager(profilesDir)
@@ -123,8 +147,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
},
}, cfg.ActivityStateDir())
if err != nil {
- slog.Error("activity store", "err", err)
- os.Exit(1)
+ fatalStartup("activity store", err)
}
profMgr.SetActivityRecorder(actStore)
@@ -209,8 +232,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
slog.Warn("unknown strategy, falling back to always-on", "strategy", strategyName, "err", err)
activeStrategy, err = strategy.New("always-on")
if err != nil {
- slog.Error("failed to initialize fallback strategy", "strategy", "always-on", "err", err)
- os.Exit(1)
+ fatalStartup("failed to initialize fallback strategy always-on", err)
}
}
if runtimeAware, ok := activeStrategy.(strategy.RuntimeConfigAware); ok {
@@ -325,6 +347,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
maintenanceCtx, maintenanceCancel := context.WithCancel(context.Background())
go orch.RunMaintenance(maintenanceCtx)
+ go sessionStore.RunMaintenance(maintenanceCtx)
shutdownOnce := &sync.Once{}
doShutdown := func() {
@@ -372,10 +395,13 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
os.Exit(130)
}()
+ listener, err := net.Listen("tcp", srv.Addr)
+ if err != nil {
+ fatalStartup("cannot listen on "+srv.Addr, err)
+ }
slog.Info("dashboard started", "port", dashPort)
- if err := srv.ListenAndServe(); err != http.ErrServerClosed {
- slog.Error("server", "err", err)
- os.Exit(1)
+ if err := srv.Serve(listener); err != http.ErrServerClosed {
+ fatalStartup("server error", err)
}
}
diff --git a/internal/session/store.go b/internal/session/store.go
index b705707c..85236b70 100644
--- a/internal/session/store.go
+++ b/internal/session/store.go
@@ -5,6 +5,7 @@
package session
import (
+ "context"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
@@ -416,6 +417,52 @@ func (s *Store) UpdateConfig(cfg Config) {
s.dispatchLifecycle(events)
}
+// MaintenanceInterval is how often RunMaintenance sweeps expired sessions.
+const MaintenanceInterval = 5 * time.Minute
+
+// PruneExpired drops revoked and expired sessions, persists the result, and
+// dispatches the resulting lifecycle events so downstream bindings are cleared.
+func (s *Store) PruneExpired() {
+ if s == nil {
+ return
+ }
+ s.mu.Lock()
+ events := s.pruneExpiredLocked()
+ var (
+ job snapshotJob
+ persist bool
+ )
+ if len(events) > 0 {
+ job, persist = s.snapshotLocked()
+ }
+ s.mu.Unlock()
+ if persist {
+ s.writeSnapshot(job)
+ }
+ s.dispatchLifecycle(events)
+}
+
+// RunMaintenance sweeps expired sessions until ctx is done. Expiry is otherwise
+// only noticed when a session's own token is presented again, so a session that
+// is simply abandoned — the usual end of an agent run — is never detected, and
+// it plus any downstream binding keyed on its id survive for the life of the
+// process.
+func (s *Store) RunMaintenance(ctx context.Context) {
+ if s == nil {
+ return
+ }
+ t := time.NewTicker(MaintenanceInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ s.PruneExpired()
+ }
+ }
+}
+
// Enabled reports whether session auth is enabled.
func (s *Store) Enabled() bool {
if s == nil {
diff --git a/internal/session/store_prune_test.go b/internal/session/store_prune_test.go
new file mode 100644
index 00000000..91a08bf2
--- /dev/null
+++ b/internal/session/store_prune_test.go
@@ -0,0 +1,82 @@
+package session
+
+import (
+ "sync"
+ "testing"
+ "time"
+)
+
+// A session that is simply abandoned is never re-authenticated, so the lazy
+// expiry checks in authenticate/Touch never run for it. PruneExpired is the
+// only thing that evicts it and tells downstream binding tables to drop it.
+func TestPruneExpiredEvictsAbandonedSessionAndNotifies(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ s := NewStore(Config{Enabled: true, IdleTimeout: time.Hour, MaxLifetime: 24 * time.Hour})
+ s.now = func() time.Time { return now }
+
+ var (
+ mu sync.Mutex
+ events []LifecycleEvent
+ )
+ s.OnLifecycle(func(evt LifecycleEvent) {
+ mu.Lock()
+ events = append(events, evt)
+ mu.Unlock()
+ })
+
+ id, _, err := s.Create("agent-1", "", "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+
+ // Nothing touches the session again; it just ages past the idle timeout.
+ now = now.Add(2 * time.Hour)
+ s.PruneExpired()
+
+ if _, ok := s.Get(id); ok {
+ t.Error("abandoned session survived PruneExpired")
+ }
+
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ mu.Lock()
+ got := len(events)
+ mu.Unlock()
+ if got > 0 || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(time.Millisecond)
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(events) != 1 {
+ t.Fatalf("got %d lifecycle events, want 1", len(events))
+ }
+ if events[0].SessionID != id || events[0].Reason != LifecycleReasonPruned {
+ t.Errorf("event = %+v, want pruned event for %s", events[0], id)
+ }
+}
+
+// A live session must survive the sweep, or every maintenance tick would log
+// active agents out.
+func TestPruneExpiredKeepsLiveSessions(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ s := NewStore(Config{Enabled: true, IdleTimeout: time.Hour, MaxLifetime: 24 * time.Hour})
+ s.now = func() time.Time { return now }
+
+ id, token, err := s.Create("agent-1", "", "")
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+
+ now = now.Add(30 * time.Minute)
+ s.PruneExpired()
+
+ if _, ok := s.Get(id); !ok {
+ t.Fatal("live session was pruned")
+ }
+ if _, ok := s.Authenticate(token); !ok {
+ t.Error("live session no longer authenticates after a sweep")
+ }
+}