Skip to content

Commit 64f9931

Browse files
authored
Fix file watcher data race (#1177)
1 parent 5123fe8 commit 64f9931

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

internal/collections/syncset.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package collections
2+
3+
type SyncSet[T comparable] struct {
4+
m SyncMap[T, struct{}]
5+
}
6+
7+
func (s *SyncSet[T]) Has(key T) bool {
8+
_, ok := s.m.Load(key)
9+
return ok
10+
}
11+
12+
func (s *SyncSet[T]) Add(key T) {
13+
s.m.Store(key, struct{}{})
14+
}
15+
16+
func (s *SyncSet[T]) Delete(key T) {
17+
s.m.Delete(key)
18+
}

internal/lsp/server.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,10 @@ type Server struct {
142142
initializeParams *lsproto.InitializeParams
143143
positionEncoding lsproto.PositionEncodingKind
144144

145-
watchEnabled bool
146-
watcherID int
147-
watchers collections.Set[project.WatcherHandle]
145+
watchEnabled bool
146+
watcherID atomic.Uint32
147+
watchers collections.SyncSet[project.WatcherHandle]
148+
148149
logger *project.Logger
149150
projectService *project.Service
150151

@@ -195,7 +196,7 @@ func (s *Server) Client() project.Client {
195196

196197
// WatchFiles implements project.Client.
197198
func (s *Server) WatchFiles(ctx context.Context, watchers []*lsproto.FileSystemWatcher) (project.WatcherHandle, error) {
198-
watcherId := fmt.Sprintf("watcher-%d", s.watcherID)
199+
watcherId := fmt.Sprintf("watcher-%d", s.watcherID.Add(1))
199200
_, err := s.sendRequest(ctx, lsproto.MethodClientRegisterCapability, &lsproto.RegistrationParams{
200201
Registrations: []*lsproto.Registration{
201202
{
@@ -213,7 +214,6 @@ func (s *Server) WatchFiles(ctx context.Context, watchers []*lsproto.FileSystemW
213214

214215
handle := project.WatcherHandle(watcherId)
215216
s.watchers.Add(handle)
216-
s.watcherID++
217217
return handle, nil
218218
}
219219

0 commit comments

Comments
 (0)