| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"log" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/viccon/sturdyc" |
| 9 |
) |
| 10 |
|
| 11 |
// NOTE: We won't use all of these features in this example. However, I thought |
| 12 |
// that it would be interesting to show how a cache client that makes full use |
| 13 |
// of this functionality might be configured. |
| 14 |
|
| 15 |
// Basic configuration for the cache. |
| 16 |
const ( |
| 17 |
capacity = 100_000 |
| 18 |
numberOfShards = 100 |
| 19 |
ttl = 5 * time.Minute |
| 20 |
percentageOfRecordsToEvictWhenFull = 25 |
| 21 |
) |
| 22 |
|
| 23 |
// Configuration for the early in-memory refreshes. |
| 24 |
const ( |
| 25 |
minRefreshTime = 100 * time.Millisecond |
| 26 |
maxRefreshTime = 500 * time.Millisecond |
| 27 |
synchronousRefreshTime = 30 * time.Second |
| 28 |
retryBaseDelay = time.Second |
| 29 |
) |
| 30 |
|
| 31 |
// Configuration for the refresh coalescing. |
| 32 |
const ( |
| 33 |
idealBufferSize = 50 |
| 34 |
bufferTimeout = 15 * time.Second |
| 35 |
) |
| 36 |
|
| 37 |
func newAPIClient(distributedStorage sturdyc.DistributedStorage) *apiClient { |
| 38 |
return &apiClient{ |
| 39 |
cache: sturdyc.New[any](capacity, numberOfShards, ttl, percentageOfRecordsToEvictWhenFull, |
| 40 |
sturdyc.WithMissingRecordStorage(), |
| 41 |
sturdyc.WithEarlyRefreshes(minRefreshTime, maxRefreshTime, synchronousRefreshTime, retryBaseDelay), |
| 42 |
sturdyc.WithRefreshCoalescing(idealBufferSize, bufferTimeout), |
| 43 |
sturdyc.WithDistributedStorage(distributedStorage), |
| 44 |
), |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
type apiClient struct { |
| 49 |
cache *sturdyc.Client[any] |
| 50 |
} |
| 51 |
|
| 52 |
type options struct { |
| 53 |
ID string |
| 54 |
SortOrder string |
| 55 |
} |
| 56 |
|
| 57 |
func (c *apiClient) GetShippingOptions(ctx context.Context, id string, sortOrder string) ([]string, error) { |
| 58 |
cacheKey := c.cache.PermutatedKey("shipping-options", options{ID: id, SortOrder: sortOrder}) |
| 59 |
fetchFn := func(_ context.Context) ([]string, error) { |
| 60 |
log.Println("Fetching shipping options from the underlying data source") |
| 61 |
return []string{"standard", "express", "next-day"}, nil |
| 62 |
} |
| 63 |
return sturdyc.GetOrFetch(ctx, c.cache, cacheKey, fetchFn) |
| 64 |
} |