Debian Codegraph @

examples/buffering/main.go

raw
1 package main
2
3 import (
4 "context"
5 "fmt"
6 "log"
7 "time"
8
9 "github.com/viccon/sturdyc"
10 )
11
12 type OrderOptions struct {
13 CarrierName string
14 LatestDeliveryTime string
15 }
16
17 type OrderAPI struct {
18 *sturdyc.Client[string]
19 }
20
21 func NewOrderAPI(client *sturdyc.Client[string]) *OrderAPI {
22 return &OrderAPI{client}
23 }
24
25 func (a *OrderAPI) OrderStatus(ctx context.Context, ids []string, opts OrderOptions) (map[string]string, error) {
26 // We use the PermutedBatchKeyFn when an ID isn't enough to uniquely identify a
27 // record. The cache is going to store each id once per set of options. In a more
28 // realistic scenario, the opts would be query params or arguments to a DB query.
29 cacheKeyFn := a.PermutatedBatchKeyFn("key", opts)
30
31 // We'll create a fetchFn with a closure that captures the options. For this
32 // simple example, it logs and returns the status for each order, but you could
33 // just as easily have called an external API.
34 fetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) {
35 log.Printf("Fetching: %v, carrier: %s, delivery time: %s\n", cacheMisses, opts.CarrierName, opts.LatestDeliveryTime)
36 response := map[string]string{}
37 for _, id := range cacheMisses {
38 response[id] = fmt.Sprintf("Available for %s", opts.CarrierName)
39 }
40 return response, nil
41 }
42 return a.GetOrFetchBatch(ctx, ids, cacheKeyFn, fetchFn)
43 }
44
45 func main() {
46 // Maximum number of entries in the sturdyc.
47 capacity := 10000
48 // Number of shards to use for the sturdyc.
49 numShards := 10
50 // Time-to-live for cache entries.
51 ttl := 2 * time.Hour
52 // Percentage of entries to evict when the cache is full. Setting this
53 // to 0 will make set a no-op if the cache has reached its capacity.
54 evictionPercentage := 10
55 // Set a minimum and maximum refresh delay for the sturdyc. This is
56 // used to spread out the refreshes for entries evenly over time.
57 minRefreshDelay := time.Second
58 maxRefreshDelay := time.Second * 2
59 // Set a synchronous refresh delay for when we want a refresh to happen synchronously.
60 synchronousRefreshDelay := time.Second * 30
61 // The base for exponential backoff when retrying a refresh.
62 retryBaseDelay := time.Millisecond * 10
63 // Whether to store misses in the sturdyc. This can be useful to
64 // prevent the cache from fetching a non-existent key repeatedly.
65
66 // With refresh coalescing enabled, the cache will buffer refreshes
67 // until the batch size is reached or the buffer timeout is hit.
68 batchSize := 3
69 batchBufferTimeout := time.Second * 30
70
71 // Create a new cache client with the specified configuration.
72 cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
73 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryBaseDelay),
74 sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout),
75 )
76
77 // We will fetch these IDs using various option sets, meaning that the ID alone
78 // won't be enough to uniquely identify a record. Instead, the cache is going to
79 // store each record by combining the ID with the permutations of the options.
80 ids := []string{"id1", "id2", "id3"}
81 optionSetOne := OrderOptions{CarrierName: "FEDEX", LatestDeliveryTime: "2024-04-06"}
82 optionSetTwo := OrderOptions{CarrierName: "DHL", LatestDeliveryTime: "2024-04-07"}
83 optionSetThree := OrderOptions{CarrierName: "UPS", LatestDeliveryTime: "2024-04-08"}
84
85 orderClient := NewOrderAPI(cacheClient)
86 ctx := context.Background()
87
88 // Next, we'll fetch the entire list of IDs for all options sets.
89 log.Println("Filling the cache with all IDs for all option sets")
90 orderClient.OrderStatus(ctx, ids, optionSetOne)
91 orderClient.OrderStatus(ctx, ids, optionSetTwo)
92 orderClient.OrderStatus(ctx, ids, optionSetThree)
93 log.Println("Cache filled")
94
95 // At this point, the cache has stored each record individually for each option set:
96 // FEDEX-2024-04-06-id1
97 // DHL-2024-04-07-id1
98 // UPS-2024-04-08-id1
99 // etc..
100
101 // Sleep to make sure that all records are due for a refresh.
102 time.Sleep(maxRefreshDelay + 1)
103
104 // Fetch each id for each option set.
105 for i := 0; i < len(ids); i++ {
106 orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetOne)
107 orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetTwo)
108 orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetThree)
109 }
110
111 // Sleep for a second to allow the refresh logs to print.
112 time.Sleep(time.Second)
113 }