From 3584cd2da5fca834b0f211b26d3b044c4f3b383c Mon Sep 17 00:00:00 2001 From: Sarthak Chaudhari Date: Mon, 30 Nov 2026 12:34:09 +0530 Subject: [PATCH 1/2] [MeshSync] Publish active exec channels immediately and deduplicate ticker When an ActiveExecEntity request arrives, processActiveExecRequest spawned streamChannelPool() which started a 10s ticker and waited for the first tick before publishing. This left requesting clients waiting up to 10 seconds for initial channel data. Furthermore, repeated requests spawned un-deduplicated background tickers and goroutines. Extract publishActiveChannels() to publish an immediate snapshot upon request arrival, and guard the background periodic ticker with sync.Once so only a single stream loop runs across the Handler lifetime. Signed-off-by: Sarthak Chaudhari --- meshsync/exec.go | 62 +++++++++++++++++++++++-------------------- meshsync/exec_test.go | 43 ++++++++++++++++++++++++++++++ meshsync/meshsync.go | 7 ++--- 3 files changed, 80 insertions(+), 32 deletions(-) diff --git a/meshsync/exec.go b/meshsync/exec.go index 49620046..6f20b22b 100644 --- a/meshsync/exec.go +++ b/meshsync/exec.go @@ -106,23 +106,38 @@ func (h *Handler) processExecRequest(obj interface{}, cfg config.ListenerConfig) } h.Log.Debug("Starting session") - err := h.Broker.Publish("active_sessions.exec", &broker.Message{ - ObjectType: broker.ActiveExecObject, - Object: h.getActiveChannels(), - }) - if err != nil { - h.Log.Error(ErrGetObject(err)) + if err := h.publishActiveChannels(); err != nil { + h.Log.Error(err) } go h.streamSession(id, req, cfg) } return nil } + func (h *Handler) processActiveExecRequest() error { - go h.streamChannelPool() + if err := h.publishActiveChannels(); err != nil { + return err + } + + h.streamPoolOnce.Do(func() { + go h.streamChannelPool() + }) return nil } + +func (h *Handler) publishActiveChannels() error { + err := h.Broker.Publish("active_sessions.exec", &broker.Message{ + ObjectType: broker.ActiveExecObject, + Object: h.getActiveChannels(), + }) + if err != nil { + return ErrGetObject(err) + } + return nil +} + func (h *Handler) getActiveChannels() []*string { ids := h.activeSessionIDs() activeChannels := make([]*string, 0, len(ids)) @@ -134,31 +149,20 @@ func (h *Handler) getActiveChannels() []*string { } func (h *Handler) streamChannelPool() { - go func() { - ticker := time.NewTicker(10 * time.Second) - defer ticker.Stop() - - publish := func() { - err := h.Broker.Publish("active_sessions.exec", &broker.Message{ - ObjectType: broker.ActiveExecObject, - Object: h.getActiveChannels(), - }) - if err != nil { - h.Log.Error(ErrGetObject(err)) - } - } + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() - loop: - for { - select { - case <-h.stopSignal(): - break loop - case <-ticker.C: - publish() + for { + select { + case <-h.stopSignal(): + h.Log.Debug("Stopping streamChannelPool") + return + case <-ticker.C: + if err := h.publishActiveChannels(); err != nil { + h.Log.Error(err) } } - h.Log.Debug("Stopping streamChannelPool") - }() + } } // streamSession wires up one exec session: its input subscription and teardown, diff --git a/meshsync/exec_test.go b/meshsync/exec_test.go index 6aff3741..53387660 100644 --- a/meshsync/exec_test.go +++ b/meshsync/exec_test.go @@ -331,3 +331,46 @@ func TestTerminalSizeQueueAdapter(t *testing.T) { } }) } + +func TestProcessActiveExecRequest_ImmediatePublishAndDeduplicatedStream(t *testing.T) { + defer goleak.VerifyNone(t, goleak.IgnoreCurrent()) + + br := channel.NewChannelBrokerHandler() + stopCh := channels.NewStopChannel() + h := &Handler{ + Log: newTestLogger(t), + Broker: br, + channelPool: map[string]channels.GenericChannel{ + channels.Stop: stopCh, + }, + } + + msgCh := make(chan *broker.Message, 10) + err := br.SubscribeWithChannel("active_sessions.exec", "", msgCh) + if err != nil { + t.Fatalf("SubscribeWithChannel: %v", err) + } + defer func() { + _ = br.Unsubscribe("active_sessions.exec") + }() + + err = h.processActiveExecRequest() + if err != nil { + t.Fatalf("processActiveExecRequest error: %v", err) + } + + select { + case msg := <-msgCh: + if msg.ObjectType != broker.ActiveExecObject { + t.Errorf("expected ObjectType %s, got %s", broker.ActiveExecObject, msg.ObjectType) + } + case <-time.After(500 * time.Millisecond): + t.Fatal("expected immediate publication on active_sessions.exec, but timed out waiting for 10s ticker") + } + + for i := 0; i < 5; i++ { + _ = h.processActiveExecRequest() + } + + close(stopCh) +} diff --git a/meshsync/meshsync.go b/meshsync/meshsync.go index f248cb2a..e5168701 100644 --- a/meshsync/meshsync.go +++ b/meshsync/meshsync.go @@ -56,9 +56,10 @@ type Handler struct { // extraStop is the optional stop signal set by SetStopChannel; stopCh is // the resolved signal every loop selects on, built once by stopSignal. - extraStop <-chan struct{} - stopOnce sync.Once - stopCh <-chan struct{} + extraStop <-chan struct{} + stopOnce sync.Once + stopCh <-chan struct{} + streamPoolOnce sync.Once } func GetListOptionsFunc(config config.Handler) (func(*v1.ListOptions), error) { From 4c5ef1a38542eeca483126150b7e24fef8fe0944 Mon Sep 17 00:00:00 2001 From: Sarthak Chaudhari Date: Mon, 30 Nov 2026 13:00:36 +0530 Subject: [PATCH 2/2] [MeshSync] Start periodic stream before publish and verify ticker deduplication Start streamChannelPool before the immediate publish attempt so a transient broker failure does not leave periodic active-session updates disabled. Add an unexported streamPoolTicker hook on Handler to test controlled ticks and assert that repeated active-exec requests create only a single periodic loop, along with defer cleanup and error-recovery coverage. Signed-off-by: Sarthak Chaudhari --- meshsync/exec.go | 26 +++++--- meshsync/exec_test.go | 139 ++++++++++++++++++++++++++++++++++++------ meshsync/meshsync.go | 9 +-- 3 files changed, 143 insertions(+), 31 deletions(-) diff --git a/meshsync/exec.go b/meshsync/exec.go index 6f20b22b..111b1233 100644 --- a/meshsync/exec.go +++ b/meshsync/exec.go @@ -116,15 +116,13 @@ func (h *Handler) processExecRequest(obj interface{}, cfg config.ListenerConfig) } func (h *Handler) processActiveExecRequest() error { - if err := h.publishActiveChannels(); err != nil { - return err - } - + // Start the periodic stream before immediate publication so a transient + // broker error does not leave periodic updates unstarted. h.streamPoolOnce.Do(func() { go h.streamChannelPool() }) - return nil + return h.publishActiveChannels() } func (h *Handler) publishActiveChannels() error { @@ -149,15 +147,27 @@ func (h *Handler) getActiveChannels() []*string { } func (h *Handler) streamChannelPool() { - ticker := time.NewTicker(10 * time.Second) - defer ticker.Stop() + var ( + ticks <-chan time.Time + stop func() + ) + if h.streamPoolTicker != nil { + ticks, stop = h.streamPoolTicker() + } else { + ticker := time.NewTicker(10 * time.Second) + ticks = ticker.C + stop = ticker.Stop + } + if stop != nil { + defer stop() + } for { select { case <-h.stopSignal(): h.Log.Debug("Stopping streamChannelPool") return - case <-ticker.C: + case <-ticks: if err := h.publishActiveChannels(); err != nil { h.Log.Error(err) } diff --git a/meshsync/exec_test.go b/meshsync/exec_test.go index 53387660..24fc78c9 100644 --- a/meshsync/exec_test.go +++ b/meshsync/exec_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" @@ -332,45 +333,145 @@ func TestTerminalSizeQueueAdapter(t *testing.T) { }) } -func TestProcessActiveExecRequest_ImmediatePublishAndDeduplicatedStream(t *testing.T) { - defer goleak.VerifyNone(t, goleak.IgnoreCurrent()) +type publishToggleBroker struct { + broker.Handler + failPublish atomic.Bool +} + +var _ broker.Handler = (*publishToggleBroker)(nil) + +func (b *publishToggleBroker) Publish(subject string, message *broker.Message) error { + if b.failPublish.Load() { + return context.Canceled + } + return b.Handler.Publish(subject, message) +} + +type activeExecHarness struct { + handler *Handler + broker *publishToggleBroker + msgCh chan *broker.Message + tickCh chan time.Time + started chan struct{} + tickerCalls atomic.Int32 +} + +func newActiveExecHarness(t *testing.T) (*activeExecHarness, func()) { + t.Helper() + + br := &publishToggleBroker{Handler: channel.NewChannelBrokerHandler()} + msgCh := make(chan *broker.Message, 10) + if err := br.SubscribeWithChannel("active_sessions.exec", "", msgCh); err != nil { + t.Fatalf("SubscribeWithChannel: %v", err) + } - br := channel.NewChannelBrokerHandler() stopCh := channels.NewStopChannel() - h := &Handler{ + ah := &activeExecHarness{ + broker: br, + msgCh: msgCh, + tickCh: make(chan time.Time), + started: make(chan struct{}, 1), + } + ah.handler = &Handler{ Log: newTestLogger(t), Broker: br, channelPool: map[string]channels.GenericChannel{ channels.Stop: stopCh, }, + streamPoolTicker: func() (<-chan time.Time, func()) { + ah.tickerCalls.Add(1) + select { + case ah.started <- struct{}{}: + default: + } + return ah.tickCh, func() {} + }, } - msgCh := make(chan *broker.Message, 10) - err := br.SubscribeWithChannel("active_sessions.exec", "", msgCh) - if err != nil { - t.Fatalf("SubscribeWithChannel: %v", err) - } - defer func() { + return ah, func() { + close(stopCh) _ = br.Unsubscribe("active_sessions.exec") - }() - - err = h.processActiveExecRequest() - if err != nil { - t.Fatalf("processActiveExecRequest error: %v", err) } +} +func awaitActiveExecMessage(t *testing.T, msgCh <-chan *broker.Message, desc string) { + t.Helper() select { case msg := <-msgCh: if msg.ObjectType != broker.ActiveExecObject { - t.Errorf("expected ObjectType %s, got %s", broker.ActiveExecObject, msg.ObjectType) + t.Errorf("%s: expected ObjectType %s, got %s", desc, broker.ActiveExecObject, msg.ObjectType) } case <-time.After(500 * time.Millisecond): - t.Fatal("expected immediate publication on active_sessions.exec, but timed out waiting for 10s ticker") + t.Fatalf("timed out waiting for %s", desc) + } +} + +func awaitSignal(t *testing.T, ch <-chan struct{}, desc string) { + t.Helper() + select { + case <-ch: + case <-time.After(500 * time.Millisecond): + t.Fatalf("timed out waiting for %s", desc) + } +} + +func sendTick(t *testing.T, tickCh chan<- time.Time) { + t.Helper() + select { + case tickCh <- time.Now(): + case <-time.After(500 * time.Millisecond): + t.Fatal("timed out delivering periodic tick") } +} + +func TestProcessActiveExecRequest_ImmediatePublishAndDeduplicatedStream(t *testing.T) { + defer goleak.VerifyNone(t, goleak.IgnoreCurrent()) + ah, cleanup := newActiveExecHarness(t) + defer cleanup() + + if err := ah.handler.processActiveExecRequest(); err != nil { + t.Fatalf("processActiveExecRequest error: %v", err) + } + awaitActiveExecMessage(t, ah.msgCh, "immediate publication") + awaitSignal(t, ah.started, "streamChannelPool start") for i := 0; i < 5; i++ { - _ = h.processActiveExecRequest() + if err := ah.handler.processActiveExecRequest(); err != nil { + t.Fatalf("repeat processActiveExecRequest[%d] error: %v", i, err) + } + awaitActiveExecMessage(t, ah.msgCh, "repeat immediate publication") + } + + if got := ah.tickerCalls.Load(); got != 1 { + t.Fatalf("expected streamChannelPool ticker to be created once, got %d", got) + } + + sendTick(t, ah.tickCh) + awaitActiveExecMessage(t, ah.msgCh, "periodic publication after tick") + + select { + case extra := <-ah.msgCh: + t.Fatalf("unexpected duplicate periodic publication: %+v", extra) + case <-time.After(50 * time.Millisecond): + } +} + +func TestProcessActiveExecRequest_StartsPeriodicStreamOnPublishError(t *testing.T) { + defer goleak.VerifyNone(t, goleak.IgnoreCurrent()) + ah, cleanup := newActiveExecHarness(t) + defer cleanup() + + ah.broker.failPublish.Store(true) + if err := ah.handler.processActiveExecRequest(); err == nil { + t.Fatal("expected immediate publish error, got nil") + } + + awaitSignal(t, ah.started, "periodic stream start after failed publish") + if got := ah.tickerCalls.Load(); got != 1 { + t.Fatalf("expected 1 periodic stream loop, got %d", got) } - close(stopCh) + ah.broker.failPublish.Store(false) + sendTick(t, ah.tickCh) + awaitActiveExecMessage(t, ah.msgCh, "recovered periodic publication") } diff --git a/meshsync/meshsync.go b/meshsync/meshsync.go index e5168701..99b67857 100644 --- a/meshsync/meshsync.go +++ b/meshsync/meshsync.go @@ -56,10 +56,11 @@ type Handler struct { // extraStop is the optional stop signal set by SetStopChannel; stopCh is // the resolved signal every loop selects on, built once by stopSignal. - extraStop <-chan struct{} - stopOnce sync.Once - stopCh <-chan struct{} - streamPoolOnce sync.Once + extraStop <-chan struct{} + stopOnce sync.Once + stopCh <-chan struct{} + streamPoolOnce sync.Once + streamPoolTicker func() (<-chan time.Time, func()) } func GetListOptionsFunc(config config.Handler) (func(*v1.ListOptions), error) {