Documentation
¶
Overview ¶
Package stalecache provides a cache with optional TTL.
The cache auto reloads after it's stale.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[T any] struct { // contains filtered or unexported fields }
Cache defines a cached single value with optional TTL.
func (*Cache[T]) Load ¶
Load loads the cached value.
If the cached value is stale (or never loaded before), the set loader will be called to load it from external source.
If the cached last loader call failed, it immediately calls loader again with the same ctx and return the new result instead. If the cached value is stale but the new loader call failed, it returns the cached stale data with error form the new loader call.
In worst case scenario a single Load could call loader twice: once another goroutine is causing it to reload (or it's loaded for the first time), and the first loader failed so it immediately calls loader again.
A single Cache instance would never have 2 loader calls at the same time.
type Loader ¶
Loader defines the callback to load value from external source.
It's called when either the ttl passed, or when validator returned false.
type Option ¶
type Option[T any] func(*opt[T])
Option defines Cache options.
func WithTTL ¶
WithTTL is an Option to set the TTL (time-to-live) for the cache.
Default is 0, means the cache does not expire. Set it to positive value will cause it to be re-loaded after expired.
func WithValidator ¶
func WithValidator[T any](validator func(ctx context.Context, data *T, loaded time.Time) (fresh bool)) Option[T]
WithValidator is an Option to set a validator to the cache.
Default is nil. A non-nil validator will be called (only after the ttl check passed if set), and if it returns true the cache will be re-loaded.
An usual use case for validator is to use a faster external source (for example, redis) to validate whether the cache is fresh.