trcache

package module
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2023 License: MIT Imports: 7 Imported by: 9

README

trcache GoDoc

Package trcache implements strongly-typed generics-based cache library wrappers.

type Cache[K comparable, V any] interface {
	Name() string
	Get(ctx context.Context, key K, options ...GetOption) (V, error)
	Set(ctx context.Context, key K, value V, options ...SetOption) error
	Delete(ctx context.Context, key K, options ...DeleteOption) error
}

type RefreshCache[K comparable, V any] interface {
	Cache[K, V]
	GetOrRefresh(ctx context.Context, key K, options ...RefreshOption) (V, error)
}

The wrappers are highly customizable and allows accessing the underlying cache functionality if desired.

A loadable (refresh) implementation is available for all caches, which provides a "GetOrRefresh" method which calls a refresh function if the data was not found in "Get".

A chain implementation is available to chain multiples caches in sequence, for example to use an in-memory cache with a lower TTL before calling a Redis backend.

Installation

go get github.com/rrgmc/trcache

Examples

ctx := context.Background()

cache, err := trmap.NewDefault[string, string]()

err = cache.Set(ctx, "a", "12")
if err != nil {
    panic(err)
}

v, err := cache.Get(ctx, "a")
if err != nil {
    panic(err)
}
fmt.Println(v)

err = cache.Delete(ctx, "a")
if err != nil {
    panic(err)
}

_, err = cache.Get(ctx, "a")
fmt.Println(err)
// Output:
// 12
// not found

With refresh:

ctx := context.Background()

cache, err := trmap.NewRefreshDefault[string, string](
    trcache.WithDefaultRefreshFunc[string, string](func(ctx context.Context, key string, options trcache.RefreshFuncOptions) (string, error) {
        return fmt.Sprintf("abc%d", options.Data), nil
    }),
)
if err != nil {
    panic(err)
}

err = cache.Set(ctx, "a", "12")
if err != nil {
    panic(err)
}

v, err := cache.Get(ctx, "a")
if err != nil {
    panic(err)
}
fmt.Println(v)

err = cache.Delete(ctx, "a")
if err != nil {
    panic(err)
}

_, err = cache.Get(ctx, "a")
fmt.Println(err)

v, err = cache.GetOrRefresh(ctx, "b", trcache.WithRefreshData[string, string](123))
if err != nil {
    panic(err)
}
fmt.Println(v)

// Output:
// 12
// not found
// abc123

Implementations

Author

Rangel Reale (rangelreale@gmail.com)

Documentation

Overview

Package trcache implements strongly-typed generics-based cache library wrappers.

The wrappers are highly customizable and allows accessing the underlying cache functionality if desired.

A loadable (refresh) implementation is available for all caches, which provides a "GetOrRefresh" method which calls a refresh function if the data was not found in "Get".

Example:

ctx := context.Background()

cache, err := trmap.NewDefault[string, string]()

err = cache.Set(ctx, "a", "12")
if err != nil {
	panic(err)
}

v, err := cache.Get(ctx, "a")
if err != nil {
	panic(err)
}
fmt.Println(v)

err = cache.Delete(ctx, "a")
if err != nil {
	panic(err)
}

_, err = cache.Get(ctx, "a")
fmt.Println(err)
// Output:
// 12
// not found

Example with refresh:

ctx := context.Background()

cache, err := trmap.NewRefreshDefault[string, string](
	trcache.WithDefaultRefreshFunc[string, string](func(ctx context.Context, key string, options trcache.RefreshFuncOptions) (string, error) {
		return fmt.Sprintf("abc%d", options.Data), nil
	}),
)
if err != nil {
	panic(err)
}

err = cache.Set(ctx, "a", "12")
if err != nil {
	panic(err)
}

v, err := cache.Get(ctx, "a")
if err != nil {
	panic(err)
}
fmt.Println(v)

err = cache.Delete(ctx, "a")
if err != nil {
	panic(err)
}

_, err = cache.Get(ctx, "a")
fmt.Println(err)

v, err = cache.GetOrRefresh(ctx, "b", trcache.WithRefreshData[string, string](123))
if err != nil {
	panic(err)
}
fmt.Println(v)

// Output:
// 12
// not found
// abc123

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound     = errors.New("not found")     // key not found
	ErrNotSupported = errors.New("not supported") // operation not supported
)

Functions

func ConcatOptions

func ConcatOptions[S ~[]O, O Option](options ...S) S

ConcatOptions concatenates multiple option lists.

func StringValue

func StringValue(key any) string

Types

type Cache

type Cache[K comparable, V any] interface {
	// Name returns the name for the cache. It can be useful in cases where multiple caches are used at the same time,
	// like on [github.com/rrgmc/trcache/cache/chain.Chain]. It often is blank.
	Name() string

	// Get gets the value of an item from the cache with this key. If not found, it returns [ErrNotFound] as the error.
	Get(ctx context.Context, key K, options ...GetOption) (V, error)

	// Set sets the value of the key on the cache.
	Set(ctx context.Context, key K, value V, options ...SetOption) error

	// Delete deletes the key from the cache.
	Delete(ctx context.Context, key K, options ...DeleteOption) error
}

Cache is the base interface for all cache implementations.

type CacheRefreshFunc

type CacheRefreshFunc[K comparable, V any] func(ctx context.Context, key K, options RefreshFuncOptions) (V, error)

CacheRefreshFunc is the function signature to use for refreshing values on RefreshCache.

type CallDefaultOptions

type CallDefaultOptions[K comparable, V any] interface {
	// OptCallDefaultGetOptions sets the default options to be appended to all [Cache.Get] calls.
	OptCallDefaultGetOptions(options ...GetOption)
	// OptCallDefaultSetOptions sets the default options to be appended to all [Cache.Set] calls.
	OptCallDefaultSetOptions(options ...SetOption)
	// OptCallDefaultDeleteOptions sets the default options to be appended to all [Cache.Delete] calls.
	OptCallDefaultDeleteOptions(options ...DeleteOption)
}

type CallDefaultRefreshOptions

type CallDefaultRefreshOptions[K comparable, V any] interface {
	// OptCallDefaultRefreshOptions sets the default options to be appended to all [RefreshCache.GetOrRefresh] calls.
	OptCallDefaultRefreshOptions(options ...RefreshOption)
}

type Codec

type Codec[V any] interface {
	Encode(ctx context.Context, data V) (any, error)
	Decode(ctx context.Context, data any) (V, error)
}

Codec is a codec to convert a cache value the requested type.

type CodecError

type CodecError struct {
	Err error
}

CodecError represents an error from a Codec or a KeyCodec.

func (CodecError) Error

func (e CodecError) Error() string

func (CodecError) Unwrap

func (e CodecError) Unwrap() error

type DefaultRefreshOptions

type DefaultRefreshOptions[K comparable, V any] interface {
	// OptDefaultRefreshFunc sets the default refresh function to be used for [RefreshCache.GetOrRefresh].
	OptDefaultRefreshFunc(refreshFunc CacheRefreshFunc[K, V])
}

type DeleteOption

type DeleteOption = IOption[IDeleteOpt]

func DeleteOptionFunc

func DeleteOptionFunc(f func(any) bool, name string, hash uint64) DeleteOption

type DeleteOptions

type DeleteOptions[K comparable, V any] interface {
}

type GetOption

type GetOption = IOption[IGetOpt]

func GetOptionFunc

func GetOptionFunc(f func(any) bool, name string, hash uint64) GetOption

type GetOptions

type GetOptions[K comparable, V any] interface {
}

type IDeleteOpt

type IDeleteOpt int

type IGetOpt

type IGetOpt int

type IIsOption

type IIsOption[T any] struct {
}

IIsOption is an implementation of IOption, meant to be embedded in structs.

type IOption

type IOption[T any] interface {
	Option
	// contains filtered or unexported methods
}

IOption is used to segregate option types, not allowing different types to be mixed. The combination of a "isCacheOption" function and a single parameter of a type marker makes interfaces compatible only between the same marker type.

func ConcatOptionsChecker

func ConcatOptionsChecker[O IOption[TO], TO any](checker OptionChecker[O, TO], options ...[]IOption[TO]) []IOption[TO]

ConcatOptionsChecker concatenates multiple option lists and prepends an OptionChecker to it.

func ForwardOptionsChecker

func ForwardOptionsChecker[O IOption[TO], TO any](checker OptionChecker[O, TO]) []IOption[TO]

ForwardOptionsChecker returns the list of options from checker prepended by the checker itself.

type IRefreshOpt

type IRefreshOpt int

type IRootOpt

type IRootOpt int

type ISetOpt

type ISetOpt int

type InvalidValueTypeError

type InvalidValueTypeError struct {
	Message string
}

InvalidValueTypeError represents an invalid value type error.

func (*InvalidValueTypeError) Error

func (e *InvalidValueTypeError) Error() string

type IsDeleteOption

type IsDeleteOption = IIsOption[IDeleteOpt]

type IsGetOption

type IsGetOption = IIsOption[IGetOpt]

type IsRefreshOption

type IsRefreshOption = IIsOption[IRefreshOpt]

type IsRootOption

type IsRootOption = IIsOption[IRootOpt]

type IsSetOption

type IsSetOption = IIsOption[ISetOpt]

type KeyCodec

type KeyCodec[K comparable] interface {
	Convert(ctx context.Context, key K) (any, error)
}

KeyCodec is a codec to convert a cache key to a format supported by the cache.

type Metrics

type Metrics interface {
	Hit(ctx context.Context, name string, key any)
	Miss(ctx context.Context, name string, key any)
	Error(ctx context.Context, name string, key any, errorType MetricsErrorType)
}

type MetricsErrorType

type MetricsErrorType int
const (
	MetricsErrorTypeError MetricsErrorType = iota
	MetricsErrorTypeGet
	MetricsErrorTypeSet
	MetricsErrorTypeDecode
	MetricsErrorTypeEncode
	MetricsErrorTypeRefresh
)

type MetricsOptions

type MetricsOptions[K comparable, V any] interface {
	// OptMetrics sets the [Metrics] instance to call for metrics.
	OptMetrics(metrics Metrics, name string)
}

type NameOptions

type NameOptions[K comparable, V any] interface {
	// OptName sets the cache name.
	OptName(name string)
}

type Option

type Option interface {
	ApplyCacheOpt(any) bool
	CacheOptName() string
	CacheOptHash() uint64
}

Option is the base interface for all options.

type OptionChecker

type OptionChecker[O IOption[TO], TO any] interface {
	IOption[TO]
	CheckCacheOpt(opt Option)
	CheckCacheError() error
	CheckCacheOptList() []IOption[TO]
}

OptionChecker is a special option type that is used to postpone checking the usage of options, to account for when the same options are used in multiple calls and we want to postpone the checking of valid options only at the end.

func NewOptionChecker

func NewOptionChecker[OA ~[]IOption[TO], TO any](options ...OA) OptionChecker[IOption[TO], TO]

NewOptionChecker creates a new OptionChecker concatenating the list of options to check into it.

type OptionNotSupportedError

type OptionNotSupportedError struct {
	Message string
	Option  Option
}

OptionNotSupportedError represents that an options is not supported by the implementation.

func NewOptionNotSupportedError

func NewOptionNotSupportedError(option Option) OptionNotSupportedError

func (OptionNotSupportedError) Error

func (e OptionNotSupportedError) Error() string

type Options

type Options[K comparable, V any] interface {
}

type ParseOptionsResult

type ParseOptionsResult struct {
	// contains filtered or unexported fields
}

ParseOptionsResult is the result of ParseOptions

func ParseOptions

func ParseOptions[OA ~[]IOption[TO], TO any](obj any, options ...OA) ParseOptionsResult

ParseOptions parses and applies a list of options, in order of appearance, and returns an error if any of the parameters was not accepted. If options of OptionChecker type exist in the list, the error is reported to them instead of being returned to the caller. See OptionChecker for details.

func ParseOptionsChecker

func ParseOptionsChecker[O IOption[TO], TO any](checker OptionChecker[O, TO], obj any) ParseOptionsResult

ParseOptionsChecker parses the options using the passed OptionChecker to report usage.

func (ParseOptionsResult) Err

func (r ParseOptionsResult) Err() error

Err returns the options parsing error, if any.

func (ParseOptionsResult) SelfErr

func (r ParseOptionsResult) SelfErr() error

SelfErr returns the options parsing error, if any, even if it was only sent to an OptionChecker.

type RefreshCache

type RefreshCache[K comparable, V any] interface {
	Cache[K, V]

	// GetOrRefresh tries to get the value for the key on the cache, calling a refresh function if not found,
	// and then storing the newly loaded value to cache before returning it.
	GetOrRefresh(ctx context.Context, key K, options ...RefreshOption) (V, error)
}

RefreshCache is the base type for cache implementations that allows refreshing on get, using the "GetOrRefresh" method.

type RefreshFuncOptions

type RefreshFuncOptions struct {
	// Data is the custom data sent with [WithRefreshData].
	Data any
}

RefreshFuncOptions is the options sent to the refresh function.

type RefreshOption

type RefreshOption = IOption[IRefreshOpt]

func RefreshOptionFunc

func RefreshOptionFunc(f func(any) bool, name string, hash uint64) RefreshOption

func WithRefreshData

func WithRefreshData[K comparable, V any](data interface{}) RefreshOption

WithRefreshData sets a custom data to be sent to the refresh function.

func WithRefreshFunc

func WithRefreshFunc[K comparable, V any](refreshFunc CacheRefreshFunc[K, V]) RefreshOption

WithRefreshFunc sets the refresh function for this call, possibly overriding a default one.

func WithRefreshGetOptions

func WithRefreshGetOptions[K comparable, V any](options ...GetOption) RefreshOption

WithRefreshGetOptions sets the options to be appended to all [Cache.Get] calls inside the refresh function.

func WithRefreshSetOptions

func WithRefreshSetOptions[K comparable, V any](options ...SetOption) RefreshOption

WithRefreshSetOptions sets the options to be appended to all [Cache.Set] calls inside the refresh function.

type RefreshOptions

type RefreshOptions[K comparable, V any] interface {
	// OptData sets a custom data to be sent to the refresh function.
	OptData(data any)
	// OptFunc sets the refresh function for this call, possibly overriding a default one.
	OptFunc(refreshFunc CacheRefreshFunc[K, V])
	// OptGetOptions sets the options to be appended to all [Cache.Get] calls inside the refresh function.
	OptGetOptions(options ...GetOption)
	// OptSetOptions sets the options to be appended to all [Cache.Set] calls inside the refresh function.
	OptSetOptions(options ...SetOption)
}

type RootOption

type RootOption = IOption[IRootOpt]

func RootOptionFunc

func RootOptionFunc(f func(any) bool, name string, hash uint64) RootOption

func WithCallDefaultDeleteOptions

func WithCallDefaultDeleteOptions[K comparable, V any](options ...DeleteOption) RootOption

WithCallDefaultDeleteOptions sets the default options to be appended to all [Cache.Delete] calls.

func WithCallDefaultGetOptions

func WithCallDefaultGetOptions[K comparable, V any](options ...GetOption) RootOption

WithCallDefaultGetOptions sets the default options to be appended to all [Cache.Get] calls.

func WithCallDefaultRefreshOptions

func WithCallDefaultRefreshOptions[K comparable, V any](options ...RefreshOption) RootOption

WithCallDefaultRefreshOptions sets the default options to be appended to all [RefreshCache.GetOrRefresh] calls.

func WithCallDefaultSetOptions

func WithCallDefaultSetOptions[K comparable, V any](options ...SetOption) RootOption

WithCallDefaultSetOptions sets the default options to be appended to all [Cache.Set] calls.

func WithDefaultRefreshFunc

func WithDefaultRefreshFunc[K comparable, V any](refreshFunc CacheRefreshFunc[K, V]) RootOption

WithDefaultRefreshFunc sets the default refresh function to be used for [RefreshCache.GetOrRefresh].

func WithMetrics

func WithMetrics[K comparable, V any](metrics Metrics, name string) RootOption

WithMetrics sets the Metrics instance to call for metrics.

func WithName

func WithName[K comparable, V any](name string) RootOption

WithName sets the cache name.

type SetOption

type SetOption = IOption[ISetOpt]

func SetOptionFunc

func SetOptionFunc(f func(any) bool, name string, hash uint64) SetOption

func WithSetDuration

func WithSetDuration[K comparable, V any](duration time.Duration) SetOption

WithSetDuration sets the cache duration (TTL) to be used for this set call instead of the default.

type SetOptions

type SetOptions[K comparable, V any] interface {
	// OptDuration sets the cache duration (TTL) to be used for this set call instead of the default.
	OptDuration(duration time.Duration)
}

type ValidationError

type ValidationError struct {
	Err error
}

ValidationError represents an error from a Validator.

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) Unwrap

func (e ValidationError) Unwrap() error

type Validator

type Validator[V any] interface {
	ValidateGet(ctx context.Context, data V) error
}

Validator allows validating data retrieved from the cache, allowing to check for a previous format for example.

Directories

Path Synopsis
cache
bigcache Module
chain Module
freecache Module
gocache Module
map Module
ristretto Module
ttlcache Module
cmd
troptgen Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL