carlos / platform Public

Retry canceled visitor lookups and release waiters after panics

Do not cache caller cancellations as anonymous identities. Release
waiters to retry, and clean pending entries when the provider panics.
Unmap IPv4 peers before sending them to the Tailscale LocalAPI.

Cover leader cancellation, panic recovery, cancellation during a wait,
and full cache resets. Focused tests and one race run pass for both
internal/edge and internal/tsidentity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3cf5aba641b15618ff2c9360e8e70d037cc3e7d8 parent 6d59ecc
4 files changed, +204 −56
  • internal/edge/visitor.go +42 −14
  • internal/edge/visitor_test.go +155 −40
  • internal/tsidentity/whois.go +1 −0
  • internal/tsidentity/whois_test.go +6 −2

CI failed — run details

diff --git a/internal/edge/visitor.go b/internal/edge/visitor.go
index 78f9c3467..a4222ddad 100644
--- a/internal/edge/visitor.go
+++ b/internal/edge/visitor.go
@@ -2,6 +2,7 @@ package edge
import (
"context"
+ "errors"
"net/netip"
"strings"
"sync"
@@ -35,7 +36,8 @@ type cachedIdentity struct {
// NewCachedIdentity caches identities by unmapped IP for 60 seconds, and
// misses or errors for 5 seconds. Cached errors return an anonymous miss with
-// nil error. At 4096 entries, a new IP resets the cache to bound memory.
+// nil error. Canceled lookups and panics are not cached; waiters retry.
+// At 4096 entries, a new IP resets the cache to bound memory.
func NewCachedIdentity(inner VisitorIdentity, now func() time.Time) VisitorIdentity {
return &cachedIdentity{inner: inner, now: now, entries: make(map[netip.Addr]*visitorCacheEntry)}
}
@@ -72,21 +74,47 @@ func (c *cachedIdentity) Who(ctx context.Context, remote netip.AddrPort) (Visito
c.entries[key] = entry
c.mu.Unlock()
- // Keep the port for the provider. Requests for this IP wait above without
- // holding the mutex, and can leave when their own context is canceled.
- visitor, ok, err := c.inner.Who(ctx, remote)
- ttl := 60 * time.Second
- if !ok || err != nil {
- visitor, ok = Visitor{}, false
- ttl = 5 * time.Second
- }
+ return c.lookup(ctx, remote, entry)
+ }
+}
+
+func (c *cachedIdentity) lookup(ctx context.Context, remote netip.AddrPort, entry *visitorCacheEntry) (Visitor, bool, error) {
+ // A canceled lookup or panic must release waiters without leaving a miss.
+ // Keep any replacement entry installed after a cap reset. Panics still
+ // propagate to the caller, where net/http can recover them as usual.
+ defer func() {
c.mu.Lock()
- entry.visitor, entry.ok, entry.expires = visitor, ok, c.now().Add(ttl)
- close(entry.ready)
- entry.ready = nil
- c.mu.Unlock()
- return visitor, ok, err
+ defer c.mu.Unlock()
+ if entry.ready != nil {
+ key := remote.Addr().Unmap()
+ if c.entries[key] == entry {
+ delete(c.entries, key)
+ }
+ close(entry.ready)
+ entry.ready = nil
+ }
+ }()
+
+ // Keep the full AddrPort for the provider. If this caller cancels, the
+ // other callers retry under their own contexts instead of caching a miss.
+ visitor, ok, err := c.inner.Who(ctx, remote)
+ if ctx.Err() != nil {
+ return Visitor{}, false, ctx.Err()
+ }
+ if errors.Is(err, context.Canceled) {
+ return Visitor{}, false, err
+ }
+ ttl := 60 * time.Second
+ if !ok || err != nil {
+ visitor, ok = Visitor{}, false
+ ttl = 5 * time.Second
}
+ c.mu.Lock()
+ entry.visitor, entry.ok, entry.expires = visitor, ok, c.now().Add(ttl)
+ close(entry.ready)
+ entry.ready = nil
+ c.mu.Unlock()
+ return visitor, ok, err
}
// anonymousSource is the front door's shared-machine rule: the devbox's own
diff --git a/internal/edge/visitor_test.go b/internal/edge/visitor_test.go
index fea768d81..08aaa95a8 100644
--- a/internal/edge/visitor_test.go
+++ b/internal/edge/visitor_test.go
@@ -7,6 +7,7 @@ import (
"sync"
"sync/atomic"
"testing"
+ "testing/synctest"
"time"
)
@@ -90,57 +91,171 @@ func TestCachedIdentityBound(t *testing.T) {
identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
calls++
return Visitor{}, false, nil
- }), time.Now)
- for i := 0; i < 4097; i++ {
- remote := netip.AddrPortFrom(netip.AddrFrom4([4]byte{100, 64, byte(i >> 8), byte(i)}), 1234)
- _, _, _ = identity.Who(context.Background(), remote)
+ }), func() time.Time { return time.Unix(1000, 0) })
+ remote := func(i int) netip.AddrPort {
+ return netip.AddrPortFrom(netip.AddrFrom4([4]byte{100, 64, byte(i >> 8), byte(i)}), 1234)
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ }
+ if calls != 4096 {
+ t.Fatalf("cache reset before cap: calls %d", calls)
+ }
+ _, _, _ = identity.Who(context.Background(), remote(4096))
+ cache := identity.(*cachedIdentity)
+ if len(cache.entries) != 1 {
+ t.Fatalf("after full reset: entries %d, want 1", len(cache.entries))
}
- _, _, _ = identity.Who(context.Background(), netip.MustParseAddrPort("100.64.0.0:4321"))
- if calls != 4098 {
- t.Fatalf("oldest entry retained beyond cap: calls %d", calls)
+ if _, ok := cache.entries[remote(4096).Addr()]; !ok {
+ t.Fatal("new entry missing after reset")
+ }
+ for i := 0; i < 4096; i++ {
+ _, _, _ = identity.Who(context.Background(), remote(i))
+ if calls != 4098+i {
+ t.Fatalf("entry %d retained after reset: calls %d", i, calls)
+ }
+ }
+ if len(cache.entries) != 1 {
+ t.Fatalf("after second reset: entries %d, want 1", len(cache.entries))
}
}
func TestCachedIdentityConcurrent(t *testing.T) {
- var calls atomic.Int32
- started, release := make(chan struct{}), make(chan struct{})
- identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
- if calls.Add(1) == 1 {
- close(started)
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started, release := make(chan struct{}), make(chan struct{})
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ }
+ <-release
+ return Visitor{Login: "alice@github"}, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ var wg sync.WaitGroup
+ for i := 0; i < 32; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ v, ok, err := identity.Who(context.Background(), remote)
+ if !ok || err != nil || v.Login != "alice@github" {
+ t.Errorf("lookup = %+v, %v, %v", v, ok, err)
+ }
+ }()
}
- <-release
- return Visitor{Login: "alice@github"}, true, nil
- }), time.Now)
- remote := netip.MustParseAddrPort("100.64.0.1:1234")
- var wg sync.WaitGroup
- for i := 0; i < 32; i++ {
- wg.Add(1)
+ <-started
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { _, _, err := identity.Who(ctx, remote); done <- err }()
+ synctest.Wait()
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("canceled waiter: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Error("canceled waiter blocked behind lookup")
+ }
+ close(release)
+ wg.Wait()
+ if calls.Load() != 1 {
+ t.Fatalf("concurrent lookups: %d, want 1", calls.Load())
+ }
+ })
+}
+
+func TestCachedIdentityCanceledLookup(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started := make(chan struct{})
+ want := Visitor{Login: "alice@github", Node: "laptop"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(ctx context.Context, _ netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ <-ctx.Done()
+ return Visitor{}, false, ctx.Err()
+ }
+ return want, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ leader := make(chan error, 1)
+ go func() { _, _, err := identity.Who(ctx, remote); leader <- err }()
+ <-started
+ waiter := make(chan struct{})
go func() {
- defer wg.Done()
+ defer close(waiter)
v, ok, err := identity.Who(context.Background(), remote)
- if !ok || err != nil || v.Login != "alice@github" {
- t.Errorf("lookup = %+v, %v, %v", v, ok, err)
+ if v != want || !ok || err != nil {
+ t.Errorf("waiter: %+v, %v, %v", v, ok, err)
}
}()
- }
- <-started
- ctx, cancel := context.WithCancel(context.Background())
- cancel()
- done := make(chan error, 1)
- go func() { _, _, err := identity.Who(ctx, remote); done <- err }()
- select {
- case err := <-done:
- if !errors.Is(err, context.Canceled) {
- t.Errorf("canceled waiter: %v", err)
+ synctest.Wait()
+ cancel()
+ if err := <-leader; !errors.Is(err, context.Canceled) {
+ t.Errorf("leader: %v", err)
}
- case <-time.After(time.Second):
- t.Error("canceled waiter blocked behind lookup")
- }
- close(release)
- wg.Wait()
- if calls.Load() != 1 {
- t.Fatalf("concurrent lookups: %d, want 1", calls.Load())
- }
+ <-waiter
+ v, ok, err := identity.Who(context.Background(), remote)
+ if v != want || !ok || err != nil {
+ t.Fatalf("later call: %+v, %v, %v", v, ok, err)
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("lookups = %d, want canceled lookup plus one retry", calls.Load())
+ }
+ })
+}
+
+func TestCachedIdentityPanicReleasesWaiters(t *testing.T) {
+ synctest.Test(t, func(t *testing.T) {
+ var calls atomic.Int32
+ started, release := make(chan struct{}), make(chan struct{})
+ want := Visitor{Login: "alice@github"}
+ identity := NewCachedIdentity(visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) {
+ if calls.Add(1) == 1 {
+ close(started)
+ <-release
+ panic("lookup panic")
+ }
+ return want, true, nil
+ }), time.Now)
+ remote := netip.MustParseAddrPort("100.64.0.1:1234")
+ panicked := make(chan any, 1)
+ go func() {
+ defer func() { panicked <- recover() }()
+ _, _, _ = identity.Who(context.Background(), remote)
+ }()
+ <-started
+ waiter := make(chan struct{})
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ go func() {
+ defer close(waiter)
+ v, ok, err := identity.Who(ctx, remote)
+ if v != want || !ok || err != nil {
+ t.Errorf("waiter after panic: %+v, %v, %v", v, ok, err)
+ }
+ }()
+ synctest.Wait()
+ close(release)
+ if got := <-panicked; got != "lookup panic" {
+ t.Errorf("panic = %v", got)
+ }
+ <-waiter
+ v, ok, err := identity.Who(ctx, remote)
+ if v != want || !ok || err != nil {
+ t.Fatalf("later call: %+v, %v, %v", v, ok, err)
+ }
+ if calls.Load() != 2 {
+ t.Fatalf("lookups = %d, want panic plus one retry", calls.Load())
+ }
+ })
}
func TestAnonymousSource(t *testing.T) {
diff --git a/internal/tsidentity/whois.go b/internal/tsidentity/whois.go
index a0bd8eade..eb1596826 100644
--- a/internal/tsidentity/whois.go
+++ b/internal/tsidentity/whois.go
@@ -42,6 +42,7 @@ func New(socketPath string, timeout time.Duration) edge.VisitorIdentity {
}
func (i *identity) Who(ctx context.Context, remote netip.AddrPort) (edge.Visitor, bool, error) {
+ remote = netip.AddrPortFrom(remote.Addr().Unmap(), remote.Port())
endpoint := "http://local-tailscaled.sock/localapi/v0/whois?" + url.Values{"addr": {remote.String()}}.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
diff --git a/internal/tsidentity/whois_test.go b/internal/tsidentity/whois_test.go
index 58d5f6724..22f70bec5 100644
--- a/internal/tsidentity/whois_test.go
+++ b/internal/tsidentity/whois_test.go
@@ -35,10 +35,14 @@ func fakeWhois(t *testing.T, handler http.HandlerFunc) string {
}
func TestWhoisParsesLoginNameNode(t *testing.T) {
- for _, addr := range []string{"100.64.0.1:4321", "[fd7a:115c:a1e0::1]:4321"} {
+ for _, addr := range []string{"100.64.0.1:4321", "[fd7a:115c:a1e0::1]:4321", "[::ffff:100.64.0.1]:4321"} {
t.Run(addr, func(t *testing.T) {
+ wantAddr := addr
+ if addr == "[::ffff:100.64.0.1]:4321" {
+ wantAddr = "100.64.0.1:4321"
+ }
path := fakeWhois(t, func(w http.ResponseWriter, r *http.Request) {
- if r.Method != "GET" || r.Host != "local-tailscaled.sock" || r.URL.Path != "/localapi/v0/whois" || r.URL.Query().Get("addr") != addr {
+ if r.Method != "GET" || r.Host != "local-tailscaled.sock" || r.URL.Path != "/localapi/v0/whois" || r.URL.Query().Get("addr") != wantAddr {
t.Errorf("request: %s %s host=%q", r.Method, r.URL, r.Host)
}
fmt.Fprint(w, `{"Node":{"ComputedName":"Laptop","Tags":null},"UserProfile":{"LoginName":"Alice@github","DisplayName":"Alïce\r\n"}}`)