gas/cache
cache/memory
import "github.com/gasmod/gas/cache/memory"Package memory is a cache held in the process’s memory, as a gas.CacheProvider. It is local to one process and lost when the process stops, so it suits development, tests and single-instance apps.
Service implements gas.Service and gas.CacheProvider, and keeps the contract of the cache package.
In an app, the container builds the store from New and calls its Init. By hand, with a configuration given in code:
cfg := memory.DefaultConfig()cfg.Cache.MaxEntries = 10000
c, err := memory.New(memory.WithConfig(cfg))(nil, logger)if err != nil { return err}if err := c.Init(ctx); err != nil { return err}defer c.Close(ctx)
err = c.Set(ctx, "greeting", []byte("hello"), time.Minute)After this c.Get(ctx, “greeting”) returns hello for a minute, and
c.Len() is 1.
Configuration
Section titled “Configuration”The settings live in the cache section, in Settings:
cache.maxentries: the most entries the store holds, 0 or more; 0 is no limit. Default: DefaultMaxEntries, no limit.cache.cleanupinterval: how often the janitor removes expired entries, at least MinCleanupInterval (1s). Default: DefaultCleanupInterval (1m).cache.defaultttl: the TTL of a Set with a zero TTL, 0 or more; 0 is no expiry. Default: DefaultTTL, no expiry.
With the defaults the store has no limit: entries without a TTL stay until deleted, and the store grows with the keys it is given. Set MaxEntries, DefaultTTL, or both, for keys that come from requests.
Service.Init resolves the configuration each time it runs, in one of two ways:
- Without WithConfig, it binds DefaultConfig from the
gas.ConfigProvider, which checks the
validatetags. A nil ConfigProvider is the error cache.ErrNoConfigProvider. - With WithConfig, it takes a copy of the given Config, never changing the caller’s struct, and checks the same tags. A nil Config is the error cache.ErrNilConfig.
A failure wraps cache.ErrInvalidConfig. The resolved configuration belongs to the entries Init opens, so a restart with another configuration is safe while calls run.
Service.Config returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was.
Eviction
Section titled “Eviction”The store keeps its entries in order of use. Get and Set make an entry the most recently used; Exists and Delete do not.
When MaxEntries is set and a Set adds a new key to a full store, the store first removes one entry:
- the one that expired first, if any has expired;
- else the least recently used.
Replacing a key’s value never evicts. A full store never refuses a Set.
Expiry
Section titled “Expiry”A TTL is counted from the Set, on the monotonic clock, so a change of the wall clock does not move it. Expired entries are removed in two ways:
- Get and Exists treat an expired entry as a miss and remove it.
- The janitor, a goroutine that each Init starts, removes every
expired entry each
cleanupinterval, holding the store’s lock while it does.
An expired entry that nothing reads is held until the next sweep, or until eviction picks it, as under Eviction. Service.Len counts it until then.
Lifecycle
Section titled “Lifecycle”A successful Init opens an empty store, starts the janitor and logs
service initialized at info level, with max_entries,
cleanup_interval and default_ttl. Init on an initialized store
returns cache.ErrAlreadyInitialized and changes nothing.
Service.Close runs these steps, in order:
- It drops every entry.
- It stops the janitor, and waits for it to return.
- It logs
service closedat info level.
Close on a store that is not initialized returns nil and logs nothing. Close ignores its context. Init after Close starts again with an empty store and a configuration resolved afresh.
Outside a successful Init, every method but Init, Close, Name, Len and Config returns an error wrapping:
- cache.ErrNotInitialized, before the first successful Init.
- cache.ErrClosed, after Close, until Init succeeds.
Len returns 0 then.
New’s constructor fails with cache.ErrNilLogger for a nil logger. A nil ConfigProvider is accepted, and Init then requires WithConfig.
Context
Section titled “Context”The store does no I/O, so a call never waits: each method returns the context’s error when the context has ended before the call, and runs to the end otherwise.
Concurrency
Section titled “Concurrency”A Service is safe for concurrent use. One mutex guards the entries and the state:
- Each call holds it for the whole call, which is short and does no I/O.
- The janitor holds it for each sweep.
- Close releases it before waiting for the janitor.
A call that runs beside Close either completes before it or returns cache.ErrClosed.
Errors
Section titled “Errors”Every error starts with ServiceName and the operation, and wraps a sentinel of the cache package, as the cache package describes.
A configuration that fails its tags gets the validator’s error after
gas/cache/memory: init: invalid config: validate config: , such as:
Key: 'Config.Cache.CleanupInterval' Error:Field validation for 'CleanupInterval' failed on the 'min' tagThe other errors, as returned, with get standing for each operation
that can fail the same way:
gas/cache/memory: logger is nilgas/cache/memory: init: config is nilgas/cache/memory: init: no config providergas/cache/memory: init: service already initializedgas/cache/memory: init: context canceledgas/cache/memory: get: invalid key: emptygas/cache/memory: get: key not foundgas/cache/memory: get: service not initializedgas/cache/memory: get: service closedgas/cache/memory: get: context canceledgas/cache/memory: set: invalid TTL: negativeAPI reference
Section titled “API reference”Constants
Section titled “Constants”const ( // DefaultMaxEntries is the entry limit of DefaultConfig: none. DefaultMaxEntries = 0 // DefaultCleanupInterval is the janitor's interval of DefaultConfig. DefaultCleanupInterval = time.Minute // DefaultTTL is the TTL of DefaultConfig for a Set with a zero TTL: // no expiry. DefaultTTL time.Duration = 0 // MinCleanupInterval is the shortest CleanupInterval. MinCleanupInterval = time.Second)const ServiceName = "gas/cache/memory"ServiceName is the name of the memory store, returned by Service.Name and prefixed to every error the store returns.
func New
Section titled “func New”func New(opts ...Option) func(gas.ConfigProvider, gas.Logger) (*Service, error)New returns the constructor of a Service with opts applied, in the shape the gas container expects. The constructor returns an error wrapping cache.ErrNilLogger for a nil logger; a nil ConfigProvider is accepted, and Init then requires WithConfig.
type Config
Section titled “type Config”type Config struct { // Cache holds the settings. Cache Settings}Config holds the memory store’s configuration, read from the cache
section.
func DefaultConfig
Section titled “func DefaultConfig”func DefaultConfig() *ConfigDefaultConfig returns the configuration a store starts from before binding: DefaultMaxEntries, DefaultCleanupInterval and DefaultTTL.
type Option
Section titled “type Option”type Option func(*Service)Option configures a Service. Options only record what they are given; Init checks it.
func WithConfig
Section titled “func WithConfig”func WithConfig(cfg *Config) OptionWithConfig makes Init use a copy of cfg instead of binding the configuration from the ConfigProvider. Init copies *cfg each time it runs and never changes it; the copy is checked against its validate tags as a bound configuration is. A nil cfg makes Init fail with cache.ErrNilConfig.
Default: bind the cache section from the ConfigProvider over
DefaultConfig.
type Service
Section titled “type Service”type Service struct { // contains filtered or unexported fields}Service is a cache held in the process’s memory, as described in the package documentation. It is safe for concurrent use.
func (*Service) Close
Section titled “func (*Service) Close”func (s *Service) Close(context.Context) errorClose drops every entry, stops the janitor and waits for it to return. Every later call but Init returns an error wrapping cache.ErrClosed. Close on a store that is not initialized returns nil and logs nothing. It ignores its context.
func (*Service) Config
Section titled “func (*Service) Config”func (s *Service) Config() ConfigConfig returns a copy of the configuration the last successful Init resolved, defaults included, or the zero Config before one. A failed Init and Close leave it as it was. Config holds no slice, map or pointer, so the copy shares nothing with the store.
func (*Service) Delete
Section titled “func (*Service) Delete”func (s *Service) Delete(ctx context.Context, key string) errorDelete removes the value of key. Deleting a key the store does not hold is not an error.
func (*Service) Exists
Section titled “func (*Service) Exists”func (s *Service) Exists(ctx context.Context, key string) (bool, error)Exists reports whether the store holds a live value under key. It does not make the entry the most recently used.
func (*Service) Get
Section titled “func (*Service) Get”func (s *Service) Get(ctx context.Context, key string) ([]byte, error)Get returns a copy of the value of key, or an error wrapping cache.ErrKeyNotFound when the store holds no live value under it. A hit makes the entry the most recently used.
func (*Service) Init
Section titled “func (*Service) Init”func (s *Service) Init(ctx context.Context) errorInit resolves the configuration, opens an empty cache and starts the janitor, as described in the package documentation. On an initialized store it returns cache.ErrAlreadyInitialized and changes nothing.
func (*Service) Len
Section titled “func (*Service) Len”func (s *Service) Len() intLen returns the number of entries the store holds, counting those that have expired and that neither a call nor the janitor has removed yet. It is 0 when the store is not initialized.
func (*Service) Name
Section titled “func (*Service) Name”func (*Service) Name() stringName returns ServiceName.
func (*Service) Set
Section titled “func (*Service) Set”func (s *Service) Set(ctx context.Context, key string, value []byte, ttl time.Duration) errorSet stores a copy of value under key, as the most recently used entry, expiring as ttl says, as described in the package documentation. A nil value is stored as empty. A new key on a full store evicts one entry first.
type Settings
Section titled “type Settings”type Settings struct { // MaxEntries is the most entries the store holds; 0 is no limit. MaxEntries int `validate:"min=0"` // CleanupInterval is how often the janitor removes expired entries, // at least MinCleanupInterval. CleanupInterval time.Duration `validate:"min=1s"` // DefaultTTL is the TTL of a Set with a zero TTL; 0 is no expiry. DefaultTTL time.Duration `validate:"min=0"`}Settings are the memory store’s settings, as described in the package documentation.