Debian Codegraph @

gopls/internal/filewatcher/poll_watcher.go

raw symbols SCIP
1 // Copyright 2025 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package filewatcher
6
7 import (
8 "context"
9 "crypto/sha256"
10 "fmt"
11 "io/fs"
12 "log/slog"
13 "path/filepath"
14 "sync"
15 "time"
16
17 "golang.org/x/tools/gopls/internal/filecache"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/settings"
20 "golang.org/x/tools/gopls/internal/util/bug"
21 "golang.org/x/tools/gopls/internal/util/frob"
22 "golang.org/x/tools/gopls/internal/util/moremaps"
23 "golang.org/x/tools/internal/event"
24 )
25
26 /*
27 Design Notes:
28 The pollWatcher provides a portable, polling-based alternative to fsnotify.
29 Key lessons and design decisions from its implementation:
30
31 1. Persistence: It leverages the gopls machine-global filecache to persist
32 file tree state across sessions, keyed by the hash of the root directory.
33 2. Adaptive Polling: It uses an adaptive backoff timer that accelerates
34 (to 2s) when user activity is signaled via Poke() and slows down
35 (up to 1m) when the file system is idle.
36 3. Synchronous Baseline: WatchDir performs a synchronous initial scan if
37 no cached state exists. This acts as a barrier, ensuring that any
38 subsequent file system changes are correctly detected as events.
39 4. Coalescing: Unlike fsnotify, polling naturally coalesces rapid sequences
40 of events (e.g., Create + Change) into a single event based on the
41 state difference between scans.
42 5. Multi-root: The watcher supports multiple independent root directories,
43 each with its own independent state and persistence.
44 */
45
46 // NewPollWatcher creates a new watcher that actively polls the file tree to
47 // detect changes. It uses an adaptive back-off strategy to reduce scans of the
48 // file tree and save battery; it is thus only eventually consistent.
49 func NewPollWatcher(log *slog.Logger, onEvents func([]protocol.FileEvent), onError func(error)) *pollWatcher {
50 if log != nil {
51 log = log.With("watcher", "poll")
52 }
53 w := &pollWatcher{
54 log: log,
55 onEvents: onEvents,
56 onError: onError,
57 ctx: context.Background(),
58 stop: make(chan struct{}),
59 poke: make(chan struct{}, 1),
60 roots: make(map[string]*promise[fileState]),
61 }
62 w.loops.Go(w.loop)
63 return w
64 }
65
66 // pollInterval is the baseline polling frequency for the fallback file watcher.
67 //
68 // A 1-second interval prioritizes Developer Experience by ensuring the editor
69 // feels highly responsive to external file system changes (like branch
70 // switches). The watcher relies on its adaptive backoff mechanism to conserve
71 // CPU and disk I/O when the workspace is idle.
72 const pollInterval = time.Second
73
74 type pollWatcher struct {
75 log *slog.Logger
76 onEvents func([]protocol.FileEvent)
77 onError func(error)
78
79 // TODO(hxjiang): accept ctx from constructor and use ctx.Done() for Close.
80 ctx context.Context
81
82 stop chan struct{} // closed by Close to terminate [pollWatcher.loop] go routine
83 loops sync.WaitGroup // counts the number of active [pollWatcher.loop] goroutine (max 1)
84
85 poke chan struct{} // signals user activity
86
87 mu sync.Mutex // guards field below
88 roots map[string]*promise[fileState] // clean root dir -> last known state.
89 }
90
91 type promise[T any] struct {
92 value T
93 err error
94 ready chan struct{}
95 }
96
97 func (p *promise[T]) isReady() bool {
98 select {
99 case <-p.ready:
100 // The channel is closed.
101 // A closed channel yields infinite zero-values without blocking.
102 return true
103 default:
104 // The channel is still open, meaning the work isn't done.
105 return false
106 }
107 }
108
109 // fileState maps file paths (relative to a specific root directory) to
110 // their corresponding metadata.
111 type fileState map[string]fileInfo
112
113 // fileInfo is a frob-serializable record of the information returned
114 // by stat for a single directory entry.
115 type fileInfo struct {
116 ModTime int64 // as defined by Time.UnixNano
117 Size int64
118 IsDir bool
119 }
120
121 func (w *pollWatcher) Mode() settings.FileWatcherMode {
122 return settings.FileWatcherPoll
123 }
124
125 func (w *pollWatcher) WatchDir(dir string) error {
126 if w.log != nil {
127 w.log.Info("Watching", "dir", dir)
128 }
129
130 // TODO(hxjiang): prevent watching for a dir if the parent dir is already
131 // being watched.
132
133 dir = filepath.Clean(dir)
134
135 w.mu.Lock()
136 p, ok := w.roots[dir]
137 if !ok || p.isReady() && p.err != nil {
138 // First goroutine who try to watch "dir" or who observed the previous
139 // attempt failed: this goroutine does the work.
140
141 // Put /replace with a promise as a place holder
142 p = &promise[fileState]{
143 ready: make(chan struct{}),
144 }
145 w.roots[dir] = p
146 w.mu.Unlock()
147
148 p.value, p.err = w.watchDir(dir)
149 close(p.ready)
150
151 // Trigger a scan soon to detect subsequent changes.
152 if p.err == nil {
153 w.Poke()
154 }
155 } else {
156 w.mu.Unlock()
157
158 // Some other goroutine got there first.
159 <-p.ready
160 }
161
162 // Inv: promise is ready
163 return p.err
164 }
165
166 func (w *pollWatcher) watchDir(dir string) (fileState, error) {
167 state, err := w.loadState(dir)
168
169 // Cache miss: perform a synchronous scan to establish a baseline.
170 if err != nil {
171 _, newState, err := scan(dir, nil)
172 if err != nil {
173 return nil, err
174 }
175 state = newState
176 w.saveState(dir, state)
177 }
178
179 return state, nil
180 }
181
182 func (w *pollWatcher) Close() error {
183 close(w.stop)
184 w.loops.Wait()
185 return nil
186 }
187
188 func (w *pollWatcher) Poke() {
189 select {
190 case w.poke <- struct{}{}:
191 default:
192 }
193 }
194
195 // loop scans the tree periodically, using adaptive backoff, until the watcher
196 // is closed.
197 //
198 // A call to [pollWatcher.Poke] interrupts any long sleep and resets the timer
199 // to the fast polling interval.
200 func (w *pollWatcher) loop() {
201 delay := pollInterval
202 timer := time.NewTimer(delay)
203 defer timer.Stop()
204
205 for {
206 select {
207 case <-w.stop:
208 return
209
210 case <-w.poke:
211 delay = pollInterval
212 timer.Reset(delay)
213
214 case <-timer.C:
215 w.mu.Lock()
216 roots := moremaps.KeySlice(w.roots)
217 w.mu.Unlock()
218
219 changed := false
220 // TODO(hxjiang): run "scan" in parallel.
221 for _, root := range roots {
222 w.mu.Lock()
223 p, ok := w.roots[root]
224 w.mu.Unlock()
225 if !ok {
226 continue // Root removed (not possible as we don't support RemoveWatch)
227 }
228 if !p.isReady() {
229 continue // Initial scan is undergoing
230 }
231 if p.err != nil {
232 continue // Initial scan failed
233 }
234
235 changes, newState, err := scan(root, p.value)
236 if err != nil {
237 if w.onError != nil {
238 w.onError(err)
239 }
240 continue
241 }
242
243 w.mu.Lock()
244 if _, ok := w.roots[root]; ok {
245 w.roots[root].value = newState
246 }
247 w.mu.Unlock()
248
249 if len(changes) > 0 {
250 w.onEvents(changes)
251 w.saveState(root, newState)
252 changed = true
253 } else if p.value == nil {
254 // Initial baseline established, save it so next run has a comparison.
255 w.saveState(root, newState)
256 }
257 }
258
259 if changed {
260 // If changes found, keep polling fast for a bit.
261 delay = pollInterval
262 } else {
263 // No changes, backoff.
264 delay = min(delay*2, 2*time.Hour)
265 }
266 timer.Reset(delay)
267 }
268 }
269 }
270
271 // scan walks the file tree for the given root directory and compares its
272 // current state against the provided oldState, returning a coalesced list
273 // of file system events (Created, Changed, Deleted) and the new state map.
274 //
275 // This method is concurrency safe. It does not mutate the watcher's internal
276 // state.
277 //
278 // To prevent triggering massive workspace reloads in the LSP, scan explicitly
279 // ignores modification time changes on the root directory itself.
280 func scan(root string, oldState fileState) ([]protocol.FileEvent, fileState, error) {
281 var (
282 newState = make(fileState)
283 events []protocol.FileEvent
284 )
285 addEvent := func(typ protocol.FileChangeType, path string) {
286 events = append(events, protocol.FileEvent{
287 URI: protocol.URIFromPath(path),
288 Type: typ,
289 })
290 }
291 err := filepath.WalkDir(root, func(path string, dirent fs.DirEntry, err error) error {
292 if err != nil {
293 // Permission errors or disappearing files are ignored during walk.
294 return nil
295 }
296 if path == root {
297 // Skip the root directory itself. We are interested in its contents.
298 // This avoids emitting a "Changed" event for the root whenever a
299 // file is added or removed.
300 return nil
301 }
302 if dirent.IsDir() && skipDir(dirent.Name()) {
303 return filepath.SkipDir
304 }
305 if !dirent.IsDir() && skipFile(dirent.Name()) {
306 return nil
307 }
308
309 info, err := dirent.Info()
310 if err != nil {
311 return nil
312 }
313
314 newInfo := fileInfo{
315 ModTime: info.ModTime().UnixNano(),
316 Size: info.Size(),
317 IsDir: dirent.IsDir(),
318 }
319 newState[path] = newInfo
320
321 if oldState == nil { // Initial population, no events.
322 return nil
323 }
324
325 if oldInfo, ok := oldState[path]; ok {
326 if oldInfo != newInfo {
327 addEvent(protocol.Changed, path)
328 }
329 } else {
330 addEvent(protocol.Created, path)
331 }
332 return nil
333 })
334 if err != nil {
335 return nil, nil, err
336 }
337
338 for path := range oldState {
339 if _, ok := newState[path]; !ok {
340 addEvent(protocol.Deleted, path)
341 }
342 }
343
344 return events, newState, nil
345 }
346
347 // -- filecache --
348
349 func (w *pollWatcher) loadState(root string) (fileState, error) {
350 key := cacheKey(root)
351 state, err := filecache.Get(filewatcherKind, key, codec.Decode)
352 if err != nil && err != filecache.ErrNotFound {
353 bug.Reportf("internal error reading shared cache: %v", err)
354 }
355 return state, err
356 }
357
358 func (w *pollWatcher) saveState(root string, state fileState) {
359 key := cacheKey(root)
360 data := codec.Encode(state)
361 if err := filecache.Set(filewatcherKind, key, data); err != nil {
362 event.Error(w.ctx, fmt.Sprintf("storing file watcher state data for %s", root), err)
363 }
364 }
365
366 const filewatcherKind = "filewatcher"
367
368 var codec = frob.CodecFor[fileState]()
369
370 func cacheKey(root string) [32]byte {
371 return sha256.Sum256([]byte(root))
372 }