diff --git a/server/Makefile b/server/Makefile index 1c593348..c9b773e5 100644 --- a/server/Makefile +++ b/server/Makefile @@ -28,7 +28,7 @@ build: proto go build -o axon-server ./cmd/... test: - go test -v ./... + go test -race -v ./... clean: rm -rf $(GENERATED_DIR) axon-server diff --git a/server/tunnel/client_registry.go b/server/tunnel/client_registry.go index 3384e346..692b76ae 100644 --- a/server/tunnel/client_registry.go +++ b/server/tunnel/client_registry.go @@ -118,45 +118,16 @@ type clientEntry struct { // leaving can be logged once rather than once per stream. instances map[string]int - // idle is a stack of streams believed to be idle, so dispatch can take - // one in O(1) instead of scanning and sorting every stream on the token. - // It is a hint, not the truth — busy is: a handle may sit here while - // concurrently acquired elsewhere, so acquisition still confirms with - // TryAcquire and skips losers. LIFO is deliberate: the most recently - // released stream is the one most recently proven healthy, which is the - // preference the old LastSuccessAt sort was reaching for. - idle []*StreamHandle + // idle holds the streams believed to be idle, so dispatch can take one + // in O(1) instead of scanning every stream on the token. It has its own + // lock: acquire and release hold the registry lock only for reading. + idle idleStack } -// pushIdle returns a stream to the idle stack. Callers hold r.mu. -func (e *clientEntry) pushIdle(s *StreamHandle) { - e.idle = append(e.idle, s) -} - -// popIdle takes the newest idle stream, dropping entries that are stale -// (already busy, or no longer registered). Callers hold r.mu. -func (e *clientEntry) popIdle() *StreamHandle { - for len(e.idle) > 0 { - s := e.idle[len(e.idle)-1] - e.idle = e.idle[:len(e.idle)-1] - if e.Streams[s.StreamID] != s { - continue // unregistered while queued - } - if s.TryAcquire() { - return s - } - } - return nil -} - -// removeIdle drops a stream from the idle stack. Callers hold r.mu. -func (e *clientEntry) removeIdle(streamID string) { - for i, s := range e.idle { - if s.StreamID == streamID { - e.idle = append(e.idle[:i], e.idle[i+1:]...) - return - } - } +// holds reports whether s is still the registered handle for its stream ID. +// Callers hold the registry lock, for reading at least. +func (e *clientEntry) holds(s *StreamHandle) bool { + return e.Streams[s.StreamID] == s } // ErrTokenStreamCap is returned by Register when the token already holds @@ -252,7 +223,7 @@ func (r *ClientRegistry) RegisterStream(token broker.Token, identity ClientIdent existing.Streams[stream.StreamID] = stream existing.instances[identity.InstanceID]++ stream.onRelease = r.makeOnRelease(key, stream) - existing.pushIdle(stream) + existing.idle.push(stream) // Debug: the entry already existed, so the token's reachability here // has not changed — only its stream count. Registered new client // below is the transition, and stays at Info. @@ -278,7 +249,7 @@ func (r *ClientRegistry) RegisterStream(token broker.Token, identity ClientIdent instances: map[string]int{identity.InstanceID: 1}, } stream.onRelease = r.makeOnRelease(key, stream) - entry.pushIdle(stream) + entry.idle.push(stream) r.entries[key] = entry r.logger.Info("Registered new client", @@ -310,13 +281,13 @@ func (r *ClientRegistry) IsBrokerServerRegistered(token broker.Token) bool { // entry may be gone or the handle replaced. func (r *ClientRegistry) makeOnRelease(key string, s *StreamHandle) func() { return func() { - r.mu.Lock() - defer r.mu.Unlock() + r.mu.RLock() + defer r.mu.RUnlock() entry, ok := r.entries[key] if !ok || entry.Streams[s.StreamID] != s { return } - entry.pushIdle(s) + entry.idle.push(s) } } @@ -344,7 +315,7 @@ func (r *ClientRegistry) UnregisterStream(token broker.Token, streamID string) U } delete(entry.Streams, streamID) - entry.removeIdle(streamID) + entry.idle.remove(streamID) instanceID := stream.Identity.InstanceID entry.instances[instanceID]-- @@ -406,22 +377,23 @@ func (r *ClientRegistry) GetIdentity(token broker.Token) *ClientIdentity { // The caller owns the returned stream's busy flag and must call Release() // when the call fully terminates. func (r *ClientRegistry) AcquireIdleStream(token broker.Token) (handle *StreamHandle, allBusy bool) { - r.mu.Lock() - defer r.mu.Unlock() + r.mu.RLock() + defer r.mu.RUnlock() entry, ok := r.entries[token.Hashed()] if !ok || len(entry.Streams) == 0 { return nil, false } - if s := entry.popIdle(); s != nil { + if s := entry.idle.pop(entry.holds); s != nil { return s, false } // The stack is a hint and can drift empty while a stream is in fact // idle (a handle released after being unregistered, say). Falling back // to a scan keeps "all busy" honest — reporting a false all-busy would - // stall dispatch until the caller's deadline for no reason. + // stall dispatch until the caller's deadline for no reason. TryAcquire is + // atomic, so the scan needs only the read lock that keeps Streams stable. for _, s := range entry.Streams { if s.TryAcquire() { return s, false diff --git a/server/tunnel/client_registry_test.go b/server/tunnel/client_registry_test.go index 3a1cbc57..d53c0483 100644 --- a/server/tunnel/client_registry_test.go +++ b/server/tunnel/client_registry_test.go @@ -2,12 +2,17 @@ package tunnel import ( "fmt" + "runtime" + "sync" + "sync/atomic" "testing" + "time" pb "github.com/cortexapps/axon-server/.generated/proto/tunnelpb" "github.com/cortexapps/axon-server/broker" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.uber.org/zap" "go.uber.org/zap/zaptest" ) @@ -324,3 +329,151 @@ func mustRegister(t *testing.T, r *ClientRegistry, token broker.Token, id Client _, err := r.Register(token, id, h) require.NoError(t, err) } + +// runWithin fails the test if fn does not return within d, so a lock +// regression shows up as a failure rather than a hung test binary. +func runWithin(t *testing.T, d time.Duration, what string, fn func()) { + t.Helper() + done := make(chan struct{}) + go func() { + defer close(done) + fn() + }() + select { + case <-done: + case <-time.After(d): + t.Fatalf("%s did not return within %s; is it waiting on the registry write lock?", what, d) + } +} + +// Acquire and release run once per dispatched call each. They must not take +// the registry's write lock, or every call on the server — on every token — +// queues on one mutex behind registration and identity lookups. Holding the +// read lock here stands in for any concurrent reader: a write-lock taker +// would block until it is released. +func TestAcquireAndReleaseNeedOnlyTheReadLock(t *testing.T) { + registry := NewClientRegistry(zaptest.NewLogger(t)) + token := broker.NewToken("token-abc") + _, err := registry.Register(token, testIdentity("tenant-1"), testStream("s1")) + require.NoError(t, err) + + registry.mu.RLock() + defer registry.mu.RUnlock() + + var s *StreamHandle + runWithin(t, 2*time.Second, "AcquireIdleStream", func() { + s, _ = registry.AcquireIdleStream(token) + }) + require.NotNil(t, s) + runWithin(t, 2*time.Second, "Release", s.Release) + + // The released stream is back on the idle stack. + runWithin(t, 2*time.Second, "AcquireIdleStream after Release", func() { + s, _ = registry.AcquireIdleStream(token) + }) + require.NotNil(t, s) + assert.Equal(t, "s1", s.StreamID) +} + +// Hammers acquire/release against stream churn on the same tokens. Its +// value is under -race (make test runs it that way): read-lock holders touch +// idle concurrently, and a missing idleStack lock shows up only as a data race -- +// TryAcquire's CAS keeps a stream from being handed out twice regardless. +// What it checks without the detector is that no stream is lost or stuck +// busy once the churn stops. +func TestConcurrentAcquireReleaseWithChurn(t *testing.T) { + registry := NewClientRegistry(zap.NewNop()) + tokens := []broker.Token{broker.NewToken("token-a"), broker.NewToken("token-b")} + for _, tok := range tokens { + for i := 0; i < 4; i++ { + _, err := registry.Register(tok, testIdentity("tenant"), testStream(fmt.Sprintf("%s-base-%d", tok.Hashed()[:6], i))) + require.NoError(t, err) + } + } + + var inUse sync.Map // *StreamHandle -> *atomic.Int32 + holders := func(s *StreamHandle) *atomic.Int32 { + v, _ := inUse.LoadOrStore(s, new(atomic.Int32)) + return v.(*atomic.Int32) + } + + stop := make(chan struct{}) + var wg sync.WaitGroup + var acquired, doubled atomic.Int64 + + for w := 0; w < 16; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + tok := tokens[w%len(tokens)] + for { + select { + case <-stop: + return + default: + } + s, _ := registry.AcquireIdleStream(tok) + if s == nil { + runtime.Gosched() + continue + } + acquired.Add(1) + if holders(s).Add(1) != 1 { + doubled.Add(1) + } + registry.GetIdentity(tok) + holders(s).Add(-1) + s.Release() + } + }(w) + } + + // Churn: streams come and go on both tokens while calls run. + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + tok := tokens[i%len(tokens)] + id := fmt.Sprintf("churn-%d", i) + if _, err := registry.Register(tok, testIdentity("tenant"), testStream(id)); err != nil { + t.Errorf("register: %v", err) + return + } + registry.Unregister(tok, id) + } + }() + + time.Sleep(300 * time.Millisecond) + close(stop) + wg.Wait() + + assert.Zero(t, doubled.Load(), "a stream was handed to two callers at once") + for _, tok := range tokens { + entry := registry.entries[tok.Hashed()] + // Duplicates are allowed (the stack is a hint), but only a handful: + // each needs a release to land between a pop finding the stack empty + // and the fallback scan. + assert.LessOrEqual(t, entry.idle.len(), 4*len(entry.Streams), "idle stack grew without bound") + } + assert.Positive(t, acquired.Load()) + + // Every base stream is idle again and can be acquired exactly once. + for _, tok := range tokens { + got := map[string]bool{} + for { + s, allBusy := registry.AcquireIdleStream(tok) + if s == nil { + assert.True(t, allBusy) + break + } + assert.False(t, got[s.StreamID], "stream %s acquired twice", s.StreamID) + got[s.StreamID] = true + } + assert.Len(t, got, 4) + } +} diff --git a/server/tunnel/idle_stack.go b/server/tunnel/idle_stack.go new file mode 100644 index 00000000..34d08f86 --- /dev/null +++ b/server/tunnel/idle_stack.go @@ -0,0 +1,75 @@ +package tunnel + +import "sync" + +// idleStack is one token's stack of streams believed to be idle. +// +// It is a hint, not the truth — each stream's busy flag is: a handle may sit +// here while concurrently acquired elsewhere, so pop confirms with TryAcquire +// and skips losers, and the same handle may briefly appear twice. LIFO is +// deliberate: the most recently released stream is the one most recently +// proven healthy. +// +// It carries its own lock so the dispatch path, which pushes and pops once +// per call, needs only the registry's read lock. Taking the registry's write +// lock there made every dispatch on the server, for every token, queue on one +// mutex alongside stream registration and identity lookups. +type idleStack struct { + mu sync.Mutex + items []*StreamHandle +} + +// push returns a stream to the top of the stack. +func (q *idleStack) push(s *StreamHandle) { + q.mu.Lock() + defer q.mu.Unlock() + q.items = append(q.items, s) +} + +// pop takes the newest stream that is still registered and can be acquired, +// discarding stale entries on the way. registered reports whether a handle is +// still the live one for its stream ID; it is called with the stack's lock +// held, so it must not call back into the stack. +func (q *idleStack) pop(registered func(*StreamHandle) bool) *StreamHandle { + q.mu.Lock() + defer q.mu.Unlock() + for len(q.items) > 0 { + last := len(q.items) - 1 + s := q.items[last] + // Clear the slot so a stream that has since closed is not kept alive + // by the backing array. + q.items[last] = nil + q.items = q.items[:last] + if !registered(s) { + continue // unregistered while queued + } + if s.TryAcquire() { + return s + } + } + return nil +} + +// remove drops a stream from the stack by ID. Only the first match goes; +// any duplicate left behind is discarded by pop once the stream is +// unregistered. +func (q *idleStack) remove(streamID string) { + q.mu.Lock() + defer q.mu.Unlock() + for i, s := range q.items { + if s.StreamID == streamID { + last := len(q.items) - 1 + copy(q.items[i:], q.items[i+1:]) + q.items[last] = nil + q.items = q.items[:last] + return + } + } +} + +// len reports how many entries the stack holds, stale ones included. +func (q *idleStack) len() int { + q.mu.Lock() + defer q.mu.Unlock() + return len(q.items) +} diff --git a/server/tunnel/idle_stack_test.go b/server/tunnel/idle_stack_test.go index 30a911e4..800c1585 100644 --- a/server/tunnel/idle_stack_test.go +++ b/server/tunnel/idle_stack_test.go @@ -179,3 +179,66 @@ func TestIdleStack_StreamCapStillEnforced(t *testing.T) { }) require.ErrorIs(t, err, ErrTokenStreamCap) } + +// The tests below exercise idleStack directly rather than through the registry. + +func allRegistered(*StreamHandle) bool { return true } + +func TestIdleStack_PopIsLIFOAndAcquires(t *testing.T) { + var q idleStack + a, b := testStream("a"), testStream("b") + q.push(a) + q.push(b) + + got := q.pop(allRegistered) + require.Same(t, b, got, "most recently released first") + assert.True(t, got.Busy(), "pop hands the stream out acquired") + + assert.Same(t, a, q.pop(allRegistered)) + assert.Nil(t, q.pop(allRegistered)) +} + +func TestIdleStack_PopSkipsStaleEntries(t *testing.T) { + var q idleStack + live, busy, gone := testStream("live"), testStream("busy"), testStream("gone") + require.True(t, busy.TryAcquire()) + q.push(live) + q.push(busy) + q.push(gone) + + got := q.pop(func(s *StreamHandle) bool { return s != gone }) + assert.Same(t, live, got) + assert.Zero(t, q.len(), "stale entries are discarded, not kept") +} + +func TestIdleStack_Remove(t *testing.T) { + var q idleStack + a, b, c := testStream("a"), testStream("b"), testStream("c") + q.push(a) + q.push(b) + q.push(c) + + q.remove("b") + q.remove("missing") + assert.Equal(t, 2, q.len()) + assert.Same(t, c, q.pop(allRegistered)) + assert.Same(t, a, q.pop(allRegistered)) +} + +// Popped and removed slots must not keep closed streams reachable through +// the backing array. +func TestIdleStack_ClearsVacatedSlots(t *testing.T) { + var q idleStack + a, b, c := testStream("a"), testStream("b"), testStream("c") + q.push(a) + q.push(b) + q.push(c) + backing := q.items[:cap(q.items)] + + q.pop(allRegistered) // c + q.remove("a") // shifts b down + assert.Same(t, b, backing[0]) + for i := 1; i < len(backing); i++ { + assert.Nil(t, backing[i], "slot %d still holds a stream", i) + } +}