cache package - github.com/anchore/go-cache - Go Packages

cache

package module
v0.0.0-...-ec2e76f Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

README

go-cache

A basic caching library.

This library provides the interfaces used for persistent caching by the Anchore Go CLI tools, including Syft and Grype.

Each application should provide means for configuring a cache.Manager and individual caches should be obtained from the cache.Manager.

Usage

To cache specific Go data types, the easiest method is using a cache.Resolver with the with automatic type version based on a cache.HashType call, which automatically creates a unique version qualifier based on the structure of the provided type. This way, if the structure changes in any way it will end up with a new version key which will invalidate older cache entries and result in populating the cache based on this new key. The cache.Resolver will store items using the json package to serialize/deserialize values, so to save space it is encouraged to use omitempty. For example:

type myCacheItem struct {
	Name string `json:"name",omitempty`
}

If it is common that checking for an item will result in errors, and you do not want to re-run the resolve function when errors are encountered, instead of using GetResolver, you can use GetResolverCachingErrors, which is useful for things such as resolving artifacts over a network, where a number of them will not be resolved, and you do not want to continue to have the expense of running the network resolution. This should be used when it is acceptable a network outage and cached errors is an acceptable risk.

An example can be seen in the Syft golang cataloger fetching remote licenses.

Example

package appcache

import "github.com/anchore/go-cache"

// default to a bypassed cache, so unit tests are easy to deal with
var manager = cache.NewBypassed()

// set the cache after any necessary configuration
func InitCache(dir string, ttl time.Duration) {
	manager = cache.NewFromDir(globalLogger, dir, ttl)
}

// utility function with an app-scoped global cache
func NewResolver[T any](name string) cache.Resolver[T] {
	return cache.NewResolver[T](manager.GetCache(name, cache.HashType[T]()))
}
package app

import "appcache"

type myDataType struct {
	Value string `json:"value,omitempty"`
}

var cacheResolver = appcache.NewResolver[myDataType]("my-top-level-cache-name")

func functionWhichCaches(someParam string) myDataType {
	return cacheResolver.Resolve(someParam, func() myDataType {
		// do some work and return 
		return myDataType{ ... }
    })
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HashType

func HashType[T any]() string

HashType returns a stable hash based on the structure of the type

Types

type Cache

type Cache interface {
	// Read returns a reader for the cache value, if found and not expired
	// or errors when unable to find / expired
	Read(key string) (ReaderAtCloser, error)

	// Write writes the contents of the reader to the cache
	// and closes it, if the reader implements io.Closer
	Write(key string, contents io.Reader) error
}

Cache is what the application interacts with to get and set cached data

type Manager

type Manager interface {
	// GetCache returns a cache scoped to the given named, versioned data
	GetCache(name, version string) Cache

	// RootDirs returns any root directories this cache manager uses
	RootDirs() []string
}

Manager is responsible for managing cache data and instantiating all caches

func NewBypassed

func NewBypassed() Manager

func NewFromDir

func NewFromDir(log logger.Logger, dir string, ttl time.Duration) (Manager, error)

NewFromDir creates a new cache manager which returns caches stored on disk, rooted at the given directory

func NewInMemory

func NewInMemory(ttl time.Duration) Manager

NewInMemory returns an in-memory only cache manager

type ReaderAtCloser

type ReaderAtCloser interface {
	io.Reader
	io.ReaderAt
	io.Closer
}

ReaderAtCloser is an amalgamation of: io.Reader, io.ReaderAt, and io.Closer

type Resolver

type Resolver[T any] interface {
	// Resolve attempts to resolve the given key from cache and convert it to the type of the cache,
	// or calls the resolver function if unable to resolve a cached value
	Resolve(key string, resolver resolverFunc[T]) (T, error)
}

Resolver interface provides a single Resolve method, which will return from cache or call the provided resolve function to get the value if not available in cache

func NewResolver

func NewResolver[T any](cache Cache) Resolver[T]

NewResolver returns a cache resolver for persistent cached data across Syft runs, stored in a unique location based on the provided name and versioned by the type

func NewResolverCachingErrors

func NewResolverCachingErrors[T any](cache Cache) Resolver[T]

NewResolverCachingErrors returns a Resolver that caches errors and will return them instead of continuing to call the provided resolve functions

Jump to

Keyboard shortcuts

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