Debian Codegraph @

distribution.go

raw
1 package sturdyc
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "maps"
9 "time"
10 )
11
12 // distributedRecord represents the records that we're writing to the distributed storage.
13 type distributedRecord[V any] struct {
14 CreatedAt time.Time `json:"created_at"`
15 Value V `json:"value"`
16 IsMissingRecord bool `json:"is_missing_record"`
17 }
18
19 // DistributedStorage is an abstraction that the cache interacts with in order
20 // to keep the distributed storage and in-memory cache in sync. Please note that
21 // you are responsible for setting the TTL and eviction policy of this storage.
22 type DistributedStorage interface {
23 Get(ctx context.Context, key string) ([]byte, bool)
24 Set(ctx context.Context, key string, value []byte)
25 GetBatch(ctx context.Context, keys []string) map[string][]byte
26 SetBatch(ctx context.Context, records map[string][]byte)
27 }
28
29 // DistributedStorageWithDeletions is an abstraction that the cache interacts
30 // with when you want to use a distributed storage with early refreshes. Please
31 // note that you are responsible for setting the TTL and eviction policy of
32 // this storage. The cache will only call the delete functions when it performs
33 // a refresh and notices that the record has been deleted at the underlying
34 // data source.
35 type DistributedStorageWithDeletions interface {
36 DistributedStorage
37 Delete(ctx context.Context, key string)
38 DeleteBatch(ctx context.Context, keys []string)
39 }
40
41 // distributedStorage adds noop implementations for the delete functions so
42 // that the cache doesn't have to deal with multiple storage types.
43 type distributedStorage struct {
44 DistributedStorage
45 }
46
47 // Delete is a noop implementation of the delete function.
48 func (d *distributedStorage) Delete(_ context.Context, _ string) {
49 }
50
51 // DeleteBatch is a noop implementation of the delete batch function.
52 func (d *distributedStorage) DeleteBatch(_ context.Context, _ []string) {
53 }
54
55 func marshalRecord[V, T any](value V, c *Client[T]) ([]byte, error) {
56 record := distributedRecord[V]{CreatedAt: c.clock.Now(), Value: value, IsMissingRecord: false}
57 bytes, err := json.Marshal(record)
58 if err != nil {
59 c.log.Error(fmt.Sprintf("sturdyc: error marshalling record: %v", err))
60 }
61 return bytes, err
62 }
63
64 func marshalMissingRecord[V, T any](c *Client[T]) ([]byte, error) {
65 var missingRecord distributedRecord[V]
66 missingRecord.CreatedAt = c.clock.Now()
67 missingRecord.IsMissingRecord = true
68 bytes, err := json.Marshal(missingRecord)
69 if err != nil {
70 c.log.Error(fmt.Sprintf("sturdyc: error marshalling missing record: %v", err))
71 }
72 return bytes, err
73 }
74
75 func unmarshalRecord[V any](bytes []byte, key string, log Logger) (distributedRecord[V], error) {
76 var record distributedRecord[V]
77 unmarshalErr := json.Unmarshal(bytes, &record)
78 if unmarshalErr != nil {
79 log.Error("sturdyc: error unmarshalling key: " + key)
80 }
81 return record, unmarshalErr
82 }
83
84 func writeMissingRecord[V, T any](c *Client[T], key string) {
85 c.safeGo(func() {
86 if missingRecordBytes, missingRecordErr := marshalMissingRecord[V](c); missingRecordErr == nil {
87 c.distributedStorage.Set(context.Background(), key, missingRecordBytes)
88 }
89 })
90 }
91
92 func distributedFetch[V, T any](c *Client[T], key string, fetchFn FetchFn[V]) FetchFn[V] {
93 if c.distributedStorage == nil {
94 return fetchFn
95 }
96
97 return func(ctx context.Context) (V, error) {
98 stale, hasStale := *new(V), false
99 bytes, existsInDistributedStorage := c.distributedStorage.Get(ctx, key)
100 c.reportDistributedCacheHit(existsInDistributedStorage)
101
102 if existsInDistributedStorage {
103 record, unmarshalErr := unmarshalRecord[V](bytes, key, c.log)
104 if unmarshalErr != nil {
105 return record.Value, unmarshalErr
106 }
107
108 // Check if the record is fresh enough to not need a refresh.
109 if !c.distributedEarlyRefreshes || c.clock.Since(record.CreatedAt) < c.distributedRefreshAfterDuration {
110 if record.IsMissingRecord {
111 c.reportDistributedMissingRecord()
112 return record.Value, ErrNotFound
113 }
114 return record.Value, nil
115 }
116 c.reportDistributedRefresh()
117 stale, hasStale = record.Value, true
118 }
119
120 // Before we call the fetchFn, we'll do an unblocking read to see if the
121 // context has been cancelled. If it has, we'll return a stale value if we
122 // have one available.
123 select {
124 case <-ctx.Done():
125 if hasStale {
126 return stale, errors.Join(errOnlyDistributedRecords, ctx.Err())
127 }
128 return *(new(V)), ctx.Err()
129 default:
130 }
131
132 // If it's not fresh enough, we'll retrieve it from the source.
133 response, fetchErr := fetchFn(ctx)
134 if fetchErr == nil {
135 c.safeGo(func() {
136 if recordBytes, marshalErr := marshalRecord[V](response, c); marshalErr == nil {
137 c.distributedStorage.Set(context.Background(), key, recordBytes)
138 }
139 })
140 return response, nil
141 }
142
143 if errors.Is(fetchErr, ErrNotFound) {
144 if c.storeMissingRecords {
145 writeMissingRecord[V](c, key)
146 return response, fetchErr
147 }
148 if hasStale {
149 c.safeGo(func() {
150 c.distributedStorage.Delete(context.Background(), key)
151 })
152 }
153 return response, fetchErr
154 }
155
156 if hasStale {
157 c.reportDistributedStaleFallback()
158 return stale, errors.Join(errOnlyDistributedRecords, fetchErr)
159 }
160
161 return response, fetchErr
162 }
163 }
164
165 func distributedBatchFetch[V, T any](c *Client[T], keyFn KeyFn, fetchFn BatchFetchFn[V]) BatchFetchFn[V] {
166 if c.distributedStorage == nil {
167 return fetchFn
168 }
169
170 return func(ctx context.Context, ids []string) (map[string]V, error) {
171 // We need to be able to look up the ID of the record based on the key.
172 keyIDMap := make(map[string]string, len(ids))
173 keys := make([]string, 0, len(ids))
174 for _, id := range ids {
175 key := keyFn(id)
176 keyIDMap[key] = id
177 keys = append(keys, key)
178 }
179
180 distributedRecords := c.distributedStorage.GetBatch(ctx, keys)
181 // Group the records we got from the distributed storage into fresh/stale maps.
182 fresh := make(map[string]V, len(ids))
183 stale := make(map[string]V, len(ids))
184
185 // The IDs that we need to get from the underlying data source are the ones that are stale or missing.
186 idsToRefresh := make([]string, 0, len(ids))
187 for _, id := range ids {
188 key := keyFn(id)
189 bytes, existsInDistributedStorage := distributedRecords[key]
190 c.reportDistributedCacheHit(existsInDistributedStorage)
191
192 if !existsInDistributedStorage {
193 idsToRefresh = append(idsToRefresh, id)
194 continue
195 }
196
197 record, unmarshalErr := unmarshalRecord[V](bytes, key, c.log)
198 if unmarshalErr != nil {
199 idsToRefresh = append(idsToRefresh, id)
200 continue
201 }
202
203 // If early refreshes isn't enabled it means all records are fresh, otherwise we'll check the CreatedAt time.
204 if !c.distributedEarlyRefreshes || c.clock.Since(record.CreatedAt) < c.distributedRefreshAfterDuration {
205 // We never want to return missing records.
206 if record.IsMissingRecord {
207 c.reportDistributedMissingRecord()
208 continue
209 }
210
211 fresh[id] = record.Value
212 continue
213 }
214
215 idsToRefresh = append(idsToRefresh, id)
216 c.reportDistributedRefresh()
217
218 // We never want to return missing records.
219 if record.IsMissingRecord {
220 c.reportDistributedMissingRecord()
221 continue
222 }
223 stale[id] = record.Value
224 }
225
226 if len(idsToRefresh) == 0 {
227 return fresh, nil
228 }
229
230 // Before we call the fetchFn, we'll do an unblocking read to see if the
231 // context has been cancelled. If it has, we'll return any potential
232 // records we got from the distributed storage.
233 select {
234 case <-ctx.Done():
235 maps.Copy(stale, fresh)
236
237 // If we didn't get any records from the distributed storage,
238 // we'll return the error from the fetch function as-is.
239 if len(stale) < 1 {
240 return stale, ctx.Err()
241 }
242 return stale, errors.Join(errOnlyDistributedRecords, ctx.Err())
243 default:
244 }
245
246 dataSourceResponses, err := fetchFn(ctx, idsToRefresh)
247 // In case of an error, we'll proceed with the ones we got from the distributed storage.
248 // NOTE: It's important that we return a specific error here, otherwise we'll potentially
249 // end up caching the IDs that we weren't able to retrieve from the underlying data source
250 // as missing records.
251 if err != nil {
252 for i := 0; i < len(stale); i++ {
253 c.reportDistributedStaleFallback()
254 }
255 maps.Copy(stale, fresh)
256
257 // If we didn't get any records from the distributed storage,
258 // we'll return the error from the fetch function as-is.
259 if len(stale) < 1 {
260 return dataSourceResponses, err
261 }
262
263 return stale, errors.Join(errOnlyDistributedRecords, err)
264 }
265
266 // Next, we'll want to check if we should change any of the records to be missing or perform deletions.
267 recordsToWrite := make(map[string][]byte, len(dataSourceResponses))
268 keysToDelete := make([]string, 0, max(len(idsToRefresh)-len(dataSourceResponses), 0))
269 for _, id := range idsToRefresh {
270 key := keyFn(id)
271 if response, ok := dataSourceResponses[id]; ok {
272 if recordBytes, marshalErr := marshalRecord[V](response, c); marshalErr == nil {
273 recordsToWrite[key] = recordBytes
274 }
275 continue
276 }
277
278 // At this point, we know that we weren't able to retrieve this ID from the underlying data source.
279 if c.storeMissingRecords {
280 if bytes, err := marshalMissingRecord[V](c); err == nil {
281 recordsToWrite[key] = bytes
282 }
283 continue
284 }
285
286 // If the record exists in the distributed storage but not at the underlying data source, we'll have to delete it.
287 if _, okStale := stale[id]; okStale {
288 keysToDelete = append(keysToDelete, key)
289 }
290 }
291
292 if len(keysToDelete) > 0 {
293 c.safeGo(func() {
294 c.distributedStorage.DeleteBatch(context.Background(), keysToDelete)
295 })
296 }
297
298 if len(recordsToWrite) > 0 {
299 c.safeGo(func() {
300 c.distributedStorage.SetBatch(context.Background(), recordsToWrite)
301 })
302 }
303
304 maps.Copy(fresh, dataSourceResponses)
305 return fresh, nil
306 }
307 }