diff --git a/meshsync/exec.go b/meshsync/exec.go index 49620046..111b1233 100644 --- a/meshsync/exec.go +++ b/meshsync/exec.go @@ -106,23 +106,36 @@ 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() + // 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 h.publishActiveChannels() +} +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 +147,32 @@ func (h *Handler) getActiveChannels() []*string { } func (h *Handler) streamChannelPool() { - go func() { + var ( + ticks <-chan time.Time + stop func() + ) + if h.streamPoolTicker != nil { + ticks, stop = h.streamPoolTicker() + } else { 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)) - } - } + ticks = ticker.C + stop = ticker.Stop + } + if stop != nil { + defer 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 <-ticks: + 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..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" @@ -331,3 +332,146 @@ func TestTerminalSizeQueueAdapter(t *testing.T) { } }) } + +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) + } + + stopCh := channels.NewStopChannel() + 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() {} + }, + } + + return ah, func() { + close(stopCh) + _ = br.Unsubscribe("active_sessions.exec") + } +} + +func awaitActiveExecMessage(t *testing.T, msgCh <-chan *broker.Message, desc string) { + t.Helper() + select { + case msg := <-msgCh: + if msg.ObjectType != broker.ActiveExecObject { + t.Errorf("%s: expected ObjectType %s, got %s", desc, broker.ActiveExecObject, msg.ObjectType) + } + case <-time.After(500 * time.Millisecond): + 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++ { + 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) + } + + 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 f248cb2a..99b67857 100644 --- a/meshsync/meshsync.go +++ b/meshsync/meshsync.go @@ -56,9 +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{} + 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) {