99 "context"
1010 "log/slog"
1111 "slices"
12+ "sync"
1213
1314 mpi "github.com/nginx/agent/v3/api/grpc/mpi/v1"
1415
3940 fileUpdatesChannel chan file.FileUpdateMessage
4041 cancel context.CancelFunc
4142 instancesWithConfigApplyInProgress []string
43+ watcherMutex sync.Mutex
4244 }
4345
4446 instanceWatcherServiceInterface interface {
@@ -65,6 +67,7 @@ func NewWatcher(agentConfig *config.Config) *Watcher {
6567 instanceHealthChannel : make (chan health.InstanceHealthMessage ),
6668 fileUpdatesChannel : make (chan file.FileUpdateMessage ),
6769 instancesWithConfigApplyInProgress : []string {},
70+ watcherMutex : sync.Mutex {},
6871 }
6972}
7073
@@ -148,6 +151,8 @@ func (w *Watcher) handleConfigApplyRequest(ctx context.Context, msg *bus.Message
148151
149152 instanceID := request .ConfigApplyRequest .GetOverview ().GetConfigVersion ().GetInstanceId ()
150153
154+ w .watcherMutex .Lock ()
155+ defer w .watcherMutex .Unlock ()
151156 w .instancesWithConfigApplyInProgress = append (w .instancesWithConfigApplyInProgress , instanceID )
152157 w .fileWatcherService .SetEnabled (false )
153158}
@@ -163,6 +168,8 @@ func (w *Watcher) handleConfigApplySuccess(ctx context.Context, msg *bus.Message
163168
164169 instanceID := response .GetInstanceId ()
165170
171+ w .watcherMutex .Lock ()
172+ defer w .watcherMutex .Unlock ()
166173 w .instancesWithConfigApplyInProgress = slices .DeleteFunc (
167174 w .instancesWithConfigApplyInProgress ,
168175 func (element string ) bool {
@@ -191,6 +198,8 @@ func (w *Watcher) handleConfigApplyComplete(ctx context.Context, msg *bus.Messag
191198
192199 instanceID := response .GetInstanceId ()
193200
201+ w .watcherMutex .Lock ()
202+ defer w .watcherMutex .Unlock ()
194203 w .instancesWithConfigApplyInProgress = slices .DeleteFunc (
195204 w .instancesWithConfigApplyInProgress ,
196205 func (element string ) bool {
@@ -210,7 +219,7 @@ func (w *Watcher) monitorWatchers(ctx context.Context) {
210219 w .handleInstanceUpdates (newCtx , message )
211220 case message := <- w .nginxConfigContextChannel :
212221 newCtx := context .WithValue (ctx , logger .CorrelationIDContextKey , message .CorrelationID )
213-
222+ w . watcherMutex . Lock ()
214223 if ! slices .Contains (w .instancesWithConfigApplyInProgress , message .NginxConfigContext .InstanceID ) {
215224 slog .DebugContext (
216225 newCtx ,
@@ -229,6 +238,7 @@ func (w *Watcher) monitorWatchers(ctx context.Context) {
229238 "nginx_config_context" , message .NginxConfigContext ,
230239 )
231240 }
241+ w .watcherMutex .Unlock ()
232242 case message := <- w .instanceHealthChannel :
233243 newCtx := context .WithValue (ctx , logger .CorrelationIDContextKey , message .CorrelationID )
234244 w .messagePipe .Process (newCtx , & bus.Message {
0 commit comments