granular

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2025 License: GPL-3.0 Imports: 15 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

granular: A High-Performance Incremental File Cache

Go Reference Go Report Card

granular is a lightweight, high-performance file caching library for Go applications that provides deterministic, content-based caching.

Features

  • Content-Addressed Storage: Uses fast hashing (xxHash by default) to create 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

Installation

go get github.com/gophersatwork/granular

Quick Start

package main

import (
    "errors"
    "fmt"
    "log"

    "github.com/gophersatwork/granular" // Import the repository
)

func main() {
    // Create a new cache
    cache, err := granular.New(".cache") // Use the granular package name
    if err != nil {
        log.Fatalf("Failed to create cache: %v", err)
    }

    // Define 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"},
    }

    // Check if the result is in the cache
    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: "output.txt",
            Metadata: map[string]string{
                "summary": "This is a summary",
            },
        }
        
        if err := cache.Store(key, result); err != nil {
            log.Fatalf("Failed to store in cache: %v", err)
        }
        
        fmt.Println("Result stored in cache")
    }
}

Input Types

The library 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

The cache can be configured with various options:

cache, err := granular.New(
    ".cache",
    granular.WithHashFunc(myCustomHashFunc),
)

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.
  • 2-level directory: Uses first 2 characters of hash for better filesystem distribution.

File Structure

.cache/
├── manifests/
│   └── [first 2 chars of hash]/
│       └── [full hash].json
└── objects/
    └── [first 2 chars of hash]/
        └── [full hash]/
            └── [cached files]

Examples

Check it out more ways to use granular here.

Contributing

Contributions are welcome! Feel free to open a discussion. An easy onboarding for a new contributor can be found here

License

This project is licensed under the GPL License - see the LICENSE file for details.

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

Constants

This section is empty.

Variables

View Source
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

func New(root string, options ...Option) (*Cache, error)

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) Clear

func (c *Cache) Clear() error

Clear removes all entries from the cache.

func (*Cache) Get

func (c *Cache) Get(key Key) (*Result, bool, error)

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

func (c *Cache) GetData(key Key, dataKey string) ([]byte, bool, error)

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

func (c *Cache) GetFile(key Key, filename string) (string, bool, error)

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.

func (*Cache) Remove

func (c *Cache) Remove(keyHash string) error

Remove removes a specific entry from the cache.

func (*Cache) Store

func (c *Cache) Store(key Key, result Result) error

Store stores a result in the cache for the given key.

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

type FileInput struct {
	Path     string // Path to the file
	afero.Fs        // The filesystem to use
}

FileInput represents a single file input for the cache.

func (FileInput) Hash

func (f FileInput) Hash(h hash.Hash) error

Hash implements the Input interface for FileInput.

func (FileInput) String

func (f FileInput) String() string

String implements the Input interface for FileInput.

type GlobInput

type GlobInput struct {
	Pattern string   // Glob pattern
	Fs      afero.Fs // The filesystem to use
}

GlobInput represents a glob pattern input for the cache.

func (GlobInput) Hash

func (g GlobInput) Hash(h hash.Hash) error

Hash implements the Input interface for GlobInput. It finds all files matching the pattern, sorts them for determinism.

func (GlobInput) String

func (g GlobInput) String() string

String implements the Input interface for GlobInput.

type HashFunc

type HashFunc func() hash.Hash

HashFunc defines a function that creates a new hash.Hash instance.

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 NowFunc

type NowFunc func() time.Time

NowFunc defines a function that return the time now.

type Option

type Option func(*Cache)

Option defines a function that configures a Cache.

func WithFs

func WithFs(fs afero.Fs) Option

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

func WithHashFunc(hashFunc HashFunc) Option

WithHashFunc sets the hash function for the cache.

func WithNowFunc

func WithNowFunc(nowFunc NowFunc) Option

WithNowFunc sets the Now() function for the cache.

type RawInput

type RawInput struct {
	Data []byte // Raw data
	Name string // Optional name for the input
}

RawInput represents a raw data input for the cache.

func (RawInput) Hash

func (r RawInput) Hash(h hash.Hash) error

Hash implements the Input interface for RawInput.

func (RawInput) String

func (r RawInput) String() string

String implements the Input interface for RawInput.

type Result

type Result struct {
	// Path contains the path to the cached file.
	Path string

	// Metadata contains additional information about the cached result.
	Metadata map[string]string
}

Result represents the result of a cache operation.

Jump to

Keyboard shortcuts

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