| 1 | // Copyright 2024 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 | "sync" |
| 10 | ) |
| 11 | |
| 12 | // A futureCache is a key-value store of "futures", which are values that might |
| 13 | // not yet be processed. By accessing values using [futureCache.get], the |
| 14 | // caller may share work with other goroutines that require the same key. |
| 15 | // |
| 16 | // This is a relatively common pattern, though this implementation includes the |
| 17 | // following two non-standard additions: |
| 18 | // |
| 19 | // 1. futures are cancellable and retryable. If the context being used to |
| 20 | // compute the future is cancelled, it will abort the computation. If other |
| 21 | // goroutes are awaiting the future, they will acquire the right to compute |
| 22 | // it, and start anew. |
| 23 | // 2. futures may be either persistent or transient. Persistent futures are |
| 24 | // the standard pattern: the results of the computation are preserved for |
| 25 | // the lifetime of the cache. However, if the cache is transient |
| 26 | // (persistent=false), the futures will be discarded once their value has |
| 27 | // been passed to all awaiting goroutines. |
| 28 | // |
| 29 | // These specific extensions are used to implement the concurrency model of the |
| 30 | // [typeCheckBatch], which allows multiple operations to piggy-back on top of |
| 31 | // an ongoing type checking operation, requesting new packages asynchronously |
| 32 | // without unduly increasing the in-use memory required by the type checking |
| 33 | // pass. |
| 34 | type futureCache[K comparable, V any] struct { |
| 35 | persistent bool |
| 36 | |
| 37 | mu sync.Mutex |
| 38 | cache map[K]*future[V] |
| 39 | } |
| 40 | |
| 41 | // newFutureCache returns a futureCache that is ready to coordinate |
| 42 | // computations via [futureCache.get]. |
| 43 | // |
| 44 | // If persistent is true, the results of these computations are stored for the |
| 45 | // lifecycle of cache. Otherwise, results are discarded after they have been |
| 46 | // passed to all awaiting goroutines. |
| 47 | func newFutureCache[K comparable, V any](persistent bool) *futureCache[K, V] { |
| 48 | return &futureCache[K, V]{ |
| 49 | persistent: persistent, |
| 50 | cache: make(map[K]*future[V]), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | type future[V any] struct { |
| 55 | // refs is the number of goroutines awaiting this future, to be used for |
| 56 | // cleaning up transient cache entries. |
| 57 | // |
| 58 | // Guarded by futureCache.mu. |
| 59 | refs int |
| 60 | |
| 61 | // done is closed when the future has been fully computed. |
| 62 | done chan unit |
| 63 | |
| 64 | // acquire used to select an awaiting goroutine to run the computation. |
| 65 | // acquire is 1-buffered, and initialized with one unit, so that the first |
| 66 | // requester starts a computation. If that computation is cancelled, the |
| 67 | // requester pushes the unit back to acquire, so that another goroutine may |
| 68 | // execute the computation. |
| 69 | acquire chan unit |
| 70 | |
| 71 | // v and err store the result of the computation, guarded by done. |
| 72 | v V |
| 73 | err error |
| 74 | } |
| 75 | |
| 76 | // cacheFunc is the type of a future computation function. |
| 77 | type cacheFunc[V any] func(context.Context) (V, error) |
| 78 | |
| 79 | // get retrieves or computes the value corresponding to k. |
| 80 | // |
| 81 | // If the cache if persistent and the value has already been computed, get |
| 82 | // returns the result of the previous computation. Otherwise, get either starts |
| 83 | // a computation or joins an ongoing computation. If that computation is |
| 84 | // cancelled, get will reassign the computation to a new goroutine as long as |
| 85 | // there are awaiters. |
| 86 | // |
| 87 | // Once the computation completes, the result is passed to all awaiting |
| 88 | // goroutines. If the cache is transient (persistent=false), the corresponding |
| 89 | // cache entry is removed, and the next call to get will execute a new |
| 90 | // computation. |
| 91 | // |
| 92 | // It is therefore the responsibility of the caller to ensure that the given |
| 93 | // compute function is safely retryable, and always returns the same value. |
| 94 | func (c *futureCache[K, V]) get(ctx context.Context, k K, compute cacheFunc[V]) (V, error) { |
| 95 | c.mu.Lock() |
| 96 | f, ok := c.cache[k] |
| 97 | if !ok { |
| 98 | f = &future[V]{ |
| 99 | done: make(chan unit), |
| 100 | acquire: make(chan unit, 1), |
| 101 | } |
| 102 | f.acquire <- unit{} // make available for computation |
| 103 | c.cache[k] = f |
| 104 | } |
| 105 | f.refs++ |
| 106 | c.mu.Unlock() |
| 107 | |
| 108 | defer func() { |
| 109 | c.mu.Lock() |
| 110 | defer c.mu.Unlock() |
| 111 | f.refs-- |
| 112 | if f.refs == 0 && !c.persistent { |
| 113 | delete(c.cache, k) |
| 114 | } |
| 115 | }() |
| 116 | |
| 117 | var zero V |
| 118 | select { |
| 119 | case <-ctx.Done(): |
| 120 | return zero, ctx.Err() |
| 121 | case <-f.done: |
| 122 | return f.v, f.err |
| 123 | case <-f.acquire: |
| 124 | } |
| 125 | |
| 126 | v, err := compute(ctx) |
| 127 | if err := ctx.Err(); err != nil { |
| 128 | f.acquire <- unit{} // hand off work to the next requester |
| 129 | return zero, err |
| 130 | } |
| 131 | |
| 132 | f.v = v |
| 133 | f.err = err |
| 134 | close(f.done) |
| 135 | return v, err |
| 136 | } |