Debian Codegraph @

inflight.go

raw
1 package sturdyc
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "sync"
8 )
9
10 type inFlightCall[T any] struct {
11 sync.WaitGroup
12 val T
13 err error
14 }
15
16 // newFlight should be called with a lock.
17 func (c *Client[T]) newFlight(key string) *inFlightCall[T] {
18 call := new(inFlightCall[T])
19 call.Add(1)
20 c.inFlightMap[key] = call
21 return call
22 }
23
24 func makeCall[T any](ctx context.Context, c *Client[T], key string, fn FetchFn[T], call *inFlightCall[T]) {
25 defer func() {
26 if err := recover(); err != nil {
27 call.err = fmt.Errorf("sturdyc: panic recovered: %v", err)
28 }
29 call.Done()
30 c.inFlightMutex.Lock()
31 delete(c.inFlightMap, key)
32 c.inFlightMutex.Unlock()
33 }()
34
35 response, err := fn(ctx)
36 call.val = response
37
38 if c.storeMissingRecords && errors.Is(err, ErrNotFound) {
39 c.StoreMissingRecord(key)
40 call.err = ErrMissingRecord
41 return
42 }
43
44 if err != nil && !errors.Is(err, errOnlyDistributedRecords) {
45 call.err = err
46 return
47 }
48
49 if errors.Is(err, errOnlyDistributedRecords) {
50 call.err = onlyCachedRecords(err)
51 }
52
53 c.Set(key, response)
54 }
55
56 func callAndCache[T any](ctx context.Context, c *Client[T], key string, fn FetchFn[T]) (T, error) {
57 c.inFlightMutex.Lock()
58 if call, ok := c.inFlightMap[key]; ok {
59 c.inFlightMutex.Unlock()
60 call.Wait()
61 return call.val, call.err
62 }
63
64 call := c.newFlight(key)
65 c.inFlightMutex.Unlock()
66 makeCall(ctx, c, key, fn, call)
67 return call.val, call.err
68 }
69
70 // newBatchFlight should be called with a lock.
71 func (c *Client[T]) newBatchFlight(ids []string, keyFn KeyFn) *inFlightCall[map[string]T] {
72 call := new(inFlightCall[map[string]T])
73 call.val = make(map[string]T, len(ids))
74 call.Add(1)
75 for _, id := range ids {
76 c.inFlightBatchMap[keyFn(id)] = call
77 }
78 return call
79 }
80
81 func (c *Client[T]) endBatchFlight(ids []string, keyFn KeyFn, call *inFlightCall[map[string]T]) {
82 call.Done()
83 c.inFlightBatchMutex.Lock()
84 for _, id := range ids {
85 delete(c.inFlightBatchMap, keyFn(id))
86 }
87 c.inFlightBatchMutex.Unlock()
88 }
89
90 type makeBatchCallOpts[T any] struct {
91 ids []string
92 fn BatchFetchFn[T]
93 keyFn KeyFn
94 call *inFlightCall[map[string]T]
95 }
96
97 func makeBatchCall[T any](ctx context.Context, c *Client[T], opts makeBatchCallOpts[T]) {
98 response, err := opts.fn(ctx, opts.ids)
99 for id, record := range response {
100 // We never want to discard values from the fetch functions, even if they
101 // return an error. Instead, we'll pass them to the user along with any
102 // errors and let them decide what to do.
103 opts.call.val[id] = record
104 // However, we'll only write them to the cache if the fetchFunction returned a non-nil error.
105 if err == nil || errors.Is(err, errOnlyDistributedRecords) {
106 c.Set(opts.keyFn(id), record)
107 }
108 }
109
110 if err != nil && !errors.Is(err, errOnlyDistributedRecords) {
111 opts.call.err = err
112 return
113 }
114
115 if errors.Is(err, errOnlyDistributedRecords) {
116 opts.call.err = onlyCachedRecords(err)
117 }
118
119 // Check if we should store any of these IDs as a missing record. However, we
120 // don't want to do this if we only received records from the distributed
121 // storage. That means that the underlying data source errored for the ID's
122 // that we didn't have in our distributed storage, and we don't know wether
123 // these records are missing or not.
124 if c.storeMissingRecords && len(response) < len(opts.ids) && !errors.Is(err, errOnlyDistributedRecords) {
125 for _, id := range opts.ids {
126 if _, ok := response[id]; !ok {
127 c.StoreMissingRecord(opts.keyFn(id))
128 }
129 }
130 }
131 }
132
133 type callBatchOpts[T any] struct {
134 ids []string
135 keyFn KeyFn
136 fn BatchFetchFn[T]
137 }
138
139 func callAndCacheBatch[T any](ctx context.Context, c *Client[T], opts callBatchOpts[T]) (map[string]T, error) {
140 c.inFlightBatchMutex.Lock()
141
142 callIDs := make(map[*inFlightCall[map[string]T]][]string)
143 uniqueIDs := make([]string, 0, len(opts.ids))
144 for _, id := range opts.ids {
145 if call, ok := c.inFlightBatchMap[opts.keyFn(id)]; ok {
146 callIDs[call] = append(callIDs[call], id)
147 continue
148 }
149 uniqueIDs = append(uniqueIDs, id)
150 }
151
152 if len(uniqueIDs) > 0 {
153 call := c.newBatchFlight(uniqueIDs, opts.keyFn)
154 callIDs[call] = append(callIDs[call], uniqueIDs...)
155 go func() {
156 defer func() {
157 if err := recover(); err != nil {
158 call.err = fmt.Errorf("sturdyc: panic recovered: %v", err)
159 }
160 c.endBatchFlight(uniqueIDs, opts.keyFn, call)
161 }()
162 batchCallOpts := makeBatchCallOpts[T]{ids: uniqueIDs, fn: opts.fn, keyFn: opts.keyFn, call: call}
163 makeBatchCall(ctx, c, batchCallOpts)
164 }()
165 }
166 c.inFlightBatchMutex.Unlock()
167
168 var err error
169 response := make(map[string]T, len(opts.ids))
170 for call, callIDs := range callIDs {
171 call.Wait()
172
173 // We need to iterate through the values that WE want from this call. The batch
174 // could contain hundreds of IDs, but we might only want a few of them.
175 for _, id := range callIDs {
176 if v, ok := call.val[id]; ok {
177 response[id] = v
178 }
179 }
180
181 // This handles the scenario where we either don't get an error, or are
182 // using the distributed storage option and are able to get some records
183 // while the request to the underlying data source fails. In the latter
184 // case, we'll continue to accumulate partial responses as long as the only
185 // issue is cached-only records.
186 if err == nil || errors.Is(call.err, ErrOnlyCachedRecords) {
187 err = call.err
188 continue
189 }
190
191 // For any other kind of error, we'll short‑circuit the function and return.
192 return response, call.err
193 }
194
195 return response, err
196 }