Debian Codegraph @

gopls/internal/cache/fs_memoized.go

raw symbols SCIP
1 // Copyright 2023 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 cache
6
7 import (
8 "context"
9 "os"
10 "sync"
11 "time"
12
13 "golang.org/x/tools/gopls/internal/file"
14 "golang.org/x/tools/gopls/internal/label"
15 "golang.org/x/tools/gopls/internal/protocol"
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/robustio"
18 )
19
20 // A memoizedFS is a file source that memoizes reads, to reduce IO.
21 type memoizedFS struct {
22 mu sync.Mutex
23
24 // filesByID maps existing file inodes to the result of a read.
25 // (The read may have failed, e.g. due to EACCES or a delete between stat+read.)
26 // Each slice is a non-empty list of aliases: different URIs.
27 filesByID map[robustio.FileID][]*diskFile
28 }
29
30 func newMemoizedFS() *memoizedFS {
31 return &memoizedFS{filesByID: make(map[robustio.FileID][]*diskFile)}
32 }
33
34 // A diskFile is a file in the filesystem, or a failure to read one.
35 // It implements the file.Source interface.
36 type diskFile struct {
37 uri protocol.DocumentURI
38 modTime time.Time
39 content []byte
40 hash file.Hash
41 err error
42 }
43
44 func (h *diskFile) String() string { return h.uri.Path() }
45
46 func (h *diskFile) URI() protocol.DocumentURI { return h.uri }
47
48 func (h *diskFile) Identity() file.Identity {
49 return file.Identity{
50 URI: h.uri,
51 Hash: h.hash,
52 }
53 }
54
55 func (h *diskFile) SameContentsOnDisk() bool { return true }
56 func (h *diskFile) Version() int32 { return 0 }
57 func (h *diskFile) Content() ([]byte, error) { return h.content, h.err }
58 func (h *diskFile) ModTime() (time.Time, error) { return h.modTime, h.err }
59
60 // ReadFile stats and (maybe) reads the file, updates the cache, and returns it.
61 func (fs *memoizedFS) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) {
62 id, mtime, err := robustio.GetFileID(uri.Path())
63 if err != nil {
64 // file does not exist
65 return &diskFile{
66 err: err,
67 uri: uri,
68 }, nil
69 }
70
71 // We check if the file has changed by comparing modification times. Notably,
72 // this is an imperfect heuristic as various systems have low resolution
73 // mtimes (as much as 1s on WSL or s390x builders), so we only cache
74 // filehandles if mtime is old enough to be reliable, meaning that we don't
75 // expect a subsequent write to have the same mtime.
76 //
77 // The coarsest mtime precision we've seen in practice is 1s, so consider
78 // mtime to be unreliable if it is less than 2s old. Capture this before
79 // doing anything else.
80 recentlyModified := time.Since(mtime) < 2*time.Second
81
82 fs.mu.Lock()
83 fhs, ok := fs.filesByID[id]
84 if ok && fhs[0].modTime.Equal(mtime) {
85 var fh *diskFile
86 // We have already seen this file and it has not changed.
87 for _, h := range fhs {
88 if h.uri == uri {
89 fh = h
90 break
91 }
92 }
93 // No file handle for this exact URI. Create an alias, but share content.
94 if fh == nil {
95 newFH := *fhs[0]
96 newFH.uri = uri
97 fh = &newFH
98 fhs = append(fhs, fh)
99 fs.filesByID[id] = fhs
100 }
101 fs.mu.Unlock()
102 return fh, nil
103 }
104 fs.mu.Unlock()
105
106 // Unknown file, or file has changed. Read (or re-read) it.
107 fh, err := readFile(ctx, uri, mtime) // ~25us
108 if err != nil {
109 return nil, err // e.g. cancelled (not: read failed)
110 }
111
112 fs.mu.Lock()
113 if !recentlyModified {
114 fs.filesByID[id] = []*diskFile{fh}
115 } else {
116 delete(fs.filesByID, id)
117 }
118 fs.mu.Unlock()
119 return fh, nil
120 }
121
122 // fileStats returns information about the set of files stored in fs. It is
123 // intended for debugging only.
124 func (fs *memoizedFS) fileStats() (files, largest, errs int) {
125 fs.mu.Lock()
126 defer fs.mu.Unlock()
127
128 files = len(fs.filesByID)
129 largest = 0
130 errs = 0
131
132 for _, files := range fs.filesByID {
133 rep := files[0]
134 if len(rep.content) > largest {
135 largest = len(rep.content)
136 }
137 if rep.err != nil {
138 errs++
139 }
140 }
141 return files, largest, errs
142 }
143
144 // ioLimit limits the number of parallel file reads per process.
145 var ioLimit = make(chan struct{}, 128)
146
147 func readFile(ctx context.Context, uri protocol.DocumentURI, mtime time.Time) (*diskFile, error) {
148 select {
149 case ioLimit <- struct{}{}:
150 case <-ctx.Done():
151 return nil, ctx.Err()
152 }
153 defer func() { <-ioLimit }()
154
155 ctx, done := event.Start(ctx, "cache.readFile", label.File.Of(uri.Path()))
156 _ = ctx
157 defer done()
158
159 // It is possible that a race causes us to read a file with different file
160 // ID, or whose mtime differs from the given mtime. However, in these cases
161 // we expect the client to notify of a subsequent file change, and the file
162 // content should be eventually consistent.
163 content, err := os.ReadFile(uri.Path()) // ~20us
164 if err != nil {
165 content = nil // just in case
166 }
167 return &diskFile{
168 modTime: mtime,
169 uri: uri,
170 content: content,
171 hash: file.HashOf(content),
172 err: err,
173 }, nil
174 }