{"modulePath":"github.com/CrisisTextLine/modular/modules/cache","version":"v0.4.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package cache\n\nPackage cache provides a flexible caching module for the modular framework.\n\nThis module supports multiple cache backends including in-memory and Redis, with configurable TTL, cleanup intervals, and connection management. It provides a unified interface for caching operations across different storage engines.\n\n### Supported Cache Engines {#hdr-Supported_Cache_Engines}\n\nThe cache module supports the following engines:\n\n  - \"memory\": In-memory cache with LRU eviction and TTL support\n  - \"redis\": Redis-based cache with connection pooling and persistence\n\n### Configuration {#hdr-Configuration}\n\nThe module can be configured through the CacheConfig structure:\n\n\tconfig := \u0026CacheConfig{\n\t    Engine:           \"memory\",     // or \"redis\"\n\t    DefaultTTL:       300,          // 5 minutes default TTL\n\t    CleanupInterval:  60,           // cleanup every minute\n\t    MaxItems:         10000,        // max items for memory cache\n\t    RedisURL:         \"redis://localhost:6379\", // for Redis engine\n\t    RedisPassword:    \"\",           // Redis password if required\n\t    RedisDB:          0,            // Redis database number\n\t    ConnectionMaxAge: 60,           // connection max age in seconds\n\t}\n\n### Service Registration {#hdr-Service_Registration}\n\nThe module registers itself as a service that can be injected into other modules:\n\n\t// Get the cache service\n\tcacheService := app.GetService(\"cache.provider\").(*CacheModule)\n\n\t// Use the cache\n\terr := cacheService.Set(ctx, \"key\", \"value\", time.Minute*5)\n\tvalue, found := cacheService.Get(ctx, \"key\")\n\n### Usage Examples {#hdr-Usage_Examples}\n\nBasic caching operations:\n\n\t// Set a value with default TTL\n\terr := cache.Set(ctx, \"user:123\", userData, 0)\n\n\t// Set a value with custom TTL\n\terr := cache.Set(ctx, \"session:abc\", sessionData, time.Hour)\n\n\t// Get a value\n\tvalue, found := cache.Get(ctx, \"user:123\")\n\tif found {\n\t    user := value.(UserData)\n\t    // use user data\n\t}\n\n\t// Batch operations\n\titems := map[string]interface{}{\n\t    \"key1\": \"value1\",\n\t    \"key2\": \"value2\",\n\t}\n\terr := cache.SetMulti(ctx, items, time.Minute*10)\n\n\tresults, err := cache.GetMulti(ctx, []string{\"key1\", \"key2\"})\n\n## Constants\n\n```go\nconst (\n\t// Cache operation events\n\tEventTypeCacheGet    = \"com.modular.cache.get\"\n\tEventTypeCacheSet    = \"com.modular.cache.set\"\n\tEventTypeCacheDelete = \"com.modular.cache.delete\"\n\tEventTypeCacheFlush  = \"com.modular.cache.flush\"\n\n\t// Cache state events\n\tEventTypeCacheHit     = \"com.modular.cache.hit\"\n\tEventTypeCacheMiss    = \"com.modular.cache.miss\"\n\tEventTypeCacheExpired = \"com.modular.cache.expired\"\n\tEventTypeCacheEvicted = \"com.modular.cache.evicted\"\n\n\t// Cache engine events\n\tEventTypeCacheConnected    = \"com.modular.cache.connected\"\n\tEventTypeCacheDisconnected = \"com.modular.cache.disconnected\"\n\tEventTypeCacheError        = \"com.modular.cache.error\"\n)\n```\nEvent type constants for cache module events. Following CloudEvents specification reverse domain notation.\n\n```go\nconst ModuleName = \"cache\"\n```\nModuleName is the unique identifier for the cache module.\n\n```go\nconst ServiceName = \"cache.provider\"\n```\nServiceName is the name of the service provided by this module. Other modules can use this name to request the cache service through dependency injection.\n\n## Variables\n\n```go\nvar (\n\t// ErrCacheFull is returned when the memory cache is full and cannot store new items\n\tErrCacheFull = errors.New(\"cache is full\")\n\n\t// ErrInvalidKey is returned when the key is invalid\n\tErrInvalidKey = errors.New(\"invalid cache key\")\n\n\t// ErrInvalidValue is returned when the value cannot be stored in the cache\n\tErrInvalidValue = errors.New(\"invalid cache value\")\n\n\t// ErrNotConnected is returned when an operation is attempted on a cache that is not connected\n\tErrNotConnected = errors.New(\"cache not connected\")\n\n\t// ErrNoSubjectForEventEmission is returned when trying to emit events without a subject\n\tErrNoSubjectForEventEmission = errors.New(\"no subject available for event emission\")\n)\n```\nError definitions\n\n## Functions\n\n```go\nfunc NewModule() modular.Module\n```\nNewModule creates a new instance of the cache module. This is the primary constructor for the cache module and should be used when registering the module with the application.\n\nExample:\n\n\tapp.RegisterModule(cache.NewModule())\n\n## Types\n\n```go\ntype CacheConfig struct {\n\t// Engine specifies the cache engine to use.\n\t// Supported values: \"memory\", \"redis\"\n\t// Default: \"memory\"\n\tEngine string `json:\"engine\" yaml:\"engine\" env:\"ENGINE\" default:\"memory\" validate:\"oneof=memory redis\"`\n\n\t// DefaultTTL is the default time-to-live for cache entries.\n\t// Used when no explicit TTL is provided in cache operations.\n\tDefaultTTL time.Duration `json:\"defaultTTL\" yaml:\"defaultTTL\" env:\"DEFAULT_TTL\" default:\"300s\"`\n\n\t// CleanupInterval is how often to clean up expired items.\n\t// Only applicable to memory cache engine.\n\tCleanupInterval time.Duration `json:\"cleanupInterval\" yaml:\"cleanupInterval\" env:\"CLEANUP_INTERVAL\" default:\"60s\"`\n\n\t// MaxItems is the maximum number of items to store in memory cache.\n\t// When this limit is reached, least recently used items are evicted.\n\t// Only applicable to memory cache engine.\n\t// Must be at least 1.\n\tMaxItems int `json:\"maxItems\" yaml:\"maxItems\" env:\"MAX_ITEMS\" default:\"10000\" validate:\"min=1\"`\n\n\t// RedisURL is the connection URL for Redis server.\n\t// Format: redis://[username:password@]host:port[/database]\n\t// Only required when using Redis engine.\n\t// Example: \"redis://localhost:6379\", \"redis://user:pass@localhost:6379/1\"\n\tRedisURL string `json:\"redisURL\" yaml:\"redisURL\" env:\"REDIS_URL\"`\n\n\t// RedisPassword is the password for Redis authentication.\n\t// Optional if Redis server doesn't require authentication.\n\tRedisPassword string `json:\"redisPassword\" yaml:\"redisPassword\" env:\"REDIS_PASSWORD\"`\n\n\t// RedisDB is the Redis database number to use.\n\t// Redis supports multiple databases (0-15 by default).\n\t// Must be non-negative.\n\tRedisDB int `json:\"redisDB\" yaml:\"redisDB\" env:\"REDIS_DB\" validate:\"min=0\"`\n\n\t// ConnectionMaxAge is the maximum age of a connection.\n\t// Connections older than this will be closed and recreated.\n\t// Helps prevent connection staleness in long-running applications.\n\tConnectionMaxAge time.Duration `json:\"connectionMaxAge\" yaml:\"connectionMaxAge\" env:\"CONNECTION_MAX_AGE\" default:\"3600s\"`\n}\n```\nCacheConfig defines the configuration for the cache module. This structure contains all the settings needed to configure both memory and Redis cache engines.\n\nConfiguration can be provided through JSON, YAML, or environment variables. The struct tags define the mapping for each configuration source and validation rules.\n\nExample JSON configuration:\n\n\t{\n\t  \"engine\": \"redis\",\n\t  \"defaultTTL\": 600,\n\t  \"cleanupInterval\": 300,\n\t  \"maxItems\": 50000,\n\t  \"redisURL\": \"redis://localhost:6379\",\n\t  \"redisPassword\": \"mypassword\",\n\t  \"redisDB\": 1\n\t}\n\nExample environment variables:\n\n\tCACHE_ENGINE=memory\n\tCACHE_DEFAULT_TTL=300\n\tCACHE_MAX_ITEMS=10000\n\n```go\ntype CacheEngine interface {\n\t// Connect establishes connection to the cache backend.\n\t// This method is called during module startup and should prepare\n\t// the engine for cache operations. For memory caches, this might\n\t// initialize internal data structures. For network-based caches\n\t// like Redis, this establishes the connection pool.\n\t//\n\t// The context can be used to handle connection timeouts.\n\tConnect(ctx context.Context) error\n\n\t// Close closes the connection to the cache backend.\n\t// This method is called during module shutdown and should cleanup\n\t// all resources, close network connections, and stop background\n\t// processes. The method should be idempotent - safe to call multiple times.\n\t//\n\t// The context can be used to handle graceful shutdown timeouts.\n\tClose(ctx context.Context) error\n\n\t// Get retrieves an item from the cache.\n\t// Returns the cached value and a boolean indicating whether the key was found.\n\t// If the key doesn't exist or has expired, returns (nil, false).\n\t//\n\t// The returned value should be the same type that was stored.\n\t// The context can be used for operation timeouts.\n\tGet(ctx context.Context, key string) (interface{}, bool)\n\n\t// Set stores an item in the cache with a TTL.\n\t// The value can be any serializable type. The TTL determines how long\n\t// the item should remain in the cache before expiring.\n\t//\n\t// If TTL is 0 or negative, the item should use the default TTL or\n\t// never expire, depending on the implementation.\n\t//\n\t// The context can be used for operation timeouts.\n\tSet(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n\n\t// Delete removes an item from the cache.\n\t// Should not return an error if the key doesn't exist.\n\t// Only returns errors for actual operation failures.\n\t//\n\t// The context can be used for operation timeouts.\n\tDelete(ctx context.Context, key string) error\n\n\t// Flush removes all items from the cache.\n\t// This operation should be atomic - either all items are removed\n\t// or none are. Should be used with caution as it's irreversible.\n\t//\n\t// The context can be used for operation timeouts.\n\tFlush(ctx context.Context) error\n\n\t// GetMulti retrieves multiple items from the cache in a single operation.\n\t// Returns a map containing only the keys that were found.\n\t// Missing or expired keys are not included in the result.\n\t//\n\t// This operation should be more efficient than multiple Get calls\n\t// for network-based caches.\n\t//\n\t// The context can be used for operation timeouts.\n\tGetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)\n\n\t// SetMulti stores multiple items in the cache with a TTL.\n\t// All items use the same TTL value. This operation should be atomic\n\t// where possible - either all items are stored or none are.\n\t//\n\t// This operation should be more efficient than multiple Set calls\n\t// for network-based caches.\n\t//\n\t// The context can be used for operation timeouts.\n\tSetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error\n\n\t// DeleteMulti removes multiple items from the cache.\n\t// Should not return an error for keys that don't exist.\n\t// Only returns errors for actual operation failures.\n\t//\n\t// This operation should be more efficient than multiple Delete calls\n\t// for network-based caches.\n\t//\n\t// The context can be used for operation timeouts.\n\tDeleteMulti(ctx context.Context, keys []string) error\n}\n```\nCacheEngine defines the interface for cache engine implementations. This interface abstracts the underlying storage mechanism, allowing the cache module to support multiple backends (memory, Redis, etc.) through a common API.\n\nAll operations are context-aware to support cancellation and timeouts. Implementations should be thread-safe and handle concurrent access properly.\n\nCache engines are responsible for:\n\n  - Connection management to the underlying storage\n  - Data serialization/deserialization\n  - TTL handling and expiration\n  - Error handling and recovery\n\n```go\ntype CacheModule struct {\n\t// contains filtered or unexported fields\n}\n```\nCacheModule provides caching functionality for the modular framework. It supports multiple cache backends (memory and Redis) and provides a unified interface for caching operations including TTL management, batch operations, and automatic cleanup.\n\nThe module implements the following interfaces:\n\n  - modular.Module: Basic module lifecycle\n  - modular.Configurable: Configuration management\n  - modular.ServiceAware: Service dependency management\n\nThe module implements the following interfaces:\n\n  - modular.Module: Basic module lifecycle\n  - modular.Configurable: Configuration management\n  - modular.ServiceAware: Service dependency management\n  - modular.Startable: Startup logic\n  - modular.Stoppable: Shutdown logic\n  - modular.ObservableModule: Event observation and emission\n\nCache operations are thread-safe and support context cancellation.\n\n```go\nfunc (m *CacheModule) Constructor() modular.ModuleConstructor\n```\nConstructor provides a dependency injection constructor for the module. This method is used by the dependency injection system to create the module instance with any required services.\n\n```go\nfunc (m *CacheModule) Delete(ctx context.Context, key string) error\n```\nDelete removes an item from the cache. Returns an error if the deletion fails, but not if the key doesn't exist.\n\nExample:\n\n\terr := cache.Delete(ctx, \"user:123\")\n\tif err != nil {\n\t    // handle deletion error\n\t}\n\n```go\nfunc (m *CacheModule) DeleteMulti(ctx context.Context, keys []string) error\n```\nDeleteMulti removes multiple items from the cache in a single operation. This is more efficient than multiple Delete calls for batch operations. Does not return an error for keys that don't exist.\n\nExample:\n\n\tkeys := []string{\"user:123\", \"user:456\", \"expired:key\"}\n\terr := cache.DeleteMulti(ctx, keys)\n\tif err != nil {\n\t    // handle deletion error\n\t}\n\n```go\nfunc (m *CacheModule) Dependencies() []string\n```\nDependencies returns the names of modules this module depends on. The cache module has no dependencies and can be started independently.\n\n```go\nfunc (m *CacheModule) EmitEvent(ctx context.Context, event cloudevents.Event) error\n```\nEmitEvent implements the ObservableModule interface. This allows the cache module to emit events to registered observers.\n\n```go\nfunc (m *CacheModule) Flush(ctx context.Context) error\n```\nFlush removes all items from the cache. This operation is irreversible and should be used with caution. Useful for cache invalidation or testing scenarios.\n\nExample:\n\n\terr := cache.Flush(ctx)\n\tif err != nil {\n\t    // handle flush error\n\t}\n\n```go\nfunc (m *CacheModule) Get(ctx context.Context, key string) (interface{}, bool)\n```\nGet retrieves a cached item by key. Returns the cached value and a boolean indicating whether the key was found. If the key doesn't exist or has expired, returns (nil, false).\n\nExample:\n\n\tvalue, found := cache.Get(ctx, \"user:123\")\n\tif found {\n\t    user := value.(UserData)\n\t    // process user data\n\t}\n\n```go\nfunc (m *CacheModule) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)\n```\nGetMulti retrieves multiple items from the cache in a single operation. Returns a map of key-value pairs for found items and an error if the operation fails. Missing keys are simply not included in the result map.\n\nExample:\n\n\tkeys := []string{\"user:123\", \"user:456\", \"user:789\"}\n\tresults, err := cache.GetMulti(ctx, keys)\n\tif err != nil {\n\t    // handle error\n\t}\n\tfor key, value := range results {\n\t    // process found values\n\t}\n\n```go\nfunc (m *CacheModule) GetRegisteredEventTypes() []string\n```\nGetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this cache module can emit.\n\n```go\nfunc (m *CacheModule) Init(app modular.Application) error\n```\nInit initializes the cache module with the application context. This method is called after all modules have been registered and their configurations loaded. It sets up the cache engine based on the configuration.\n\nThe initialization process:\n\n 1. Retrieves the module's configuration\n 2. Sets up logging\n 3. Initializes the appropriate cache engine (memory or Redis)\n 4. Logs the initialization status\n\nSupported cache engines:\n\n  - \"memory\": In-memory cache with LRU eviction\n  - \"redis\": Redis-based distributed cache\n  - fallback: defaults to memory cache for unknown engines\n\n```go\nfunc (m *CacheModule) Name() string\n```\nName returns the unique identifier for this module. This name is used for service registration, dependency resolution, and configuration section identification.\n\n```go\nfunc (m *CacheModule) ProvidesServices() []modular.ServiceProvider\n```\nProvidesServices declares services provided by this module. The cache module provides a cache service that can be injected into other modules.\n\nProvided services:\n\n  - \"cache.provider\": The main cache service interface\n\n```go\nfunc (m *CacheModule) RegisterConfig(app modular.Application) error\n```\nRegisterConfig registers the module's configuration structure. This method is called during application initialization to register the configuration structure for the cache module. Defaults are provided via struct tags in the CacheConfig structure.\n\nDefault configuration (from struct tags):\n\n  - Engine: \"memory\"\n  - DefaultTTL: 300s (5 minutes)\n  - CleanupInterval: 60s (1 minute)\n  - MaxItems: 10000\n  - ConnectionMaxAge: 3600s (1 hour)\n  - Redis settings: empty/default values\n\n```go\nfunc (m *CacheModule) RegisterObservers(subject modular.Subject) error\n```\nRegisterObservers implements the ObservableModule interface. This allows the cache module to register as an observer for events it's interested in.\n\n```go\nfunc (m *CacheModule) RequiresServices() []modular.ServiceDependency\n```\nRequiresServices declares services required by this module. The cache module operates independently and requires no external services.\n\n```go\nfunc (m *CacheModule) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n```\nSet stores an item in the cache with an optional TTL. If ttl is 0, uses the default TTL from configuration. The value can be any serializable type.\n\nExample:\n\n\t// Use default TTL\n\terr := cache.Set(ctx, \"user:123\", userData, 0)\n\n\t// Use custom TTL\n\terr := cache.Set(ctx, \"session:abc\", sessionData, time.Hour)\n\n```go\nfunc (m *CacheModule) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error\n```\nSetMulti stores multiple items in the cache in a single operation. All items will use the same TTL. If ttl is 0, uses the default TTL from configuration. This is more efficient than multiple Set calls for batch operations.\n\nExample:\n\n\titems := map[string]interface{}{\n\t    \"user:123\": userData1,\n\t    \"user:456\": userData2,\n\t    \"session:abc\": sessionData,\n\t}\n\terr := cache.SetMulti(ctx, items, time.Minute*30)\n\n```go\nfunc (m *CacheModule) Start(ctx context.Context) error\n```\nStart performs startup logic for the module. This method establishes connections to the cache backend and prepares the cache for operations. It's called after all modules have been initialized.\n\nFor memory cache: No external connections are needed For Redis cache: Establishes connection pool to the Redis server\n\n```go\nfunc (m *CacheModule) Stop(ctx context.Context) error\n```\nStop performs shutdown logic for the module. This method gracefully closes all connections and cleans up resources. It's called during application shutdown to ensure proper cleanup.\n\nThe shutdown process:\n\n 1. Logs the shutdown initiation\n 2. Closes cache engine connections\n 3. Cleans up any background processes\n\n```go\ntype MemoryCache struct {\n\t// contains filtered or unexported fields\n}\n```\nMemoryCache implements CacheEngine using in-memory storage\n\n```go\nfunc NewMemoryCache(config *CacheConfig) *MemoryCache\n```\nNewMemoryCache creates a new memory cache engine\n\n```go\nfunc (c *MemoryCache) CleanupNow(ctx context.Context)\n```\nCleanupNow forces an immediate cleanup cycle of expired items and emits corresponding events. Intended primarily for tests to deterministically process expirations without waiting for timers.\n\n```go\nfunc (c *MemoryCache) Close(_ context.Context) error\n```\nClose stops the memory cache cleanup routine\n\n```go\nfunc (c *MemoryCache) Connect(ctx context.Context) error\n```\nConnect initializes the memory cache\n\n```go\nfunc (c *MemoryCache) Delete(_ context.Context, key string) error\n```\nDelete removes an item from the cache\n\n```go\nfunc (c *MemoryCache) DeleteMulti(ctx context.Context, keys []string) error\n```\nDeleteMulti removes multiple items from the cache\n\n```go\nfunc (c *MemoryCache) Flush(_ context.Context) error\n```\nFlush removes all items from the cache\n\n```go\nfunc (c *MemoryCache) Get(ctx context.Context, key string) (interface{}, bool)\n```\nGet retrieves an item from the cache\n\n```go\nfunc (c *MemoryCache) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)\n```\nGetMulti retrieves multiple items from the cache\n\n```go\nfunc (c *MemoryCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n```\nSet stores an item in the cache\n\n```go\nfunc (c *MemoryCache) SetEventEmitter(emitter func(ctx context.Context, event cloudevents.Event))\n```\nSetEventEmitter sets the event emission callback for the memory cache\n\n```go\nfunc (c *MemoryCache) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error\n```\nSetMulti stores multiple items in the cache\n\n```go\nfunc (c *MemoryCache) TriggerCleanupIfNeeded(ctx context.Context)\n```\nTriggerCleanupIfNeeded forces cleanup to run if sufficient time has passed since last cleanup This method can be used by tests to ensure cleanup happens naturally without artificial delays\n\n```go\ntype RedisCache struct {\n\t// contains filtered or unexported fields\n}\n```\nRedisCache implements CacheEngine using Redis\n\n```go\nfunc NewRedisCache(config *CacheConfig) *RedisCache\n```\nNewRedisCache creates a new Redis cache engine\n\n```go\nfunc (c *RedisCache) Close(ctx context.Context) error\n```\nClose closes the connection to Redis\n\n```go\nfunc (c *RedisCache) Connect(ctx context.Context) error\n```\nConnect establishes connection to Redis\n\n```go\nfunc (c *RedisCache) Delete(ctx context.Context, key string) error\n```\nDelete removes an item from the Redis cache\n\n```go\nfunc (c *RedisCache) DeleteMulti(ctx context.Context, keys []string) error\n```\nDeleteMulti removes multiple items from the Redis cache\n\n```go\nfunc (c *RedisCache) Flush(ctx context.Context) error\n```\nFlush removes all items from the Redis cache\n\n```go\nfunc (c *RedisCache) Get(ctx context.Context, key string) (interface{}, bool)\n```\nGet retrieves an item from the Redis cache\n\n```go\nfunc (c *RedisCache) GetMulti(ctx context.Context, keys []string) (map[string]interface{}, error)\n```\nGetMulti retrieves multiple items from the Redis cache\n\n```go\nfunc (c *RedisCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error\n```\nSet stores an item in the Redis cache with a TTL\n\n```go\nfunc (c *RedisCache) SetMulti(ctx context.Context, items map[string]interface{}, ttl time.Duration) error\n```\nSetMulti stores multiple items in the Redis cache with a TTL\n\n","path":"github.com/CrisisTextLine/modular/modules/cache","name":"cache","synopsis":"Package cache provides a flexible caching module for the modular framework.","isRedistributable":true}
