Skip to content

Commit 9ae98dc

Browse files
committed
Refactor server context handling in server.go to prevent race conditions
- Updated background initialization methods to use read locks for accessing server context. - Added cancellation of the old context in StartServer to avoid potential race conditions. - Improved tool re-indexing logic after configuration reload to ensure thread safety.
1 parent 5e7615d commit 9ae98dc

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

internal/server/server.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,10 +190,16 @@ func (s *Server) backgroundInitialization() {
190190

191191
// Start background connection attempts
192192
s.updateStatus("Connecting", "Connecting to upstream servers...")
193-
go s.backgroundConnections(s.serverCtx)
193+
s.mu.RLock()
194+
ctx := s.serverCtx
195+
s.mu.RUnlock()
196+
go s.backgroundConnections(ctx)
194197

195198
// Start background tool discovery and indexing
196-
go s.backgroundToolIndexing(s.serverCtx)
199+
s.mu.RLock()
200+
ctx = s.serverCtx
201+
s.mu.RUnlock()
202+
go s.backgroundToolIndexing(ctx)
197203

198204
// Only set "Ready" status if the server is not already running
199205
// If server is running, don't override the "Running" status
@@ -726,6 +732,11 @@ func (s *Server) StartServer(ctx context.Context) error {
726732
return fmt.Errorf("server is already running")
727733
}
728734

735+
// Cancel the old context before creating a new one to avoid race conditions
736+
if s.cancelFunc != nil {
737+
s.cancelFunc()
738+
}
739+
729740
s.serverCtx, s.cancelFunc = context.WithCancel(ctx)
730741

731742
go func() {
@@ -899,7 +910,10 @@ func (s *Server) ReloadConfiguration() error {
899910

900911
// Trigger tool re-indexing after configuration changes
901912
go func() {
902-
if err := s.discoverAndIndexTools(s.serverCtx); err != nil {
913+
s.mu.RLock()
914+
ctx := s.serverCtx
915+
s.mu.RUnlock()
916+
if err := s.discoverAndIndexTools(ctx); err != nil {
903917
s.logger.Error("Failed to re-index tools after config reload", zap.Error(err))
904918
}
905919
}()

0 commit comments

Comments
 (0)