Debian Codegraph @

gopls/internal/util/memoize/memoize.go

raw symbols SCIP
1 // Copyright 2019 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 memoize defines a "promise" abstraction that enables
6 // memoization of the result of calling an expensive but idempotent
7 // function.
8 //
9 // Call p = NewPromise(f) to obtain a promise for the future result of
10 // calling f(), and call p.Get() to obtain that result. All calls to
11 // p.Get return the result of a single call of f().
12 // Get blocks if the function has not finished (or started).
13 //
14 // A Store is a map of arbitrary keys to promises. Use Store.Promise
15 // to create a promise in the store. All calls to Handle(k) return the
16 // same promise as long as it is in the store. These promises are
17 // reference-counted and must be explicitly released. Once the last
18 // reference is released, the promise is removed from the store.
19 package memoize
20
21 import (
22 "context"
23 "fmt"
24 "reflect"
25 "runtime/trace"
26 "sync"
27 "sync/atomic"
28 )
29
30 // Function is the type of a function that can be memoized.
31 //
32 // If the arg is a RefCounted, its Acquire/Release operations are called.
33 //
34 // The argument must not materially affect the result of the function
35 // in ways that are not captured by the promise's key, since if
36 // Promise.Get is called twice concurrently, with the same (implicit)
37 // key but different arguments, the Function is called only once but
38 // its result must be suitable for both callers.
39 //
40 // The main purpose of the argument is to avoid the Function closure
41 // needing to retain large objects (in practice: the snapshot) in
42 // memory that can be supplied at call time by any caller.
43 type Function func(ctx context.Context, arg any) any
44
45 // A RefCounted is a value whose functional lifetime is determined by
46 // reference counting.
47 //
48 // Its Acquire method is called before the Function is invoked, and
49 // the corresponding release is called when the Function returns.
50 // Usually both events happen within a single call to Get, so Get
51 // would be fine with a "borrowed" reference, but if the context is
52 // cancelled, Get may return before the Function is complete, causing
53 // the argument to escape, and potential premature destruction of the
54 // value. For a reference-counted type, this requires a pair of
55 // increment/decrement operations to extend its life.
56 type RefCounted interface {
57 // Acquire prevents the value from being destroyed until the
58 // returned function is called.
59 Acquire() func()
60 }
61
62 // A Promise represents the future result of a call to a function.
63 type Promise struct {
64 debug string // for observability
65
66 // refcount is the reference count in the containing Store, used by
67 // Store.Promise. It is guarded by Store.promisesMu on the containing Store.
68 refcount int32
69
70 mu sync.Mutex
71
72 // A Promise starts out IDLE, waiting for something to demand
73 // its evaluation. It then transitions into RUNNING state.
74 //
75 // While RUNNING, waiters tracks the number of Get calls
76 // waiting for a result, and the done channel is used to
77 // notify waiters of the next state transition. Once
78 // evaluation finishes, value is set, state changes to
79 // COMPLETED, and done is closed, unblocking waiters.
80 //
81 // Alternatively, as Get calls are cancelled, they decrement
82 // waiters. If it drops to zero, the inner context is
83 // cancelled, computation is abandoned, and state resets to
84 // IDLE to start the process over again.
85 state state
86 // done is set in running state, and closed when exiting it.
87 done chan struct{}
88 // cancel is set in running state. It cancels computation.
89 cancel context.CancelFunc
90 // waiters is the number of Gets outstanding.
91 waiters uint
92 // the function that will be used to populate the value
93 function Function
94 // value is set in completed state.
95 value any
96 }
97
98 // NewPromise returns a promise for the future result of calling the
99 // specified function.
100 //
101 // The debug string is used to classify promises in logs and metrics.
102 // It should be drawn from a small set.
103 func NewPromise(debug string, function Function) *Promise {
104 if function == nil {
105 panic("nil function")
106 }
107 return &Promise{
108 debug: debug,
109 function: function,
110 }
111 }
112
113 type state int
114
115 const (
116 stateIdle = iota // newly constructed, or last waiter was cancelled
117 stateRunning // start was called and not cancelled
118 stateCompleted // function call ran to completion
119 )
120
121 // Cached returns the value associated with a promise.
122 //
123 // It will never cause the value to be generated.
124 // It will return the cached value, if present.
125 func (p *Promise) Cached() any {
126 p.mu.Lock()
127 defer p.mu.Unlock()
128 if p.state == stateCompleted {
129 return p.value
130 }
131 return nil
132 }
133
134 // Get returns the value associated with a promise.
135 //
136 // All calls to Promise.Get on a given promise return the
137 // same result but the function is called (to completion) at most once.
138 //
139 // If the value is not yet ready, the underlying function will be invoked.
140 //
141 // If ctx is cancelled, Get returns (nil, Canceled).
142 // If all concurrent calls to Get are cancelled, the context provided
143 // to the function is cancelled. A later call to Get may attempt to
144 // call the function again.
145 func (p *Promise) Get(ctx context.Context, arg any) (any, error) {
146 if ctx.Err() != nil {
147 return nil, ctx.Err()
148 }
149 p.mu.Lock()
150 switch p.state {
151 case stateIdle:
152 return p.run(ctx, arg)
153 case stateRunning:
154 return p.wait(ctx)
155 case stateCompleted:
156 defer p.mu.Unlock()
157 return p.value, nil
158 default:
159 panic("unknown state")
160 }
161 }
162
163 // run starts p.function and returns the result. p.mu must be locked.
164 func (p *Promise) run(ctx context.Context, arg any) (any, error) {
165 childCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
166 p.cancel = cancel
167 p.state = stateRunning
168 p.done = make(chan struct{})
169 function := p.function // Read under the lock
170
171 // Make sure that the argument isn't destroyed while we're running in it.
172 release := func() {}
173 if rc, ok := arg.(RefCounted); ok {
174 release = rc.Acquire()
175 }
176
177 go func() {
178 trace.WithRegion(childCtx, fmt.Sprintf("Promise.run %s", p.debug), func() {
179 defer release()
180 // Just in case the function does something expensive without checking
181 // the context, double-check we're still alive.
182 if childCtx.Err() != nil {
183 return
184 }
185 v := function(childCtx, arg)
186 if childCtx.Err() != nil {
187 return
188 }
189
190 p.mu.Lock()
191 defer p.mu.Unlock()
192 // It's theoretically possible that the promise has been cancelled out
193 // of the run that started us, and then started running again since we
194 // checked childCtx above. Even so, that should be harmless, since each
195 // run should produce the same results.
196 if p.state != stateRunning {
197 return
198 }
199
200 p.value = v
201 p.function = nil // aid GC
202 p.state = stateCompleted
203 close(p.done)
204 })
205 }()
206
207 return p.wait(ctx)
208 }
209
210 // wait waits for the value to be computed, or ctx to be cancelled. p.mu must be locked.
211 func (p *Promise) wait(ctx context.Context) (any, error) {
212 p.waiters++
213 done := p.done
214 p.mu.Unlock()
215
216 select {
217 case <-done:
218 p.mu.Lock()
219 defer p.mu.Unlock()
220 if p.state == stateCompleted {
221 return p.value, nil
222 }
223 return nil, nil
224 case <-ctx.Done():
225 p.mu.Lock()
226 defer p.mu.Unlock()
227 p.waiters--
228 if p.waiters == 0 && p.state == stateRunning {
229 p.cancel()
230 close(p.done)
231 p.state = stateIdle
232 p.done = nil
233 p.cancel = nil
234 }
235 return nil, ctx.Err()
236 }
237 }
238
239 // An EvictionPolicy controls the eviction behavior of keys in a Store when
240 // they no longer have any references.
241 type EvictionPolicy int
242
243 const (
244 // ImmediatelyEvict evicts keys as soon as they no longer have references.
245 ImmediatelyEvict EvictionPolicy = iota
246
247 // NeverEvict does not evict keys.
248 NeverEvict
249 )
250
251 // A Store maps arbitrary keys to reference-counted promises.
252 //
253 // The zero value is a valid Store, though a store may also be created via
254 // NewStore if a custom EvictionPolicy is required.
255 type Store struct {
256 evictionPolicy EvictionPolicy
257
258 promisesMu sync.Mutex
259 promises map[any]*Promise
260 }
261
262 // NewStore creates a new store with the given eviction policy.
263 func NewStore(policy EvictionPolicy) *Store {
264 return &Store{evictionPolicy: policy}
265 }
266
267 // Promise returns a reference-counted promise for the future result of
268 // calling the specified function.
269 //
270 // Calls to Promise with the same key return the same promise, incrementing its
271 // reference count. The caller must call the returned function to decrement
272 // the promise's reference count when it is no longer needed. The returned
273 // function must not be called more than once.
274 //
275 // Once the last reference has been released, the promise is removed from the
276 // store.
277 func (store *Store) Promise(key any, function Function) (*Promise, func()) {
278 store.promisesMu.Lock()
279 p, ok := store.promises[key]
280 if !ok {
281 p = NewPromise(reflect.TypeOf(key).String(), function)
282 if store.promises == nil {
283 store.promises = map[any]*Promise{}
284 }
285 store.promises[key] = p
286 }
287 p.refcount++
288 store.promisesMu.Unlock()
289
290 var released int32
291 release := func() {
292 if !atomic.CompareAndSwapInt32(&released, 0, 1) {
293 panic("release called more than once")
294 }
295 store.promisesMu.Lock()
296
297 p.refcount--
298 if p.refcount == 0 && store.evictionPolicy != NeverEvict {
299 // Inv: if p.refcount > 0, then store.promises[key] == p.
300 delete(store.promises, key)
301 }
302 store.promisesMu.Unlock()
303 }
304
305 return p, release
306 }
307
308 // Stats returns the number of each type of key in the store.
309 func (s *Store) Stats() map[reflect.Type]int {
310 result := map[reflect.Type]int{}
311
312 s.promisesMu.Lock()
313 defer s.promisesMu.Unlock()
314
315 for k := range s.promises {
316 result[reflect.TypeOf(k)]++
317 }
318 return result
319 }
320
321 // DebugOnlyIterate iterates through the store and, for each completed
322 // promise, calls f(k, v) for the map key k and function result v. It
323 // should only be used for debugging purposes.
324 func (s *Store) DebugOnlyIterate(f func(k, v any)) {
325 s.promisesMu.Lock()
326 defer s.promisesMu.Unlock()
327
328 for k, p := range s.promises {
329 if v := p.Cached(); v != nil {
330 f(k, v)
331 }
332 }
333 }