From a739505da23ddb443a8b5dc4151f85dae7f912f4 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 14:48:18 +0000 Subject: [PATCH 1/2] feat(cache)!: the cache runs from its config, not CACHE_DRIVER The cache read CACHE_DRIVER from the environment, and queueing and the rate-limit middleware each built a cache of their own. A cache now takes config.Cache through cache.WithConfig, and one used without it fails with ErrNoConfig; the Redis driver uses the connection the config names. Queueing debounces in the app's cache (queueing.WithCache, which app.WithQueueing passes), and rate-limited jobs count in it (middleware.UseCache, which app.New calls). BREAKING CHANGE: a cache needs cache.WithConfig, cache.NewEngine and queueing.NewEngine take the config and the cache, and NewRedis takes a connection name. --- app/app.go | 4 +++ app/options.go | 2 +- cache/cache.go | 17 +++++++--- cache/engine.go | 20 ++++++----- cache/options.go | 10 ++++++ cache/resolvers/redis.go | 13 ++++++-- config/cache.go | 20 +++++++++++ queueing/engine.go | 6 ++-- .../middleware/rate-limited.middleware.go | 20 ++++++++--- queueing/options.go | 13 +++++++- queueing/queueing.go | 10 +++++- tests/cache/cache_test.go | 33 +++++++++++++++++++ tests/queueing/queueing_test.go | 5 +-- .../ratelimit}/ratelimit_test.go | 4 +-- 14 files changed, 146 insertions(+), 31 deletions(-) create mode 100644 config/cache.go create mode 100644 tests/cache/cache_test.go rename {ratelimit => tests/ratelimit}/ratelimit_test.go (89%) diff --git a/app/app.go b/app/app.go index b33c94f..a06a195 100644 --- a/app/app.go +++ b/app/app.go @@ -12,6 +12,7 @@ import ( "github.com/gonstruct/core/eventing" "github.com/gonstruct/core/facades/database" "github.com/gonstruct/core/queueing" + "github.com/gonstruct/core/queueing/middleware" "github.com/gonstruct/core/routing" "github.com/gonstruct/core/routing/response" "github.com/gonstruct/core/scheduling" @@ -71,6 +72,9 @@ func New(configuration config.App, options ...option) *App { option(application) } + // Rate-limited jobs count in the app's cache. + middleware.UseCache(application.Cache()) + if err := application.providers.Register(application.ctx); err != nil { log.Fatal().Err(err).Msg("Failed to register providers") } diff --git a/app/options.go b/app/options.go index b575460..257ec2c 100644 --- a/app/options.go +++ b/app/options.go @@ -76,7 +76,7 @@ func WithScheduling(options ...scheduling.Option) option { func WithQueueing(options ...queueing.Option) option { return func(a *App) { - a.queueing = queueing.New(options...) + a.queueing = queueing.New(append([]queueing.Option{queueing.WithCache(a.Cache)}, options...)...) a.console.Register("queue:work", func(*console.Console, []string) error { return a.queueing.Run() }) } } diff --git a/cache/cache.go b/cache/cache.go index 906ecef..fc2b8a4 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -2,12 +2,19 @@ package cache import ( "context" + "errors" "fmt" "sync" "time" + + "github.com/gonstruct/core/config" ) +// ErrNoConfig is a cache used without WithConfig. +var ErrNoConfig = errors.New("[cache] no config: pass cache.WithConfig") + type Cache struct { + config *config.Cache engine *Engine mu sync.Mutex } @@ -78,13 +85,13 @@ func (c *Cache) ensureEngine() error { return nil } - engine, err := NewEngine() - if err != nil { - return err + if c.config == nil { + return ErrNoConfig } - if engine.EngineResolver == nil { - return fmt.Errorf("no cache resolver configured (set CACHE_DRIVER)") + engine, err := NewEngine(*c.config) + if err != nil { + return err } c.engine = engine diff --git a/cache/engine.go b/cache/engine.go index 63f540e..dd5d128 100644 --- a/cache/engine.go +++ b/cache/engine.go @@ -2,20 +2,22 @@ package cache import ( "context" + "fmt" "time" "github.com/gonstruct/core/cache/resolvers" - - "github.com/gonstruct/validation/env" + "github.com/gonstruct/core/config" ) -func NewEngine() (*Engine, error) { - return &Engine{ - EngineResolver: map[string]EngineResolver{ - "memory": resolvers.NewMemory(), - "redis": resolvers.NewRedis(), - }[env.String("CACHE_DRIVER")], - }, nil +func NewEngine(cache config.Cache) (*Engine, error) { + switch cache.Driver { + case config.MemoryCacheDriver: + return &Engine{EngineResolver: resolvers.NewMemory()}, nil + case config.RedisCacheDriver: + return &Engine{EngineResolver: resolvers.NewRedis(cache.Connection.String())}, nil + default: + return nil, fmt.Errorf("[cache] unknown cache driver %q", cache.Driver) + } } type Engine struct { diff --git a/cache/options.go b/cache/options.go index 153065c..1e91ff5 100644 --- a/cache/options.go +++ b/cache/options.go @@ -1,3 +1,13 @@ package cache +import "github.com/gonstruct/core/config" + type Option func(*Cache) + +// WithConfig is how the cache runs: its driver. A cache used without one +// fails with ErrNoConfig. +func WithConfig(cache config.Cache) Option { + return func(c *Cache) { + c.config = &cache + } +} diff --git a/cache/resolvers/redis.go b/cache/resolvers/redis.go index 5ed490b..262cf9c 100644 --- a/cache/resolvers/redis.go +++ b/cache/resolvers/redis.go @@ -15,18 +15,25 @@ import ( // initialised lazily on first use so the package can be imported safely from // anywhere without requiring an explicit boot step. type Redis struct { + connection string clientOnce sync.Once client redis.UniversalClient clientErr error } -func NewRedis() *Redis { - return &Redis{} +// NewRedis is a cache on the Redis connection by that name: the default one +// when empty. +func NewRedis(connection string) *Redis { + if connection == "" { + connection = redisconnection.DefaultConnection + } + + return &Redis{connection: connection} } func (r *Redis) Client() (redis.UniversalClient, error) { r.clientOnce.Do(func() { - r.client, r.clientErr = redisconnection.NewClient(redisconnection.DefaultConnection) + r.client, r.clientErr = redisconnection.NewClient(r.connection) }) return r.client, r.clientErr } diff --git a/config/cache.go b/config/cache.go new file mode 100644 index 0000000..e34460c --- /dev/null +++ b/config/cache.go @@ -0,0 +1,20 @@ +package config + +// CacheDriver is where cached values live. +type CacheDriver string + +const ( + // MemoryCacheDriver keeps them in the process: gone on restart, and + // not shared between processes. + MemoryCacheDriver CacheDriver = "memory" + // RedisCacheDriver keeps them in Redis, shared between processes. + RedisCacheDriver CacheDriver = "redis" +) + +// Cache is how the cache runs, handed to cache.WithConfig. +type Cache struct { + Driver CacheDriver + // Connection is the Redis connection the redis driver uses: the + // default one when empty. + Connection RedisConnectionType +} diff --git a/queueing/engine.go b/queueing/engine.go index 8338dce..db74d88 100644 --- a/queueing/engine.go +++ b/queueing/engine.go @@ -15,9 +15,9 @@ import ( "github.com/hibiken/asynq" ) -func NewEngine(queue config.Queue) (*Engine, error) { - sharedCache := cache.New() - +// NewEngine is the queue running as configured, debouncing jobs in the +// cache. +func NewEngine(queue config.Queue, sharedCache *cache.Cache) (*Engine, error) { var resolver EngineResolver switch queue.Driver { case config.SynchronousQueueDriver: diff --git a/queueing/middleware/rate-limited.middleware.go b/queueing/middleware/rate-limited.middleware.go index 7a047e4..234605f 100644 --- a/queueing/middleware/rate-limited.middleware.go +++ b/queueing/middleware/rate-limited.middleware.go @@ -4,6 +4,7 @@ package middleware import ( "context" "errors" + "sync/atomic" "time" "github.com/gonstruct/core/cache" @@ -26,14 +27,25 @@ type RateLimited struct { limiter *ratelimit.Limiter } -// defaultLimiter is shared across every RateLimited instance: Middlewares() is +// sharedLimiter is shared across every RateLimited instance: Middlewares() is // re-evaluated on each job execution, so constructing a limiter (and with it a // cache engine and redis client) per instance would leak a connection pool per -// run and, on the memory driver, reset the window every run. -var defaultLimiter = ratelimit.New(cache.New()) +// run and, on the memory driver, reset the window every run. It counts in the +// app's cache (UseCache); until then, in one with no config, which fails +// open. +var sharedLimiter atomic.Pointer[ratelimit.Limiter] + +func init() { + sharedLimiter.Store(ratelimit.New(cache.New())) +} + +// UseCache has every RateLimited count in the cache: the app passes its own. +func UseCache(counts *cache.Cache) { + sharedLimiter.Store(ratelimit.New(counts)) +} func NewRateLimited(key string, limit ratelimit.Limit) *RateLimited { - return &RateLimited{key: key, limit: limit, limiter: defaultLimiter} + return &RateLimited{key: key, limit: limit, limiter: sharedLimiter.Load()} } func (self *RateLimited) Handle(context context.Context, _ job.Job, next func(context.Context) error) error { diff --git a/queueing/options.go b/queueing/options.go index 7c9bacd..7af6b85 100644 --- a/queueing/options.go +++ b/queueing/options.go @@ -1,6 +1,9 @@ package queueing -import "github.com/gonstruct/core/config" +import ( + "github.com/gonstruct/core/cache" + "github.com/gonstruct/core/config" +) type Option func(*Queueing) @@ -10,6 +13,14 @@ func WithQueues(queues ...func(*Engine)) Option { } } +// WithCache is the cache queued jobs debounce in, asked for when the queue +// first runs: the app passes its own. +func WithCache(cache func() *cache.Cache) Option { + return func(r *Queueing) { + r.Cache = cache + } +} + // WithConfig is how the queue runs: its driver, and how many workers the // default queue and each group have. Queueing needs it. func WithConfig(queue config.Queue) Option { diff --git a/queueing/queueing.go b/queueing/queueing.go index 969988d..fd524dc 100644 --- a/queueing/queueing.go +++ b/queueing/queueing.go @@ -7,6 +7,7 @@ import ( "sync" "time" + "github.com/gonstruct/core/cache" "github.com/gonstruct/core/config" "github.com/gonstruct/core/queueing/job" @@ -19,6 +20,9 @@ var ErrNoConfig = errors.New("[queueing] no config: pass queueing.WithConfig") type Queueing struct { Queues []func(*Engine) Config *config.Queue + // Cache is where debounced jobs keep their tokens: a cache with no + // config when unset, which fails a debounced dispatch. + Cache func() *cache.Cache engine *Engine mu sync.Mutex @@ -81,7 +85,11 @@ func (q *Queueing) ensureEngine() error { return ErrNoConfig } - engine, err := NewEngine(*q.Config) + shared := cache.New() + if q.Cache != nil { + shared = q.Cache() + } + engine, err := NewEngine(*q.Config, shared) if err != nil { return err } diff --git a/tests/cache/cache_test.go b/tests/cache/cache_test.go new file mode 100644 index 0000000..5a66aac --- /dev/null +++ b/tests/cache/cache_test.go @@ -0,0 +1,33 @@ +package cache_test + +import ( + "errors" + "testing" + "time" + + "github.com/gonstruct/core/cache" + "github.com/gonstruct/core/config" +) + +func TestACacheNeedsAConfig(t *testing.T) { + if _, _, err := cache.New().Get(t.Context(), "key"); !errors.Is(err, cache.ErrNoConfig) { + t.Fatalf("expected ErrNoConfig, got %v", err) + } +} + +func TestAnUnknownDriverIsRefused(t *testing.T) { + if _, err := cache.NewEngine(config.Cache{Driver: "floppy"}); err == nil { + t.Fatal("expected an error") + } +} + +func TestTheMemoryDriverKeepsWhatItIsGiven(t *testing.T) { + kept := cache.New(cache.WithConfig(config.Cache{Driver: config.MemoryCacheDriver})) + if err := kept.Set(t.Context(), "key", "value", time.Minute); err != nil { + t.Fatal(err) + } + + if value, found, err := kept.Get(t.Context(), "key"); err != nil || !found || value != "value" { + t.Fatalf("expected the value back, got %q %v (%v)", value, found, err) + } +} diff --git a/tests/queueing/queueing_test.go b/tests/queueing/queueing_test.go index 82d5884..a94b266 100644 --- a/tests/queueing/queueing_test.go +++ b/tests/queueing/queueing_test.go @@ -5,6 +5,7 @@ import ( "errors" "testing" + "github.com/gonstruct/core/cache" "github.com/gonstruct/core/config" "github.com/gonstruct/core/queueing" "github.com/gonstruct/core/queueing/job" @@ -30,13 +31,13 @@ func TestQueueingNeedsAConfig(t *testing.T) { } func TestAnUnknownDriverIsRefused(t *testing.T) { - if _, err := queueing.NewEngine(config.Queue{Driver: "carrier-pigeon"}); err == nil { + if _, err := queueing.NewEngine(config.Queue{Driver: "carrier-pigeon"}, cache.New()); err == nil { t.Fatal("expected an error") } } func TestAJobGoesOnItsGroupsQueue(t *testing.T) { - engine, err := queueing.NewEngine(config.Queue{Driver: config.SynchronousQueueDriver}) + engine, err := queueing.NewEngine(config.Queue{Driver: config.SynchronousQueueDriver}, cache.New()) if err != nil { t.Fatal(err) } diff --git a/ratelimit/ratelimit_test.go b/tests/ratelimit/ratelimit_test.go similarity index 89% rename from ratelimit/ratelimit_test.go rename to tests/ratelimit/ratelimit_test.go index a9032fd..8bc52c4 100644 --- a/ratelimit/ratelimit_test.go +++ b/tests/ratelimit/ratelimit_test.go @@ -5,12 +5,12 @@ import ( "time" "github.com/gonstruct/core/cache" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/ratelimit" ) func TestIncrementWeighsACallByItsAmount(t *testing.T) { - t.Setenv("CACHE_DRIVER", "memory") - limiter := ratelimit.New(cache.New()) + limiter := ratelimit.New(cache.New(cache.WithConfig(config.Cache{Driver: config.MemoryCacheDriver}))) limit := ratelimit.PerMinute(10) ctx := t.Context() From adf65e2db480ae0fee56ea277661cf8de5208da2 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 15:57:35 +0000 Subject: [PATCH 2/2] refactor(cache): keep the cache driver type private and the missing config error inline --- cache/cache.go | 5 +---- cache/options.go | 2 +- config/cache.go | 10 +++++----- tests/cache/cache_test.go | 6 +++--- 4 files changed, 10 insertions(+), 13 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index fc2b8a4..357e458 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -10,9 +10,6 @@ import ( "github.com/gonstruct/core/config" ) -// ErrNoConfig is a cache used without WithConfig. -var ErrNoConfig = errors.New("[cache] no config: pass cache.WithConfig") - type Cache struct { config *config.Cache engine *Engine @@ -86,7 +83,7 @@ func (c *Cache) ensureEngine() error { } if c.config == nil { - return ErrNoConfig + return errors.New("[cache] no config: pass cache.WithConfig") } engine, err := NewEngine(*c.config) diff --git a/cache/options.go b/cache/options.go index 1e91ff5..bcd9874 100644 --- a/cache/options.go +++ b/cache/options.go @@ -5,7 +5,7 @@ import "github.com/gonstruct/core/config" type Option func(*Cache) // WithConfig is how the cache runs: its driver. A cache used without one -// fails with ErrNoConfig. +// fails. func WithConfig(cache config.Cache) Option { return func(c *Cache) { c.config = &cache diff --git a/config/cache.go b/config/cache.go index e34460c..2dad5f2 100644 --- a/config/cache.go +++ b/config/cache.go @@ -1,19 +1,19 @@ package config -// CacheDriver is where cached values live. -type CacheDriver string +// cacheDriver is where cached values live. +type cacheDriver string const ( // MemoryCacheDriver keeps them in the process: gone on restart, and // not shared between processes. - MemoryCacheDriver CacheDriver = "memory" + MemoryCacheDriver cacheDriver = "memory" // RedisCacheDriver keeps them in Redis, shared between processes. - RedisCacheDriver CacheDriver = "redis" + RedisCacheDriver cacheDriver = "redis" ) // Cache is how the cache runs, handed to cache.WithConfig. type Cache struct { - Driver CacheDriver + Driver cacheDriver // Connection is the Redis connection the redis driver uses: the // default one when empty. Connection RedisConnectionType diff --git a/tests/cache/cache_test.go b/tests/cache/cache_test.go index 5a66aac..702f66f 100644 --- a/tests/cache/cache_test.go +++ b/tests/cache/cache_test.go @@ -1,7 +1,7 @@ package cache_test import ( - "errors" + "strings" "testing" "time" @@ -10,8 +10,8 @@ import ( ) func TestACacheNeedsAConfig(t *testing.T) { - if _, _, err := cache.New().Get(t.Context(), "key"); !errors.Is(err, cache.ErrNoConfig) { - t.Fatalf("expected ErrNoConfig, got %v", err) + if _, _, err := cache.New().Get(t.Context(), "key"); err == nil || !strings.Contains(err.Error(), "no config") { + t.Fatalf("expected no config, got %v", err) } }