Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 42 additions & 28 deletions meshsync/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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,
Expand Down
144 changes: 144 additions & 0 deletions meshsync/exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -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()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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")
}
8 changes: 5 additions & 3 deletions meshsync/meshsync.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down