diff --git a/app/app.go b/app/app.go index 9d97ec9..348ecdb 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/scheduling" @@ -67,6 +68,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..357e458 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -2,12 +2,16 @@ package cache import ( "context" + "errors" "fmt" "sync" "time" + + "github.com/gonstruct/core/config" ) type Cache struct { + config *config.Cache engine *Engine mu sync.Mutex } @@ -78,13 +82,13 @@ func (c *Cache) ensureEngine() error { return nil } - engine, err := NewEngine() - if err != nil { - return err + if c.config == nil { + return errors.New("[cache] no config: pass cache.WithConfig") } - 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..bcd9874 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. +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..2dad5f2 --- /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 eba9640..0a3fda5 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 af1bd10..2c3aaa2 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" @@ -16,6 +17,9 @@ import ( 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 @@ -78,7 +82,11 @@ func (q *Queueing) ensureEngine() error { return errors.New("[queueing] no config: pass queueing.WithConfig") } - 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..702f66f --- /dev/null +++ b/tests/cache/cache_test.go @@ -0,0 +1,33 @@ +package cache_test + +import ( + "strings" + "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"); err == nil || !strings.Contains(err.Error(), "no config") { + t.Fatalf("expected no config, 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 0a8f665..2a88711 100644 --- a/tests/queueing/queueing_test.go +++ b/tests/queueing/queueing_test.go @@ -5,6 +5,7 @@ import ( "strings" "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()