@@ -105,22 +105,9 @@ func (m *outputModule) Start(ctx context.Context) error {
105105 runCtx , cancel := context .WithCancel (context .Background ())
106106 m .cancel = cancel
107107
108- m .health .SetRunning (true )
109- m .log .LogStreamStart ("bento.output" ,
110- slog .String ("source_topic" , m .sourceTopic ),
111- slog .String ("source_broker" , m .sourceBroker ),
112- )
113-
114- go func () {
115- defer close (m .done )
116- if runErr := stream .Run (runCtx ); runErr != nil && runCtx .Err () == nil {
117- m .metrics .RecordError ()
118- m .log .LogStreamError (runErr )
119- }
120- }()
121-
122- // Subscribe to the host EventBus topic. When messages arrive, forward them
123- // to the Bento producer.
108+ // Subscribe to the host EventBus topic before starting the stream. When
109+ // messages arrive, forward them to the Bento producer. Subscribing first
110+ // avoids leaking the stream goroutine if Subscribe returns an error.
124111 producerFnRef := m .producerFn
125112 metrics := m .metrics
126113 log := m .log
@@ -140,9 +127,29 @@ func (m *outputModule) Start(ctx context.Context) error {
140127 log .LogMessageProcessed (sourceTopic )
141128 return nil
142129 }); err != nil {
130+ // Cancel the context since the stream goroutine was never launched.
131+ cancel ()
143132 return fmt .Errorf ("bento.output %q: subscribe to topic %q: %w" , m .name , m .sourceTopic , err )
144133 }
145134
135+ m .health .SetRunning (true )
136+ m .metrics .MarkStarted ()
137+ m .log .LogStreamStart ("bento.output" ,
138+ slog .String ("source_topic" , m .sourceTopic ),
139+ slog .String ("source_broker" , m .sourceBroker ),
140+ )
141+
142+ go func () {
143+ defer close (m .done )
144+ if runErr := stream .Run (runCtx ); runCtx .Err () == nil {
145+ m .health .SetRunning (false )
146+ if runErr != nil {
147+ m .metrics .RecordError ()
148+ m .log .LogStreamError (runErr )
149+ }
150+ }
151+ }()
152+
146153 return nil
147154}
148155
@@ -168,6 +175,7 @@ func (m *outputModule) Stop(ctx context.Context) error {
168175 }
169176
170177 m .health .SetRunning (false )
178+ m .metrics .MarkStopped ()
171179 snap := m .metrics .Snapshot ()
172180 m .log .LogStreamStop (snap .MessagesIn ,
173181 slog .String ("source_topic" , m .sourceTopic ),
0 commit comments