Debian Codegraph @

gopls/internal/filewatcher/filewatcher_test.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_test
6
7 import (
8 "cmp"
9 "fmt"
10 "maps"
11 "os"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "testing"
16 "time"
17
18 "golang.org/x/sync/errgroup"
19 "golang.org/x/tools/gopls/internal/filewatcher"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/settings"
22 "golang.org/x/tools/gopls/internal/util/moremaps"
23 "golang.org/x/tools/internal/robustio"
24 "golang.org/x/tools/internal/testfiles"
25 "golang.org/x/tools/txtar"
26 )
27
28 // tryFSOperation executes a function `op` with retry logic, making it resilient
29 // to transient errors. It attempts the operation up to 5 times with exponential
30 // backoff. Retries occur only if the error is ephemeral.
31 func tryFSOperation(op func() error) error {
32 var (
33 delay = 50 * time.Millisecond
34 err error
35 )
36
37 for range 5 {
38 if err = op(); !robustio.IsEphemeralError(err) {
39 return err
40 }
41
42 time.Sleep(delay)
43 delay *= 2
44 }
45
46 return err // return last error encountered
47 }
48
49 func TestFileWatcher(t *testing.T) {
50 testCases := []struct {
51 name string
52 initWorkspace string
53 changes func(root string) error
54 expectedEvents map[protocol.FileEvent]struct{}
55 }{
56 {
57 name: "create file",
58 initWorkspace: `
59 -- foo.go --
60 package foo
61 `,
62 changes: func(root string) error {
63 return os.WriteFile(filepath.Join(root, "bar.go"), []byte("package main"), 0644)
64 },
65 expectedEvents: map[protocol.FileEvent]struct{}{
66 {URI: "bar.go", Type: protocol.Created}: {},
67 },
68 },
69 {
70 name: "modify file",
71 initWorkspace: `
72 -- foo.go --
73 package foo
74 `,
75 changes: func(root string) error {
76 return os.WriteFile(filepath.Join(root, "foo.go"), []byte("package main // modified"), 0644)
77 },
78 expectedEvents: map[protocol.FileEvent]struct{}{
79 {URI: "foo.go", Type: protocol.Changed}: {},
80 },
81 },
82 {
83 name: "delete file",
84 initWorkspace: `
85 -- foo.go --
86 package foo
87 -- bar.go --
88 package bar
89 `,
90 changes: func(root string) error {
91 return os.Remove(filepath.Join(root, "foo.go"))
92 },
93 expectedEvents: map[protocol.FileEvent]struct{}{
94 {URI: "foo.go", Type: protocol.Deleted}: {},
95 },
96 },
97 {
98 name: "rename file",
99 initWorkspace: `
100 -- foo.go --
101 package foo
102 `,
103 changes: func(root string) error {
104 return os.Rename(filepath.Join(root, "foo.go"), filepath.Join(root, "bar.go"))
105 },
106 expectedEvents: map[protocol.FileEvent]struct{}{
107 {URI: "foo.go", Type: protocol.Deleted}: {},
108 {URI: "bar.go", Type: protocol.Created}: {},
109 },
110 },
111 {
112 name: "create directory",
113 initWorkspace: `
114 -- foo.go --
115 package foo
116 `,
117 changes: func(root string) error {
118 return os.Mkdir(filepath.Join(root, "bar"), 0755)
119 },
120 expectedEvents: map[protocol.FileEvent]struct{}{
121 {URI: "bar", Type: protocol.Created}: {},
122 },
123 },
124 {
125 name: "delete directory",
126 initWorkspace: `
127 -- foo/bar.go --
128 package foo
129 `,
130 changes: func(root string) error {
131 return os.RemoveAll(filepath.Join(root, "foo"))
132 },
133 expectedEvents: map[protocol.FileEvent]struct{}{
134 // We only assert that the directory deletion event exists,
135 // because file system event behavior is inconsistent across
136 // platforms when deleting a non-empty directory.
137 // e.g. windows-amd64 may only emit a single dir removal event,
138 // freebsd-amd64 report dir removal before file removal,
139 // linux-amd64 report the reverse order.
140 // Therefore, the most reliable and cross-platform compatible
141 // signal is the deletion event for the directory itself.
142 {URI: "foo", Type: protocol.Deleted}: {},
143 },
144 },
145 {
146 name: "rename directory",
147 initWorkspace: `
148 -- foo/bar.go --
149 package foo
150 `,
151 changes: func(root string) error {
152 return os.Rename(filepath.Join(root, "foo"), filepath.Join(root, "baz"))
153 },
154 expectedEvents: map[protocol.FileEvent]struct{}{
155 {URI: "foo", Type: protocol.Deleted}: {},
156 {URI: "baz", Type: protocol.Created}: {},
157 {URI: "baz/bar.go", Type: protocol.Created}: {},
158 },
159 },
160 // TODO(hxjiang): test for symlink to a dir.
161 }
162
163 for _, tt := range testCases {
164 t.Run(tt.name, func(t *testing.T) {
165 for _, mode := range []settings.FileWatcherMode{settings.FileWatcherFSNotify, settings.FileWatcherPoll} {
166 t.Run(string(mode), func(t *testing.T) {
167 // "poll" mode is portable, so we can run it on all OS.
168 if mode == settings.FileWatcherFSNotify {
169 switch runtime.GOOS {
170 case "darwin", "linux", "windows":
171 default:
172 t.Skip("unsupported OS")
173 }
174 }
175
176 fs, err := txtar.FS(txtar.Parse([]byte(tt.initWorkspace)))
177 if err != nil {
178 t.Fatal(err)
179 }
180 root := testfiles.CopyToTmp(t, fs)
181
182 var (
183 all = maps.Clone(tt.expectedEvents)
184 foundAll = make(chan struct{})
185
186 gots []protocol.FileEvent
187 )
188
189 eventsHandler := func(events []protocol.FileEvent) {
190 // Trim prefix for readability.
191 for i := range events {
192 rel := strings.TrimPrefix(events[i].URI.Path(), root+string(filepath.Separator))
193 events[i].URI = protocol.DocumentURI(filepath.ToSlash(rel))
194 }
195
196 gots = append(gots, events...)
197
198 if len(all) == 0 {
199 return
200 }
201
202 for _, got := range events {
203 delete(all, got)
204 if len(all) == 0 {
205 close(foundAll)
206 return
207 }
208 }
209
210 }
211 errHandler := func(err error) {
212 t.Errorf("error from watcher: %v", err)
213 }
214
215 w, err := filewatcher.New(mode, nil, eventsHandler, errHandler)
216 if err != nil {
217 t.Fatal(err)
218 }
219 defer func() {
220 if err := w.Close(); err != nil {
221 t.Errorf("failed to close the file watcher: %v", err)
222 }
223 }()
224
225 if err := w.WatchDir(root); err != nil {
226 t.Fatal(err)
227 }
228
229 // For poll watcher, we need to ensure mtime changes. The test
230 // cases use os.WriteFile which updates mtime. However, if the
231 // test runs too fast, mtime might not change (if resolution
232 // is low). Poll watcher checks mtime.
233 if mode == settings.FileWatcherPoll {
234 time.Sleep(10 * time.Millisecond)
235 }
236 // The poll watcher periodically scans the directory in the
237 // background.
238 // On Windows, the file system enforces mandatory file locking.
239 // If the test attempts to modify files while the watcher is
240 // reading them, Windows will reject the modification with a
241 // sharing or permission error. We use tryFSOperation to
242 // retry the modification until the watcher releases the
243 // file lock.
244 //
245 // However this also means other process (maybe the user)
246 // will encounter this problem while the poll watcher is
247 // scanning through the dir.
248 if err := tryFSOperation(func() error {
249 return tt.changes(root)
250 }); err != nil {
251 t.Fatal(err)
252 }
253
254 select {
255 case <-foundAll:
256 case <-time.After(30 * time.Second):
257 if len(all) != 0 {
258 var want strings.Builder
259 for e := range tt.expectedEvents {
260 fmt.Fprintf(&want, "URI: %s type: %v\n", e.URI, e.Type)
261 }
262 var got strings.Builder
263 for _, e := range gots {
264 fmt.Fprintf(&got, "URI: %s type: %v\n", e.URI, e.Type)
265 }
266 t.Errorf("found %v matching events slice\nwant sequences:\n%s\nall got:\n%s", len(tt.expectedEvents)-len(all), want.String(), got.String())
267 }
268
269 }
270 })
271 }
272 })
273 }
274 }
275
276 func TestBrokenSymlink(t *testing.T) {
277 if runtime.GOOS != "darwin" {
278 t.Skip("unsupported OS")
279 }
280
281 root := t.TempDir()
282
283 // watchErrs is used to capture watch errors during directory monitoring.
284 // This mechanism allows the test to assert that specific directory watches
285 // initially fail and subsequently recover upon fixing the broken symlink.
286 watchErrs := make(chan error, 10)
287 filewatcher.SetAfterAddHook(func(path string, watchErr error) {
288 rel, err := filepath.Rel(root, path)
289 if err != nil {
290 return
291 }
292 if rel == "foo" {
293 if watchErr == nil {
294 close(watchErrs)
295 } else {
296 watchErrs <- watchErr
297 }
298 }
299 })
300 defer filewatcher.SetAfterAddHook(nil)
301
302 var (
303 gots []protocol.FileEvent
304 matched int
305 foundAll = make(chan struct{})
306 )
307 wants := []protocol.FileEvent{
308 // "foo" create event from fsnotify and synthesized create event
309 // for all entries under foo.
310 {URI: "foo", Type: protocol.Created},
311 {URI: "foo/a.go", Type: protocol.Created},
312 {URI: "foo/b.go", Type: protocol.Created},
313 {URI: "foo/from.go", Type: protocol.Created},
314 // "to.go" creation from fsnotify.
315 {URI: "to.go", Type: protocol.Created},
316 // file creation event after watch retry succeeded.
317 {URI: "foo/new.go", Type: protocol.Created},
318 }
319 eventsHandler := func(events []protocol.FileEvent) {
320 gots = append(gots, events...)
321
322 if matched == len(wants) {
323 return
324 }
325
326 for _, got := range events {
327 want := protocol.FileEvent{
328 URI: protocol.URIFromPath(filepath.Join(root, string(wants[matched].URI))),
329 Type: wants[matched].Type,
330 }
331 if want == got {
332 matched++
333 }
334 if matched == len(wants) {
335 close(foundAll)
336 return
337 }
338 }
339
340 }
341 errHandler := func(err error) {
342 t.Errorf("error from watcher: %v", err)
343 }
344 w, err := filewatcher.New(settings.FileWatcherFSNotify, nil, eventsHandler, errHandler)
345 if err != nil {
346 t.Fatal(err)
347 }
348 defer func() {
349 if err := w.Close(); err != nil {
350 t.Errorf("failed to close the file watcher: %v", err)
351 }
352 }()
353
354 if err := w.WatchDir(root); err != nil {
355 t.Fatal(err)
356 }
357
358 {
359 // Prepare a dir with broken symbolic link.
360 // foo <- 1st
361 // ├── from.go -> root/to.go <- 1st
362 // ├── a.go <- 1st
363 // └── b.go <- 1st
364
365 to := filepath.Join(root, "to.go")
366
367 archive := txtar.Parse([]byte(`
368 -- a.go --
369 package a
370 -- b.go --
371 package b
372 `))
373 tmp := filepath.Join(t.TempDir(), "foo")
374 for _, f := range archive.Files {
375 path := filepath.Join(tmp, f.Name)
376 if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
377 t.Fatalf("fail to create dir %v", err)
378 }
379 if err := os.WriteFile(path, f.Data, 0644); err != nil {
380 t.Fatalf("fail to write file %v", err)
381 }
382 }
383
384 // Create the symbolic link to a non-existing file. This would
385 // cause the watch registration for dir "foo" to fail.
386 if err := os.Symlink(to, filepath.Join(tmp, "from.go")); err != nil {
387 t.Fatalf("fail to create symlink file %v", err)
388 }
389
390 // Move the directory containing the broken symlink into place
391 // to avoids a flaky test where the directory could be watched
392 // before the symlink is created. See golang/go#74782.
393 if err := os.Rename(tmp, filepath.Join(root, "foo")); err != nil {
394 t.Fatalf("fail to rename file %v", err)
395 }
396
397 // root
398 // ├── foo <- 2nd (Move)
399 // │ ├── a.go <- 2nd (Move)
400 // │ ├── b.go <- 2nd (Move)
401 // │ ├── from.go -> ../../to.go <- 2nd (Move)
402 // │ └── new.go <- 4th (Create)
403 // └── to.go <- 3rd (Create)
404
405 // Should be able to capture watch error while trying to watch dir "foo".
406 if err := <-watchErrs; err == nil {
407 t.Errorf("did not capture watch registration failure for dir foo")
408 }
409
410 // The file watcher should retry watch registration and eventually succeed
411 // watching for all dir under 'foo' after the file got created.
412 {
413 if err := os.WriteFile(to, []byte("package main"), 0644); err != nil {
414 t.Errorf("fail to write file %v", err)
415 }
416
417 timer := time.NewTimer(30 * time.Second)
418 defer timer.Stop()
419
420 outer:
421 for {
422 select {
423 case _, ok := <-watchErrs:
424 if !ok {
425 break outer
426 }
427 case <-timer.C:
428 t.Errorf("timed out after 30s waiting for watches on foo to be established")
429 }
430 }
431 }
432
433 // Once the watch registration is done, file events under the
434 // dir "foo" should be captured
435 if err := os.WriteFile(filepath.Join(root, "foo", "new.go"), []byte("package main"), 0644); err != nil {
436 t.Fatalf("fail to write file %v", err)
437 }
438 }
439
440 select {
441 case <-foundAll:
442 case <-time.After(30 * time.Second):
443 if matched != len(wants) {
444 var want strings.Builder
445 for _, e := range wants {
446 fmt.Fprintf(&want, "URI: %s type: %v\n", e.URI, e.Type)
447 }
448 var got strings.Builder
449 for _, e := range gots {
450 fmt.Fprintf(&got, "URI: %s type: %v\n", strings.TrimPrefix(e.URI.Path(), root+"/"), e.Type)
451 }
452 t.Errorf("found %v matching events slice\nwant sequences:\n%s\nall got:\n%s", matched, &want, &got)
453 }
454
455 }
456 }
457
458 func TestStress(t *testing.T) {
459 for _, mode := range []settings.FileWatcherMode{settings.FileWatcherPoll, settings.FileWatcherFSNotify} {
460 t.Run(string(mode), func(t *testing.T) {
461 // "poll" mode is portable, so we can run it on all OS.
462 if mode == settings.FileWatcherFSNotify {
463 switch runtime.GOOS {
464 case "darwin", "linux", "windows":
465 default:
466 t.Skip("unsupported OS")
467 }
468 }
469
470 const parallelism = 100 // number of parallel instances of each kind of operation
471
472 root := t.TempDir()
473
474 mkdir := func(base string) func() error {
475 return func() error {
476 return os.Mkdir(filepath.Join(root, base), 0755)
477 }
478 }
479 write := func(base string) func() error {
480 return func() error {
481 return os.WriteFile(filepath.Join(root, base), []byte("package main"), 0644)
482 }
483 }
484 remove := func(base string) func() error {
485 return func() error {
486 return os.Remove(filepath.Join(root, base))
487 }
488 }
489 rename := func(old, new string) func() error {
490 return func() error {
491 return os.Rename(filepath.Join(root, old), filepath.Join(root, new))
492 }
493 }
494
495 wants := make(map[protocol.FileEvent]bool)
496 want := func(base string, t protocol.FileChangeType) {
497 wants[protocol.FileEvent{URI: protocol.URIFromPath(filepath.Join(root, base)), Type: t}] = true
498 }
499
500 for i := range parallelism {
501 // Create files and dirs that will be deleted or renamed later.
502 if err := cmp.Or(
503 mkdir(fmt.Sprintf("delete-dir-%d", i))(),
504 mkdir(fmt.Sprintf("old-dir-%d", i))(),
505 write(fmt.Sprintf("delete-file-%d.go", i))(),
506 write(fmt.Sprintf("old-file-%d.go", i))(),
507 ); err != nil {
508 t.Fatal(err)
509 }
510
511 // Add expected notification events to the "wants" set.
512 want(fmt.Sprintf("file-%d.go", i), protocol.Created)
513 want(fmt.Sprintf("delete-file-%d.go", i), protocol.Deleted)
514 want(fmt.Sprintf("old-file-%d.go", i), protocol.Deleted)
515 want(fmt.Sprintf("new-file-%d.go", i), protocol.Created)
516 want(fmt.Sprintf("dir-%d", i), protocol.Created)
517 want(fmt.Sprintf("delete-dir-%d", i), protocol.Deleted)
518 want(fmt.Sprintf("old-dir-%d", i), protocol.Deleted)
519 want(fmt.Sprintf("new-dir-%d", i), protocol.Created)
520 }
521
522 foundAll := make(chan struct{})
523
524 eventsHandler := func(events []protocol.FileEvent) {
525 if len(wants) == 0 { // avoid closing twice
526 return
527 }
528 for _, e := range events {
529 delete(wants, e)
530 }
531 if len(wants) == 0 {
532 close(foundAll)
533 }
534 }
535 errHandler := func(err error) {
536 // Work around test flake go.dev/issue/78366 due to Windows'
537 // regrettable locking of files during reads.
538 if runtime.GOOS == "windows" && strings.Contains(err.Error(), "being used by another process") {
539 t.Log(err)
540 return
541 }
542
543 t.Errorf("error from watcher: %v", err)
544 }
545 w, err := filewatcher.New(mode, nil, eventsHandler, errHandler)
546 if err != nil {
547 t.Fatal(err)
548 }
549 defer func() {
550 if err := w.Close(); err != nil {
551 t.Errorf("failed to close the file watcher: %v", err)
552 }
553 }()
554
555 if err := w.WatchDir(root); err != nil {
556 t.Fatal(err)
557 }
558
559 // Spin up multiple goroutines, to perform 6 file system operations i.e.
560 // create, delete, rename of file or directory. For deletion and rename,
561 // the goroutine deletes / renames files or directories created before the
562 // watcher starts.
563 var g errgroup.Group
564 for id := range parallelism {
565 ops := []func() error{
566 write(fmt.Sprintf("file-%d.go", id)),
567 remove(fmt.Sprintf("delete-file-%d.go", id)),
568 rename(fmt.Sprintf("old-file-%d.go", id), fmt.Sprintf("new-file-%d.go", id)),
569 mkdir(fmt.Sprintf("dir-%d", id)),
570 remove(fmt.Sprintf("delete-dir-%d", id)),
571 rename(fmt.Sprintf("old-dir-%d", id), fmt.Sprintf("new-dir-%d", id)),
572 }
573 for _, f := range ops {
574 g.Go(func() error {
575 return tryFSOperation(f)
576 })
577 }
578 }
579 if err := g.Wait(); err != nil {
580 t.Fatal(err)
581 }
582
583 select {
584 case <-foundAll:
585 case <-time.After(30 * time.Second):
586 if len(wants) > 0 {
587 t.Errorf("missing expected events: %#v", moremaps.KeySlice(wants))
588 }
589 }
590 })
591 }
592 }