Skip to content
Merged
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
9 changes: 5 additions & 4 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,11 @@ 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"

"github.com/rs/zerolog/log"

"github.com/gonstruct/validation/env"
)

type App struct {
Expand Down Expand Up @@ -53,9 +52,9 @@ func Instance() *App {

var instance *App

func New(options ...option) *App {
func New(configuration config.App, options ...option) *App {
application := &App{
environment: env.Enum[config.Environment]("APP_ENV"),
environment: configuration.Environment,
ctx: context.Background(),
createdAt: time.Now(),
console: console.New(),
Expand All @@ -65,6 +64,8 @@ func New(options ...option) *App {
option(application)
}

middleware.UseCache(application.Cache())

if err := application.providers.Register(application.ctx); err != nil {
log.Fatal().Err(err).Msg("Failed to register providers")
}
Expand Down
13 changes: 11 additions & 2 deletions app/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import (
"embed"

"github.com/gonstruct/core/cache"
"github.com/gonstruct/core/config"
"github.com/gonstruct/core/console"
"github.com/gonstruct/core/database/migration"
"github.com/gonstruct/core/eventing"
"github.com/gonstruct/core/facades/database"
"github.com/gonstruct/core/facades/database/seeder"
"github.com/gonstruct/core/queueing"
redisconnection "github.com/gonstruct/core/redis"
"github.com/gonstruct/core/routing"
"github.com/gonstruct/core/scheduling"
)
Expand Down Expand Up @@ -54,6 +56,13 @@ func WithSeeders(seeders seeder.Seeders) option {
}
}

// WithRedis registers the Redis connections the queue and cache use.
func WithRedis(redis config.Redis) option {
return func(*App) {
redisconnection.Configure(redis)
}
}

func WithCache(options ...cache.Option) option {
return func(a *App) {
a.cache = cache.New(options...)
Expand All @@ -69,14 +78,14 @@ func WithRouting(options ...routing.Option) option {

func WithScheduling(options ...scheduling.Option) option {
return func(a *App) {
a.scheduling = scheduling.New(options...)
a.scheduling = scheduling.New(append([]scheduling.Option{scheduling.WithEnvironment(a.environment.String())}, options...)...)
a.console.Register("schedule:work", func(*console.Console, []string) error { return a.scheduling.Run() })
}
}

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
9 changes: 9 additions & 0 deletions cache/options.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
package cache

import "github.com/gonstruct/core/config"

type Option func(*Cache)

// WithConfig is required.
func WithConfig(cache config.Cache) Option {
return func(c *Cache) {
c.config = &cache
}
}
8 changes: 5 additions & 3 deletions cache/resolvers/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,20 @@ 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 uses the named config.Redis connection; the default when empty.
func NewRedis(connection string) *Redis {
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
21 changes: 21 additions & 0 deletions config/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package config

type cacheDriver string

const (
MemoryCacheDriver cacheDriver = "memory"
RedisCacheDriver cacheDriver = "redis"
)

func (driver cacheDriver) Values() []cacheDriver {
return []cacheDriver{MemoryCacheDriver, RedisCacheDriver}
}

func (driver cacheDriver) String() string {
return string(driver)
}

type Cache struct {
Driver cacheDriver
Connection RedisConnectionType // the redis driver's connection; default when empty
}
33 changes: 27 additions & 6 deletions config/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,33 @@ type Redis struct {
}

type RedisConnection struct {
Host string
Port string
Username string
Password string
Database int
TLS bool
Mode redisMode // default single
Addresses []string // the servers, or the sentinels; Host and Port also work for one server
Host string
Port string
MasterName string // sentinel mode only
Username string
Password string
SentinelUsername string
SentinelPassword string
Database int // 0 to 15; must be 0 in cluster mode
TLS bool
}

type redisMode string

const (
SingleRedisMode redisMode = "single"
SentinelRedisMode redisMode = "sentinel"
ClusterRedisMode redisMode = "cluster"
)

func (mode redisMode) Values() []redisMode {
return []redisMode{SingleRedisMode, SentinelRedisMode, ClusterRedisMode}
}

func (mode redisMode) String() string {
return string(mode)
}

type RedisConnectionType string
Expand Down
12 changes: 12 additions & 0 deletions config/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package config

import "time"

type Server struct {
Host string // default 0.0.0.0
Port int // default 80
ShutdownTimeout time.Duration // default 30s
HealthEndpoint string // no health endpoint when empty
TrustedPlatform string // see gin.Engine.TrustedPlatform
ShowErrors bool // include the error in failed responses; never in production
}
4 changes: 1 addition & 3 deletions queueing/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ import (
"github.com/hibiken/asynq"
)

func NewEngine(queue config.Queue) (*Engine, error) {
sharedCache := cache.New()

func NewEngine(queue config.Queue, sharedCache *cache.Cache) (*Engine, error) {
var resolver EngineResolver
switch queue.Driver {
case config.SynchronousQueueDriver:
Expand Down
16 changes: 13 additions & 3 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,23 @@ 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())
var sharedLimiter atomic.Pointer[ratelimit.Limiter]

func init() {
sharedLimiter.Store(ratelimit.New(cache.New()))
}

// UseCache sets the cache rate limits count in. app.New calls it.
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 sets the cache debounced jobs use. It is called when the queue
// first runs.
func WithCache(cache func() *cache.Cache) Option {
return func(r *Queueing) {
r.Cache = cache
}
}

// WithConfig is required.
func WithConfig(queue config.Queue) Option {
return func(r *Queueing) {
Expand Down
8 changes: 7 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,7 @@ import (
type Queueing struct {
Queues []func(*Engine)
Config *config.Queue
Cache func() *cache.Cache

engine *Engine
mu sync.Mutex
Expand Down Expand Up @@ -78,7 +80,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
Loading