stalecache

package module
Version: v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2023 License: BSD-3-Clause Imports: 4 Imported by: 0

README

PkgGoDev Go Report Card

StaleCache

A Go library provides a cache with optional TTL.

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 New

func New[T any](loader Loader[T], options ...Option[T]) *Cache[T]

New creates a new Cache with loader and options.

func (*Cache[T]) Load

func (c *Cache[T]) Load(ctx context.Context) (*T, error)

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.

func (*Cache[T]) Update added in v0.2.0

func (c *Cache[T]) Update(data *T)

Update updates the cache with data and current timestamp.

type Loader

type Loader[T any] func(context.Context) (*T, error)

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

func WithTTL[T any](ttl time.Duration) Option[T]

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.

Jump to

Keyboard shortcuts

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