| 1 |
package sturdyc |
| 2 |
|
| 3 |
import "time" |
| 4 |
|
| 5 |
type Option func(*Config) |
| 6 |
|
| 7 |
// WithMetrics is used to make the cache report metrics. |
| 8 |
func WithMetrics(recorder MetricsRecorder) Option { |
| 9 |
return func(c *Config) { |
| 10 |
recorder.ObserveCacheSize(c.getSize) |
| 11 |
c.metricsRecorder = &distributedMetricsRecorder{recorder} |
| 12 |
} |
| 13 |
} |
| 14 |
|
| 15 |
// WithClock can be used to change the clock that the cache uses. This is useful for testing. |
| 16 |
func WithClock(clock Clock) Option { |
| 17 |
return func(c *Config) { |
| 18 |
c.clock = clock |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
// WithEvictionInterval sets the interval at which the cache scans a shard to |
| 23 |
// evict expired entries. Setting this to a higher value will increase cache |
| 24 |
// performance and is advised if you don't think you'll exceed the capacity. |
| 25 |
// If the capacity is reached, the cache will still trigger an eviction. |
| 26 |
func WithEvictionInterval(interval time.Duration) Option { |
| 27 |
return func(c *Config) { |
| 28 |
c.evictionInterval = interval |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
// WithNoContinuousEvictions improves cache performance when the cache capacity |
| 33 |
// is unlikely to be exceeded. While this setting disables the continuous |
| 34 |
// eviction job, it still allows for the eviction of the least recently used |
| 35 |
// items once the cache reaches its full capacity. |
| 36 |
func WithNoContinuousEvictions() Option { |
| 37 |
return func(c *Config) { |
| 38 |
c.disableContinuousEvictions = true |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
// WithMissingRecordStorage allows the cache to mark keys as missing from the |
| 43 |
// underlying data source. This allows you to stop streams of outgoing requests |
| 44 |
// for requests that don't exist. The keys will still have the same TTL and |
| 45 |
// refresh durations as any of the other record in the cache. |
| 46 |
func WithMissingRecordStorage() Option { |
| 47 |
return func(c *Config) { |
| 48 |
c.storeMissingRecords = true |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
// WithEarlyRefreshes instructs the cache to refresh the keys that are in |
| 53 |
// active rotation, thereby preventing them from ever expiring. This can have a |
| 54 |
// significant impact on your application's latency as you're able to |
| 55 |
// continuously serve frequently used keys from memory. An asynchronous |
| 56 |
// background refresh gets scheduled when a key is requested again after a |
| 57 |
// random time between minRefreshTime and maxRefreshTime has passed. This is an |
| 58 |
// important distinction because it means that the cache won't just naively |
| 59 |
// refresh every key it's ever seen. The third argument to this function will |
| 60 |
// also allow you to provide a duration for when a refresh should become |
| 61 |
// synchronous. If any of the refreshes were to fail, you'll get the latest |
| 62 |
// data from the cache for the duration of the TTL. |
| 63 |
func WithEarlyRefreshes(minAsyncRefreshTime, maxAsyncRefreshTime, syncRefreshTime, retryBaseDelay time.Duration) Option { |
| 64 |
return func(c *Config) { |
| 65 |
c.earlyRefreshes = true |
| 66 |
c.minAsyncRefreshTime = minAsyncRefreshTime |
| 67 |
c.maxAsyncRefreshTime = maxAsyncRefreshTime |
| 68 |
c.syncRefreshTime = syncRefreshTime |
| 69 |
c.retryBaseDelay = retryBaseDelay |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
// WithRefreshCoalescing will make the cache refresh data from batchable |
| 74 |
// endpoints more efficiently. It is going to create a buffer for each cache |
| 75 |
// key permutation, and gather IDs until the bufferSize is reached, or the |
| 76 |
// bufferDuration has passed. |
| 77 |
// |
| 78 |
// NOTE: This requires the WithEarlyRefreshes functionality to be enabled. |
| 79 |
func WithRefreshCoalescing(bufferSize int, bufferDuration time.Duration) Option { |
| 80 |
return func(c *Config) { |
| 81 |
c.bufferRefreshes = true |
| 82 |
c.bufferSize = bufferSize |
| 83 |
c.bufferTimeout = bufferDuration |
| 84 |
c.permutationBufferMap = make(map[string]*buffer) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
// WithRelativeTimeKeyFormat allows you to control the truncation of time.Time |
| 89 |
// values that are being passed in to the cache key functions. |
| 90 |
func WithRelativeTimeKeyFormat(truncation time.Duration) Option { |
| 91 |
return func(c *Config) { |
| 92 |
c.useRelativeTimeKeyFormat = true |
| 93 |
c.keyTruncation = truncation |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
// WithLog allows you to set a custom logger for the cache. The cache isn't chatty, |
| 98 |
// and will only log warnings and errors that would be a nightmare to debug. If you |
| 99 |
// absolutely don't want any logs, you can pass in the sturdyc.NoopLogger. |
| 100 |
func WithLog(log Logger) Option { |
| 101 |
return func(c *Config) { |
| 102 |
c.log = log |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
// WithDistributedStorage allows you to use the cache with a distributed |
| 107 |
// key-value store. The "GetOrFetch" and "GetOrFetchBatch" functions will check |
| 108 |
// this store first and only proceed to the underlying data source if the key |
| 109 |
// is missing. When a record is retrieved from the underlying data source, it |
| 110 |
// is written both to memory and to the distributed storage. You are |
| 111 |
// responsible for setting TTL and eviction policies for the distributed |
| 112 |
// storage. Sturdyc will only read and write records. |
| 113 |
func WithDistributedStorage(storage DistributedStorage) Option { |
| 114 |
return func(c *Config) { |
| 115 |
c.distributedStorage = &distributedStorage{storage} |
| 116 |
c.distributedEarlyRefreshes = false |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
// WithDistributedStorageEarlyRefreshes is the distributed equivalent of the |
| 121 |
// "WithEarlyRefreshes" option. It allows distributed records to be refreshed |
| 122 |
// before their TTL expires. If a refresh fails, the cache will fall back to |
| 123 |
// what was returned by the distributed storage. This ensures that data can be |
| 124 |
// served for the duration of the TTL even if an upstream system goes down. To |
| 125 |
// use this functionality, you need to implement an interface with two |
| 126 |
// additional methods for deleting records compared to the simpler |
| 127 |
// "WithDistributedStorage" option. This is because a distributed cache that is |
| 128 |
// used with this option might have low refresh durations but high TTLs. If a |
| 129 |
// record is deleted from the underlying data source, it needs to be propagated |
| 130 |
// to the distributed storage before the TTL expires. However, please note that |
| 131 |
// you are still responsible for managing the TTL and eviction policies for the |
| 132 |
// distributed storage. Sturdyc will only delete records that have been removed |
| 133 |
// at the underlying data source. |
| 134 |
func WithDistributedStorageEarlyRefreshes(storage DistributedStorageWithDeletions, refreshAfter time.Duration) Option { |
| 135 |
return func(c *Config) { |
| 136 |
c.distributedStorage = storage |
| 137 |
c.distributedEarlyRefreshes = true |
| 138 |
c.distributedRefreshAfterDuration = refreshAfter |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
// WithDistributedMetrics instructs the cache to report additional metrics |
| 143 |
// regarding its interaction with the distributed storage. |
| 144 |
func WithDistributedMetrics(metricsRecorder DistributedMetricsRecorder) Option { |
| 145 |
return func(c *Config) { |
| 146 |
metricsRecorder.ObserveCacheSize(c.getSize) |
| 147 |
c.metricsRecorder = metricsRecorder |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
// validateConfig is a helper function that panics if the cache has been configured incorrectly. |
| 152 |
func validateConfig(capacity, numShards int, ttl time.Duration, evictionPercentage int, cfg *Config) { |
| 153 |
if capacity <= 0 { |
| 154 |
panic("capacity must be greater than 0") |
| 155 |
} |
| 156 |
|
| 157 |
if numShards <= 0 { |
| 158 |
panic("numShards must be greater than 0") |
| 159 |
} |
| 160 |
|
| 161 |
if ttl <= 0 { |
| 162 |
panic("ttl must be greater than 0") |
| 163 |
} |
| 164 |
|
| 165 |
if evictionPercentage < 0 || evictionPercentage > 100 { |
| 166 |
panic("evictionPercentage must be between 0 and 100") |
| 167 |
} |
| 168 |
|
| 169 |
if !cfg.earlyRefreshes && cfg.bufferRefreshes { |
| 170 |
panic("refresh buffering requires early refreshes to be enabled") |
| 171 |
} |
| 172 |
|
| 173 |
if cfg.bufferRefreshes && cfg.bufferSize < 1 { |
| 174 |
panic("batchSize must be greater than 0") |
| 175 |
} |
| 176 |
|
| 177 |
if cfg.bufferRefreshes && cfg.bufferTimeout < 1 { |
| 178 |
panic("bufferTimeout must be greater than 0") |
| 179 |
} |
| 180 |
|
| 181 |
if cfg.evictionInterval < 1 { |
| 182 |
panic("evictionInterval must be greater than 0") |
| 183 |
} |
| 184 |
|
| 185 |
if cfg.minAsyncRefreshTime > cfg.maxAsyncRefreshTime { |
| 186 |
panic("minRefreshTime must be less than or equal to maxRefreshTime") |
| 187 |
} |
| 188 |
|
| 189 |
if cfg.maxAsyncRefreshTime > cfg.syncRefreshTime { |
| 190 |
panic("maxRefreshTime must be less than or equal to synchronousRefreshTime") |
| 191 |
} |
| 192 |
|
| 193 |
if cfg.retryBaseDelay < 0 { |
| 194 |
panic("retryBaseDelay must be greater than or equal to 0") |
| 195 |
} |
| 196 |
} |