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