Skip to content

Commit 0e6ed92

Browse files
committed
use sync.Once - Events should return the same event channel
Signed-off-by: Davanum Srinivas <[email protected]>
1 parent df96b80 commit 0e6ed92

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

store-client/pkg/client/mongodb_client.go

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"fmt"
2020
"log/slog"
2121
"strings"
22+
"sync"
2223

2324
"github.com/nvidia/nvsentinel/data-models/pkg/model"
2425
"github.com/nvidia/nvsentinel/store-client/pkg/config"
@@ -887,26 +888,33 @@ type mongoSessionContext struct {
887888
}
888889

889890
type mongoChangeStreamWatcher struct {
890-
watcher *mongoWatcher.ChangeStreamWatcher
891+
watcher *mongoWatcher.ChangeStreamWatcher
892+
eventChan chan Event
893+
initOnce sync.Once
891894
}
892895

893896
func (w *mongoChangeStreamWatcher) Start(ctx context.Context) {
894897
w.watcher.Start(ctx)
895898
}
896899

900+
// Events returns the event channel for this watcher.
901+
// The returned channel is initialized once and cached, so multiple calls
902+
// return the same channel. Safe for concurrent use.
897903
func (w *mongoChangeStreamWatcher) Events() <-chan Event {
898-
bsonChan := w.watcher.Events()
899-
eventChan := make(chan Event)
904+
w.initOnce.Do(func() {
905+
w.eventChan = make(chan Event)
906+
bsonChan := w.watcher.Events()
900907

901-
go func() {
902-
defer close(eventChan)
908+
go func() {
909+
defer close(w.eventChan)
903910

904-
for rawEvent := range bsonChan {
905-
eventChan <- &mongoEvent{rawEvent: rawEvent}
906-
}
907-
}()
911+
for rawEvent := range bsonChan {
912+
w.eventChan <- &mongoEvent{rawEvent: rawEvent}
913+
}
914+
}()
915+
})
908916

909-
return eventChan
917+
return w.eventChan
910918
}
911919

912920
func (w *mongoChangeStreamWatcher) MarkProcessed(ctx context.Context, token []byte) error {

0 commit comments

Comments
 (0)