Debian Codegraph @

gopls/internal/cache/imports.go

raw symbols SCIP
1 // Copyright 2020 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 "fmt"
10 "log"
11 "sync"
12 "time"
13
14 "golang.org/x/tools/gopls/internal/file"
15 "golang.org/x/tools/gopls/internal/label"
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/event/keys"
18 "golang.org/x/tools/internal/imports"
19 "golang.org/x/tools/internal/modindex"
20 )
21
22 // refreshTimer implements delayed asynchronous refreshing of state.
23 //
24 // See the [refreshTimer.schedule] documentation for more details.
25 type refreshTimer struct {
26 mu sync.Mutex
27 duration time.Duration
28 timer *time.Timer
29 refreshFn func()
30 }
31
32 // newRefreshTimer constructs a new refresh timer which schedules refreshes
33 // using the given function.
34 func newRefreshTimer(refresh func()) *refreshTimer {
35 return &refreshTimer{
36 refreshFn: refresh,
37 }
38 }
39
40 // stop stops any future scheduled refresh.
41 func (t *refreshTimer) stop() {
42 t.mu.Lock()
43 defer t.mu.Unlock()
44
45 if t.timer != nil {
46 t.timer.Stop()
47 t.timer = nil
48 t.refreshFn = nil // release resources
49 }
50 }
51
52 // schedule schedules the refresh function to run at some point in the future,
53 // if no existing refresh is already scheduled.
54 //
55 // At a minimum, scheduled refreshes are delayed by 30s, but they may be
56 // delayed longer to keep their expected execution time under 2% of wall clock
57 // time.
58 func (t *refreshTimer) schedule() {
59 t.mu.Lock()
60 defer t.mu.Unlock()
61
62 if t.timer == nil {
63 // Don't refresh more than twice per minute.
64 // Don't spend more than ~2% of the time refreshing.
65 delay := max(30*time.Second, 50*t.duration)
66 t.timer = time.AfterFunc(delay, func() {
67 start := time.Now()
68 t.mu.Lock()
69 refreshFn := t.refreshFn
70 t.mu.Unlock()
71 if refreshFn != nil { // timer may be stopped.
72 refreshFn()
73 t.mu.Lock()
74 t.duration = time.Since(start)
75 t.timer = nil
76 t.mu.Unlock()
77 }
78 })
79 }
80 }
81
82 // A sharedModCache tracks goimports state for GOMODCACHE directories
83 // (each session may have its own GOMODCACHE).
84 //
85 // This state is refreshed independently of view-specific imports state.
86 type sharedModCache struct {
87 mu sync.Mutex
88 caches map[string]*imports.DirInfoCache // GOMODCACHE -> cache content; never invalidated
89 // TODO(rfindley): consider stopping these timers when the session shuts down.
90 timers map[string]*refreshTimer // GOMODCACHE -> timer
91 }
92
93 func (c *sharedModCache) dirCache(dir string) *imports.DirInfoCache {
94 c.mu.Lock()
95 defer c.mu.Unlock()
96
97 cache, ok := c.caches[dir]
98 if !ok {
99 cache = imports.NewDirInfoCache()
100 c.caches[dir] = cache
101 }
102 return cache
103 }
104
105 // refreshDir schedules a refresh of the given directory, which must be a
106 // module cache.
107 func (c *sharedModCache) refreshDir(ctx context.Context, dir string, logf func(string, ...any)) {
108 cache := c.dirCache(dir)
109
110 c.mu.Lock()
111 defer c.mu.Unlock()
112 timer, ok := c.timers[dir]
113 if !ok {
114 timer = newRefreshTimer(func() {
115 _, done := event.Start(ctx, "cache.sharedModCache.refreshDir", label.Directory.Of(dir))
116 defer done()
117 imports.ScanModuleCache(dir, cache, logf)
118 })
119 c.timers[dir] = timer
120 }
121
122 timer.schedule()
123 }
124
125 // importsState tracks view-specific imports state.
126 type importsState struct {
127 ctx context.Context
128 modCache *sharedModCache
129 refreshTimer *refreshTimer
130
131 mu sync.Mutex
132 processEnv *imports.ProcessEnv
133 cachedModFileHash file.Hash
134 }
135
136 // newImportsState constructs a new imports state for running goimports
137 // functions via [runProcessEnvFunc].
138 //
139 // The returned state will automatically refresh itself following a delay.
140 func newImportsState(backgroundCtx context.Context, modCache *sharedModCache, env *imports.ProcessEnv) *importsState {
141 s := &importsState{
142 ctx: backgroundCtx,
143 modCache: modCache,
144 processEnv: env,
145 }
146 s.refreshTimer = newRefreshTimer(s.refreshProcessEnv)
147 s.refreshTimer.schedule()
148 return s
149 }
150
151 // modcacheState holds a modindex.Index and controls its updates
152 type modcacheState struct {
153 gomodcache string
154 refreshTimer *refreshTimer
155
156 // (index, indexErr) is zero in the initial state.
157 // Thereafter they hold the memoized result pair for getIndex.
158 mu sync.Mutex
159 index *modindex.Index
160 indexErr error
161 }
162
163 // newModcacheState constructs a new modcacheState for goimports.
164 // The returned state is automatically updated until [modcacheState.stopTimer] is called.
165 func newModcacheState(gomodcache string) *modcacheState {
166 s := &modcacheState{
167 gomodcache: gomodcache,
168 }
169 s.refreshTimer = newRefreshTimer(s.refreshIndex)
170 go s.refreshIndex()
171 return s
172 }
173
174 // getIndex reads the module cache index.
175 func (s *modcacheState) getIndex() (*modindex.Index, error) {
176 s.mu.Lock()
177 defer s.mu.Unlock()
178
179 if s.index == nil && s.indexErr == nil {
180 // getIndex was called before refreshIndex finished.
181 // Read, but don't update, whatever index is present.
182 s.index, s.indexErr = modindex.Read(s.gomodcache)
183 }
184
185 return s.index, s.indexErr
186 }
187
188 func (s *modcacheState) refreshIndex() {
189 index, err := modindex.Update(s.gomodcache)
190 s.mu.Lock()
191 if err != nil {
192 if s.indexErr != nil {
193 s.indexErr = err // prefer most recent error
194 } else if s.index != nil {
195 // Keep using stale s.index.
196 log.Printf("modcacheState.refreshIndex: %v", err)
197 }
198 } else {
199 s.index, s.indexErr = index, nil // success
200 }
201 s.mu.Unlock()
202 }
203
204 func (s *modcacheState) stopTimer() {
205 s.refreshTimer.stop()
206 }
207
208 // stopTimer stops scheduled refreshes of this imports state.
209 func (s *importsState) stopTimer() {
210 s.refreshTimer.stop()
211 }
212
213 // runProcessEnvFunc runs goimports.
214 //
215 // Any call to runProcessEnvFunc will schedule a refresh of the imports state
216 // at some point in the future, if such a refresh is not already scheduled. See
217 // [refreshTimer] for more details.
218 func (s *importsState) runProcessEnvFunc(ctx context.Context, snapshot *Snapshot, fn func(context.Context, *imports.Options) error) error {
219 ctx, done := event.Start(ctx, "cache.importsState.runProcessEnvFunc")
220 defer done()
221
222 s.mu.Lock()
223 defer s.mu.Unlock()
224
225 // Find the hash of active mod files, if any. Using the unsaved content
226 // is slightly wasteful, since we'll drop caches a little too often, but
227 // the mod file shouldn't be changing while people are autocompleting.
228 //
229 // TODO(rfindley): consider instead hashing on-disk modfiles here.
230 var modFileHash file.Hash
231 for m := range snapshot.view.workspaceModFiles {
232 fh, err := snapshot.ReadFile(ctx, m)
233 if err != nil {
234 return err
235 }
236 modFileHash.XORWith(fh.Identity().Hash)
237 }
238
239 // If anything relevant to imports has changed, clear caches and
240 // update the processEnv. Clearing caches blocks on any background
241 // scans.
242 if modFileHash != s.cachedModFileHash {
243 s.processEnv.ClearModuleInfo()
244 s.cachedModFileHash = modFileHash
245 }
246
247 // Run the user function.
248 opts := &imports.Options{
249 // Defaults.
250 AllErrors: true,
251 Comments: true,
252 Fragment: true,
253 FormatOnly: false,
254 TabIndent: true,
255 TabWidth: 8,
256 Env: s.processEnv,
257 LocalPrefix: snapshot.Options().Local,
258 }
259
260 if err := fn(ctx, opts); err != nil {
261 return err
262 }
263
264 // Refresh the imports resolver after usage. This may seem counterintuitive,
265 // since it means the first ProcessEnvFunc after a long period of inactivity
266 // may be stale, but in practice we run ProcessEnvFuncs frequently during
267 // active development (e.g. during completion), and so this mechanism will be
268 // active while gopls is in use, and inactive when gopls is idle.
269 s.refreshTimer.schedule()
270
271 // TODO(rfindley): the GOMODCACHE value used here isn't directly tied to the
272 // ProcessEnv.Env["GOMODCACHE"], though they should theoretically always
273 // agree. It would be better if we guaranteed this, possibly by setting all
274 // required environment variables in ProcessEnv.Env, to avoid the redundant
275 // Go command invocation.
276 gomodcache := snapshot.view.folder.Env.GOMODCACHE
277 s.modCache.refreshDir(s.ctx, gomodcache, s.processEnv.Logf)
278
279 return nil
280 }
281
282 func (s *importsState) refreshProcessEnv() {
283 ctx, done := event.Start(s.ctx, "cache.importsState.refreshProcessEnv")
284 defer done()
285
286 start := time.Now()
287
288 s.mu.Lock()
289 resolver, err := s.processEnv.GetResolver()
290 s.mu.Unlock()
291 if err != nil {
292 event.Error(s.ctx, "failed to get import resolver", err)
293 return
294 }
295
296 event.Log(s.ctx, "background imports cache refresh starting")
297 resolver2 := resolver.ClearForNewScan()
298
299 // Prime the new resolver before updating the processEnv, so that gopls
300 // doesn't wait on an unprimed cache.
301 if err := imports.PrimeCache(context.Background(), resolver2); err == nil {
302 event.Log(ctx, fmt.Sprintf("background refresh finished after %v", time.Since(start)))
303 } else {
304 event.Log(ctx, fmt.Sprintf("background refresh finished after %v", time.Since(start)), keys.Err.Of(err))
305 }
306
307 s.mu.Lock()
308 s.processEnv.UpdateResolver(resolver2)
309 s.mu.Unlock()
310 }