Documentation
¶
Overview ¶
Package granular provides a high-performance incremental file cache library for Go applications.
It offers deterministic, content-based caching optimized for local filesystem operations.
Overview ¶
granular is a lightweight, high-performance file caching library that provides deterministic, content-based caching. It is inspired by Zig's build cache architecture and optimized for local filesystem operations without distributed system complexity.
Core Architecture ¶
granular uses a two-level structure for its cache:
- manifests/ - Metadata about cached computations
- objects/ - Actual cached artifacts
The cache uses content-addressed storage with fast hashing (xxHash by default) to create deterministic cache keys, and a manifest system with JSON files tracking inputs, outputs, and metadata.
Key Features ¶
- Content-Addressed Storage: Uses fast hashing (xxHash by default) for deterministic cache keys
- Manifest System: JSON files tracking inputs, outputs, and metadata
- Flexible Inputs: Support for files, directories, glob patterns, and raw data
- Memory Efficient: Buffer pooling and lazy evaluation
- Concurrent Access: Thread-safe operations with proper locking
Basic Usage ¶
Creating a cache:
cache, err := granular.New(".cache")
if err != nil {
log.Fatalf("Failed to create cache: %v", err)
}
Defining a cache key:
key := granular.Key{
Inputs: []granular.Input{
granular.FileInput{Path: "main.go"},
granular.GlobInput{Pattern: "*.json"},
},
Extra: map[string]string{"version": "1.0.0"},
}
Checking for a cache hit:
result, hit, err := cache.Get(key)
if err != nil && !errors.Is(err, granular.ErrCacheMiss) {
log.Fatalf("Cache error: %v", err)
}
if hit {
fmt.Println("Cache hit!")
// Use cached result
fmt.Printf("Cached file: %s\n", result.Path)
} else {
fmt.Println("Cache miss, computing result...")
// Perform your computation here
// ...
// Store the result in the cache
result := granular.Result{
Path: outputFile,
Metadata: map[string]string{
"summary": "Computation complete",
},
}
err = cache.Store(key, result)
if err != nil {
log.Fatalf("Failed to store in cache: %v", err)
}
}
Input Types ¶
granular supports several input types:
FileInput - Single file input:
input := granular.FileInput{Path: "path/to/file.txt"}
GlobInput - Multiple files matching a pattern:
input := granular.GlobInput{Pattern: "src/*.go"}
DirectoryInput - All files in a directory (recursive):
input := granular.DirectoryInput{
Path: "src/",
Exclude: []string{"*.tmp", "*.log"},
}
RawInput - Raw data:
input := granular.RawInput{
Data: []byte("raw data"),
Name: "config",
}
Configuration Options ¶
granular can be configured with various options:
cache, err := granular.New(
".cache",
granular.WithHashFunc(myCustomHashFunc),
granular.WithFs(myCustomFs),
)
Performance Considerations ¶
- Hash Function: xxHash is used by default for its speed, but you can provide a custom hash function
- Buffer Pooling: Reuses buffers to reduce memory allocations
File Structure ¶
The cache uses the following directory structure:
.cache/
├── manifests/
│ └── [first 2 chars of hash]/
│ └── [full hash].json
└── objects/
└── [first 2 chars of hash]/
└── [full hash]/
└── [cached files]
Error Handling ¶
The package defines several error types:
- ErrCacheMiss: Returned when a cache key is not found
- ErrInvalidKey: Returned when a key is invalid
Always check for these errors when using the cache:
result, hit, err := cache.Get(key)
if err != nil {
if errors.Is(err, granular.ErrCacheMiss) {
// Handle cache miss
} else {
// Handle other errors
}
}
Index ¶
- Variables
- type Cache
- func (c *Cache) Clear() error
- func (c *Cache) Get(key Key) (*Result, bool, error)
- func (c *Cache) GetData(key Key, dataKey string) ([]byte, bool, error)
- func (c *Cache) GetFile(key Key, filename string) (string, bool, error)
- func (c *Cache) Remove(keyHash string) error
- func (c *Cache) Store(key Key, result Result) error
- type DirectoryInput
- type FileInput
- type GlobInput
- type HashFunc
- type Input
- type Key
- type Manifest
- type NowFunc
- type Option
- type RawInput
- type Result
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCacheMiss is returned when a cache key is not found. ErrCacheMiss = errors.New("cache miss") // ErrInvalidKey is returned when a key is invalid. ErrInvalidKey = errors.New("invalid key") )
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache represents the main cache structure. It manages the storage and retrieval of cached artifacts.
func New ¶
New creates a new cache instance with the given root directory. It uses the default hash function (xxHash) if none is provided. It uses the OS filesystem by default, but this can be overridden with WithFs.
func (*Cache) Get ¶
Get retrieves a cached result for the given key. It returns the result, a boolean indicating whether the key was found, and an error if one occurred.
func (*Cache) GetData ¶
GetData retrieves cached data for the given key and data key. It returns the data, a boolean indicating whether the key was found, and an error if one occurred.
func (*Cache) GetFile ¶
GetFile retrieves a cached file for the given key and filename. It returns the path to the file, a boolean indicating whether the key was found, and an error if one occurred.
type DirectoryInput ¶
type DirectoryInput struct {
Path string // Path to the directory
Exclude []string // Patterns to exclude
Fs afero.Fs // The filesystem to use
}
DirectoryInput represents a directory input for the cache.
func (DirectoryInput) Hash ¶
func (d DirectoryInput) Hash(h hash.Hash) error
Hash implements the Input interface for DirectoryInput.
func (DirectoryInput) String ¶
func (d DirectoryInput) String() string
String implements the Input interface for DirectoryInput.
type FileInput ¶
FileInput represents a single file input for the cache.
type GlobInput ¶
GlobInput represents a glob pattern input for the cache.
type Input ¶
type Input interface {
// Hash writes the input's content to the hash.
Hash(h hash.Hash) error
// String returns a string representation of the input.
String() string
}
Input defines the interface for cache inputs. Inputs are used to calculate the cache key.
type Key ¶
type Key struct {
Inputs []Input // Files, globs, raw data
Extra map[string]string // Additional cache key components
}
Key represents a cache key composed of inputs and extra metadata.
type Manifest ¶
type Manifest struct {
// Key information
KeyHash string `json:"keyHash"` // Hash of the key
InputDescs []string `json:"inputs"` // String descriptions of inputs
ExtraData map[string]string `json:"extra"` // Extra key components
// Result information
OutputFiles []string `json:"outputs"` // Paths to output files
OutputData map[string][]byte `json:"-"` // Raw output data
OutputMeta map[string]string `json:"outputMeta"` // String metadata (stored in JSON)
OutputHash string `json:"outputHash"` // Hash of outputs
// Metadata
CreatedAt time.Time `json:"createdAt"` // When the cache entry was created
AccessedAt time.Time `json:"accessedAt"` // When the cache entry was last accessed
Description string `json:"description"` // Optional description
}
Manifest represents a cache manifest file. It contains metadata about a cached computation.
type Option ¶
type Option func(*Cache)
Option defines a function that configures a Cache.
func WithFs ¶
WithFs sets the filesystem implementation for the cache. This allows using different filesystem implementations like in-memory filesystems for testing or remote filesystems.
func WithHashFunc ¶
WithHashFunc sets the hash function for the cache.
func WithNowFunc ¶
WithNowFunc sets the Now() function for the cache.