Debian Codegraph @

fetch.go

raw
1 package sturdyc
2
3 import (
4 "context"
5 "errors"
6 "maps"
7 )
8
9 func (c *Client[T]) groupIDs(ids []string, keyFn KeyFn) (hits map[string]T, misses, backgroundRefreshes, synchronousRefreshes []string) {
10 hits = make(map[string]T)
11 misses = make([]string, 0)
12 backgroundRefreshes = make([]string, 0)
13 synchronousRefreshes = make([]string, 0)
14
15 for _, id := range ids {
16 key := keyFn(id)
17 value, exists, markedAsMissing, backgroundRefresh, synchronousRefresh := c.getWithState(key)
18
19 if synchronousRefresh {
20 synchronousRefreshes = append(synchronousRefreshes, id)
21 }
22
23 // Check if the record should be refreshed in the background.
24 if backgroundRefresh && !synchronousRefresh {
25 backgroundRefreshes = append(backgroundRefreshes, id)
26 }
27
28 if markedAsMissing {
29 continue
30 }
31
32 // If the record should be synchronously refreshed, it's going to be added to both the hits and misses maps.
33 if !exists {
34 misses = append(misses, id)
35 continue
36 }
37
38 hits[id] = value
39 }
40 return hits, misses, backgroundRefreshes, synchronousRefreshes
41 }
42
43 func getFetch[V, T any](ctx context.Context, c *Client[T], key string, fetchFn FetchFn[V]) (T, error) {
44 value, ok, markedAsMissing, backgroundRefresh, synchronousRefresh := c.getWithState(key)
45 wrappedFetch := wrap[T](distributedFetch(c, key, fetchFn))
46
47 if synchronousRefresh {
48 res, err := callAndCache(ctx, c, key, wrappedFetch)
49 // Check if the record has been deleted at the source. If it has, we'll
50 // delete it from the cache too. NOTE: The callAndCache function converts
51 // ErrNotFound to ErrMissingRecord if missing record storage is enabled.
52 if ok && errors.Is(err, ErrNotFound) {
53 c.Delete(key)
54 }
55
56 if errors.Is(err, ErrMissingRecord) || errors.Is(err, ErrNotFound) {
57 return res, err
58 }
59
60 // If the call to synchrounously refresh the record failed,
61 // we'll return the latest value if we have it in the cache
62 // along with a ErrOnlyCachedRecords error. The consumer can
63 // then decide whether to proceed with the cached data or to
64 // propagate the error.
65 if err != nil && ok {
66 return value, errors.Join(ErrOnlyCachedRecords, err)
67 }
68
69 return res, err
70 }
71
72 if backgroundRefresh {
73 c.safeGo(func() {
74 c.refresh(key, wrappedFetch)
75 })
76 }
77
78 if markedAsMissing {
79 return value, ErrMissingRecord
80 }
81
82 if ok {
83 return value, nil
84 }
85
86 return callAndCache(ctx, c, key, wrappedFetch)
87 }
88
89 // GetOrFetch attempts to retrieve the specified key from the cache. If the value
90 // is absent, it invokes the fetchFn function to obtain it and then stores the result.
91 // Additionally, when early refreshes are enabled, GetOrFetch determines if the record
92 // needs refreshing and, if necessary, schedules this task for background execution.
93 //
94 // Parameters:
95 //
96 // ctx - The context to be used for the request.
97 // key - The key to be fetched.
98 // fetchFn - Used to retrieve the data from the underlying data source if the key is not found in the cache.
99 //
100 // Returns:
101 //
102 // The value corresponding to the key and an error if one occurred.
103 func (c *Client[T]) GetOrFetch(ctx context.Context, key string, fetchFn FetchFn[T]) (T, error) {
104 return getFetch[T, T](ctx, c, key, fetchFn)
105 }
106
107 // GetOrFetch is a convenience function that performs type assertion on the result of client.GetOrFetch.
108 //
109 // Parameters:
110 //
111 // ctx - The context to be used for the request.
112 // c - The cache client.
113 // key - The key to be fetched.
114 // fetchFn - Used to retrieve the data from the underlying data source if the key is not found in the cache.
115 //
116 // Returns:
117 //
118 // The value corresponding to the key and an error if one occurred.
119 //
120 // Type Parameters:
121 //
122 // V - The type returned by the fetchFn. Must be assignable to T.
123 // T - The type stored in the cache.
124 func GetOrFetch[V, T any](ctx context.Context, c *Client[T], key string, fetchFn FetchFn[V]) (V, error) {
125 res, err := getFetch[V, T](ctx, c, key, fetchFn)
126 return unwrap[V](res, err)
127 }
128
129 func getFetchBatch[V, T any](ctx context.Context, c *Client[T], ids []string, keyFn KeyFn, fetchFn BatchFetchFn[V]) (map[string]T, error) {
130 wrappedFetch := wrapBatch[T](distributedBatchFetch[V, T](c, keyFn, fetchFn))
131 cachedRecords, cacheMisses, idsToBackgroundRefresh, idsToSynchronouslyRefresh := c.groupIDs(ids, keyFn)
132
133 // Schedule background refreshes.
134 if len(idsToBackgroundRefresh) > 0 {
135 c.safeGo(func() {
136 if c.bufferRefreshes {
137 bufferBatchRefresh(c, idsToBackgroundRefresh, keyFn, wrappedFetch)
138 return
139 }
140 c.refreshBatch(idsToBackgroundRefresh, keyFn, wrappedFetch)
141 })
142 }
143
144 // If we were able to retrieve all records from the cache, we can return them straight away.
145 if len(cacheMisses) == 0 && len(idsToSynchronouslyRefresh) == 0 {
146 return cachedRecords, nil
147 }
148
149 // Create a list of the IDs that we're going to fetch from the underlying data source or distributed storage.
150 cacheMissesAndSyncRefreshes := make([]string, 0, len(cacheMisses)+len(idsToSynchronouslyRefresh))
151 cacheMissesAndSyncRefreshes = append(cacheMissesAndSyncRefreshes, cacheMisses...)
152 cacheMissesAndSyncRefreshes = append(cacheMissesAndSyncRefreshes, idsToSynchronouslyRefresh...)
153
154 callBatchOpts := callBatchOpts[T]{ids: cacheMissesAndSyncRefreshes, keyFn: keyFn, fn: wrappedFetch}
155 response, err := callAndCacheBatch(ctx, c, callBatchOpts)
156
157 // If we did a call to synchronously refresh some of the records, and it
158 // didn't fail, we'll have to check if any of the IDs have been deleted at
159 // the underlying data source. If they have, we'll have to delete them from
160 // the cache and remove them from the cachedRecords map so that we don't
161 // return them.
162 if err == nil && len(idsToSynchronouslyRefresh) > 0 {
163 for _, id := range idsToSynchronouslyRefresh {
164 // If we have it in the cache, but not in the response, it means
165 // that the ID no longer exists at the underlying data source.
166 _, okResponse := response[id]
167 _, okCache := cachedRecords[id]
168 if okCache && !okResponse {
169 if !c.storeMissingRecords {
170 c.Delete(keyFn(id))
171 }
172 delete(cachedRecords, id)
173 }
174 }
175 }
176
177 if err != nil && !errors.Is(err, ErrOnlyCachedRecords) {
178 // At this point, the call for the IDs that we didn't have in the cache
179 // have failed. However, these ID's could have been picked from multiple
180 // in-flight requests. Hence, we'll check if we're able to add any of these
181 // IDs to the cached records before returning.
182 if len(cachedRecords) > 0 {
183 maps.Copy(cachedRecords, response)
184 return cachedRecords, errors.Join(ErrOnlyCachedRecords, err)
185 }
186 }
187
188 maps.Copy(cachedRecords, response)
189 return cachedRecords, err
190 }
191
192 // GetOrFetchBatch attempts to retrieve the specified ids from the cache. If
193 // any of the values are absent, it invokes the fetchFn function to obtain them
194 // and then stores the result. Additionally, when background refreshes are
195 // enabled, GetOrFetch determines if any of the records need refreshing and, if
196 // necessary, schedules this to be performed in the background.
197 //
198 // Parameters:
199 //
200 // ctx - The context to be used for the request.
201 // ids - The list of IDs to be fetched.
202 // keyFn - Used to generate the cache key for each ID.
203 // fetchFn - Used to retrieve the data from the underlying data source if any IDs are not found in the cache.
204 //
205 // Returns:
206 //
207 // A map of IDs to their corresponding values and an error if one occurred.
208 func (c *Client[T]) GetOrFetchBatch(ctx context.Context, ids []string, keyFn KeyFn, fetchFn BatchFetchFn[T]) (map[string]T, error) {
209 return getFetchBatch[T, T](ctx, c, ids, keyFn, fetchFn)
210 }
211
212 // GetOrFetchBatch is a convenience function that performs type assertion on the
213 // result of client.GetOrFetchBatch.
214 //
215 // Parameters:
216 //
217 // ctx - The context to be used for the request.
218 // c - The cache client.
219 // ids - The list of IDs to be fetched.
220 // keyFn - Used to prefix each ID in order to create a unique cache key.
221 // fetchFn - Used to retrieve the data from the underlying data source.
222 //
223 // Returns:
224 //
225 // A map of ids to their corresponding values and an error if one occurred.
226 //
227 // Type Parameters:
228 //
229 // V - The type returned by the fetchFn. Must be assignable to T.
230 // T - The type stored in the cache.
231
232 func GetOrFetchBatch[V, T any](ctx context.Context, c *Client[T], ids []string, keyFn KeyFn, fetchFn BatchFetchFn[V]) (map[string]V, error) {
233 res, err := getFetchBatch[V, T](ctx, c, ids, keyFn, fetchFn)
234 return unwrapBatch[V](res, err)
235 }