cache

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2025 License: MIT Imports: 8 Imported by: 1

README

Cache Module

The Cache Module provides caching functionality for Modular applications. It offers different cache backend options including in-memory and Redis (placeholder implementation).

Features

  • Multiple cache engine options (memory, Redis)
  • Support for time-to-live (TTL) expirations
  • Automatic cache cleanup for expired items
  • Basic cache operations (get, set, delete)
  • Bulk operations (getMulti, setMulti, deleteMulti)

Installation

import (
    "github.com/GoCodeAlone/modular"
    "github.com/GoCodeAlone/modular/modules/cache"
)

// Register the cache module with your Modular application
app.RegisterModule(cache.NewModule())

Configuration

The cache module can be configured using the following options:

cache:
  engine: memory            # Cache engine to use: "memory" or "redis"
  defaultTTL: 300           # Default TTL in seconds if not specified (300s = 5 minutes)
  cleanupInterval: 60       # How often to clean up expired items (60s = 1 minute)
  maxItems: 10000           # Maximum items to store in memory cache
  redisURL: ""              # Redis connection URL (for Redis engine)
  redisPassword: ""         # Redis password (for Redis engine)
  redisDB: 0                # Redis database number (for Redis engine)
  connectionMaxAge: 60      # Maximum age of connections in seconds

Usage

Accessing the Cache Service
// In your module's Init function
func (m *MyModule) Init(app modular.Application) error {
    var cacheService *cache.CacheModule
    err := app.GetService("cache.provider", &cacheService)
    if err != nil {
        return fmt.Errorf("failed to get cache service: %w", err)
    }
    
    // Now you can use the cache service
    m.cache = cacheService
    return nil
}
Using Interface-Based Service Matching
// Define the service dependency
func (m *MyModule) RequiresServices() []modular.ServiceDependency {
    return []modular.ServiceDependency{
        {
            Name:               "cache",
            Required:           true,
            MatchByInterface:   true,
            SatisfiesInterface: reflect.TypeOf((*cache.CacheEngine)(nil)).Elem(),
        },
    }
}

// Access the service in your constructor
func (m *MyModule) Constructor() modular.ModuleConstructor {
    return func(app modular.Application, services map[string]any) (modular.Module, error) {
        cacheService := services["cache"].(cache.CacheEngine)
        return &MyModule{cache: cacheService}, nil
    }
}
Basic Operations
// Set a value in the cache with a TTL
err := cacheService.Set(ctx, "user:123", userData, 5*time.Minute)
if err != nil {
    // Handle error
}

// Get a value from the cache
value, found := cacheService.Get(ctx, "user:123")
if !found {
    // Cache miss, fetch from primary source
} else {
    userData = value.(UserData)
}

// Delete a value from the cache
err := cacheService.Delete(ctx, "user:123")
if err != nil {
    // Handle error
}
Bulk Operations
// Get multiple values
keys := []string{"user:123", "user:456", "user:789"}
results, err := cacheService.GetMulti(ctx, keys)
if err != nil {
    // Handle error
}

// Set multiple values
items := map[string]interface{}{
    "user:123": userData1,
    "user:456": userData2,
}
err := cacheService.SetMulti(ctx, items, 10*time.Minute)
if err != nil {
    // Handle error
}

// Delete multiple values
err := cacheService.DeleteMulti(ctx, keys)
if err != nil {
    // Handle error
}

Implementation Notes

  • The in-memory cache uses Go's built-in concurrency primitives for thread safety
  • Redis implementation is provided as a placeholder and would require a Redis client implementation
  • The cache automatically cleans up expired items at configurable intervals

Testing

The cache module includes comprehensive tests for the memory cache implementation.

Documentation

Index

Constants

View Source
const ModuleName = "cache"

ModuleName is the name of this module

View Source
const ServiceName = "cache.provider"

ServiceName is the name of the service provided by this module

Variables

View Source
var (
	// ErrCacheFull is returned when the memory cache is full and cannot store new items
	ErrCacheFull = errors.New("cache is full")

	// ErrInvalidKey is returned when the key is invalid
	ErrInvalidKey = errors.New("invalid cache key")

	// ErrInvalidValue is returned when the value cannot be stored in the cache
	ErrInvalidValue = errors.New("invalid cache value")

	// ErrNotConnected is returned when an operation is attempted on a cache that is not connected
	ErrNotConnected = errors.New("cache not connected")
)

Error definitions

Functions

func NewModule

func NewModule() modular.Module

NewModule creates a new instance of the cache module

Types

type CacheConfig

type CacheConfig struct {
	// Engine specifies the cache engine to use ("memory" or "redis")
	Engine string `json:"engine" yaml:"engine" env:"ENGINE" validate:"oneof=memory redis"`

	// DefaultTTL is the default time-to-live for cache entries in seconds
	DefaultTTL int `json:"defaultTTL" yaml:"defaultTTL" env:"DEFAULT_TTL" validate:"min=1"`

	// CleanupInterval is how often to clean up expired items (in seconds)
	CleanupInterval int `json:"cleanupInterval" yaml:"cleanupInterval" env:"CLEANUP_INTERVAL" validate:"min=1"`

	// MaxItems is the maximum number of items to store in memory cache
	MaxItems int `json:"maxItems" yaml:"maxItems" env:"MAX_ITEMS" validate:"min=1"`

	// Redis-specific configuration
	RedisURL      string `json:"redisURL" yaml:"redisURL" env:"REDIS_URL"`
	RedisPassword string `json:"redisPassword" yaml:"redisPassword" env:"REDIS_PASSWORD"`
	RedisDB       int    `json:"redisDB" yaml:"redisDB" env:"REDIS_DB" validate:"min=0"`

	// ConnectionMaxAge is the maximum age of a connection in seconds
	ConnectionMaxAge int `json:"connectionMaxAge" yaml:"connectionMaxAge" env:"CONNECTION_MAX_AGE" validate:"min=1"`
}

CacheConfig defines the configuration for the cache module

type CacheEngine

type CacheEngine interface {
	// Connect establishes connection to the cache backend
	Connect(ctx context.Context) error

	// Close closes the connection to the cache backend
	Close(ctx context.Context) error

	// Get retrieves an item from the cache
	Get(ctx context.Context, key string) (interface{}, bool)

	// Set stores an item in the cache with a TTL
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

	// Delete removes an item from the cache
	Delete(ctx context.Context, key string) error

	// Flush removes all items from the cache
	Flush(ctx context.Context) error

	// GetMulti retrieves multiple items from the cache
	GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)

	// SetMulti stores multiple items in the cache with a TTL
	SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error

	// DeleteMulti removes multiple items from the cache
	DeleteMulti(ctx context.Context, keys []string) error
}

CacheEngine defines the interface for cache engine implementations

type CacheModule

type CacheModule struct {
	// contains filtered or unexported fields
}

CacheModule represents the cache module

func (*CacheModule) Constructor

func (m *CacheModule) Constructor() modular.ModuleConstructor

Constructor provides a dependency injection constructor for the module

func (*CacheModule) Delete

func (m *CacheModule) Delete(ctx context.Context, key string) error

Delete removes an item from the cache

func (*CacheModule) DeleteMulti

func (m *CacheModule) DeleteMulti(ctx context.Context, keys []string) error

DeleteMulti removes multiple items from the cache

func (*CacheModule) Dependencies

func (m *CacheModule) Dependencies() []string

Dependencies returns the names of modules this module depends on

func (*CacheModule) Flush

func (m *CacheModule) Flush(ctx context.Context) error

Flush removes all items from the cache

func (*CacheModule) Get

func (m *CacheModule) Get(ctx context.Context, key string) (interface{}, bool)

Get retrieves a cached item by key

func (*CacheModule) GetMulti

func (m *CacheModule) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)

GetMulti retrieves multiple items from the cache

func (*CacheModule) Init

func (m *CacheModule) Init(app modular.Application) error

Init initializes the module

func (*CacheModule) Name

func (m *CacheModule) Name() string

Name returns the name of the module

func (*CacheModule) ProvidesServices

func (m *CacheModule) ProvidesServices() []modular.ServiceProvider

ProvidesServices declares services provided by this module

func (*CacheModule) RegisterConfig

func (m *CacheModule) RegisterConfig(app modular.Application) error

RegisterConfig registers the module's configuration structure

func (*CacheModule) RequiresServices

func (m *CacheModule) RequiresServices() []modular.ServiceDependency

RequiresServices declares services required by this module

func (*CacheModule) Set

func (m *CacheModule) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores an item in the cache with an optional TTL

func (*CacheModule) SetMulti

func (m *CacheModule) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error

SetMulti stores multiple items in the cache

func (*CacheModule) Start

func (m *CacheModule) Start(ctx context.Context) error

Start performs startup logic for the module

func (*CacheModule) Stop

func (m *CacheModule) Stop(ctx context.Context) error

Stop performs shutdown logic for the module

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache implements CacheEngine using in-memory storage

func NewMemoryCache

func NewMemoryCache(config *CacheConfig) *MemoryCache

NewMemoryCache creates a new memory cache engine

func (*MemoryCache) Close

func (c *MemoryCache) Close(_ context.Context) error

Close stops the memory cache cleanup routine

func (*MemoryCache) Connect

func (c *MemoryCache) Connect(ctx context.Context) error

Connect initializes the memory cache

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(_ context.Context, key string) error

Delete removes an item from the cache

func (*MemoryCache) DeleteMulti

func (c *MemoryCache) DeleteMulti(ctx context.Context, keys []string) error

DeleteMulti removes multiple items from the cache

func (*MemoryCache) Flush

func (c *MemoryCache) Flush(_ context.Context) error

Flush removes all items from the cache

func (*MemoryCache) Get

func (c *MemoryCache) Get(_ context.Context, key string) (interface{}, bool)

Get retrieves an item from the cache

func (*MemoryCache) GetMulti

func (c *MemoryCache) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)

GetMulti retrieves multiple items from the cache

func (*MemoryCache) Set

func (c *MemoryCache) Set(_ context.Context, key string, value interface{}, ttl time.Duration) error

Set stores an item in the cache

func (*MemoryCache) SetMulti

func (c *MemoryCache) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error

SetMulti stores multiple items in the cache

type RedisCache

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache implements CacheEngine using Redis

func NewRedisCache

func NewRedisCache(config *CacheConfig) *RedisCache

NewRedisCache creates a new Redis cache engine

func (*RedisCache) Close

func (c *RedisCache) Close(ctx context.Context) error

Close closes the connection to Redis

func (*RedisCache) Connect

func (c *RedisCache) Connect(ctx context.Context) error

Connect establishes connection to Redis

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, key string) error

Delete removes an item from the Redis cache

func (*RedisCache) DeleteMulti

func (c *RedisCache) DeleteMulti(ctx context.Context, keys []string) error

DeleteMulti removes multiple items from the Redis cache

func (*RedisCache) Flush

func (c *RedisCache) Flush(ctx context.Context) error

Flush removes all items from the Redis cache

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) (interface{}, bool)

Get retrieves an item from the Redis cache

func (*RedisCache) GetMulti

func (c *RedisCache) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)

GetMulti retrieves multiple items from the Redis cache

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores an item in the Redis cache with a TTL

func (*RedisCache) SetMulti

func (c *RedisCache) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error

SetMulti stores multiple items in the Redis cache with a TTL

Jump to

Keyboard shortcuts

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