Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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")
}
Expand Down
2 changes: 1 addition & 1 deletion app/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() })
}
}
Expand Down
14 changes: 9 additions & 5 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down
20 changes: 11 additions & 9 deletions cache/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 10 additions & 0 deletions cache/options.go
Original file line number Diff line number Diff line change
@@ -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
}
}
13 changes: 10 additions & 3 deletions cache/resolvers/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
20 changes: 20 additions & 0 deletions config/cache.go
Original file line number Diff line number Diff line change
@@ -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
}
6 changes: 3 additions & 3 deletions queueing/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 16 additions & 4 deletions queueing/middleware/rate-limited.middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package middleware
import (
"context"
"errors"
"sync/atomic"
"time"

"github.com/gonstruct/core/cache"
Expand All @@ -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 {
Expand Down
13 changes: 12 additions & 1 deletion queueing/options.go
Original file line number Diff line number Diff line change
@@ -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)

Expand All @@ -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 {
Expand Down
10 changes: 9 additions & 1 deletion queueing/queueing.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"sync"
"time"

"github.com/gonstruct/core/cache"
"github.com/gonstruct/core/config"
"github.com/gonstruct/core/queueing/job"

Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
33 changes: 33 additions & 0 deletions tests/cache/cache_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
5 changes: 3 additions & 2 deletions tests/queueing/queueing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down