diff --git a/app/app.go b/app/app.go index 50c6f5d..e65def4 100644 --- a/app/app.go +++ b/app/app.go @@ -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 { @@ -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(), @@ -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") } diff --git a/app/options.go b/app/options.go index 9e09338..3f03649 100644 --- a/app/options.go +++ b/app/options.go @@ -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" ) @@ -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...) @@ -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() }) } } 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..28ef171 100644 --- a/cache/options.go +++ b/cache/options.go @@ -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 + } +} diff --git a/cache/resolvers/redis.go b/cache/resolvers/redis.go index 5ed490b..68f2932 100644 --- a/cache/resolvers/redis.go +++ b/cache/resolvers/redis.go @@ -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 } diff --git a/config/cache.go b/config/cache.go new file mode 100644 index 0000000..db80b25 --- /dev/null +++ b/config/cache.go @@ -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 +} diff --git a/config/redis.go b/config/redis.go index 298419f..9161b22 100644 --- a/config/redis.go +++ b/config/redis.go @@ -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 diff --git a/config/server.go b/config/server.go new file mode 100644 index 0000000..b2128f7 --- /dev/null +++ b/config/server.go @@ -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 +} diff --git a/queueing/engine.go b/queueing/engine.go index 48d65b9..0ac80a7 100644 --- a/queueing/engine.go +++ b/queueing/engine.go @@ -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: diff --git a/queueing/middleware/rate-limited.middleware.go b/queueing/middleware/rate-limited.middleware.go index 7a047e4..cb5957b 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,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 { diff --git a/queueing/options.go b/queueing/options.go index b72a1b2..105ef45 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 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) { diff --git a/queueing/queueing.go b/queueing/queueing.go index af1bd10..81e0e62 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,7 @@ import ( type Queueing struct { Queues []func(*Engine) Config *config.Queue + Cache func() *cache.Cache engine *Engine mu sync.Mutex @@ -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 } diff --git a/redis/connection.go b/redis/connection.go index f58ab84..832ee96 100644 --- a/redis/connection.go +++ b/redis/connection.go @@ -2,11 +2,13 @@ package redis import ( "crypto/tls" + "errors" "fmt" "net" - "os" - "strconv" "strings" + "sync/atomic" + + "github.com/gonstruct/core/config" goredis "github.com/redis/go-redis/v9" ) @@ -14,9 +16,9 @@ import ( const ( DefaultConnection = "default" - ModeSingle = "single" - ModeSentinel = "sentinel" - ModeCluster = "cluster" + ModeSingle = string(config.SingleRedisMode) + ModeSentinel = string(config.SentinelRedisMode) + ModeCluster = string(config.ClusterRedisMode) ) type Configuration struct { @@ -31,40 +33,47 @@ type Configuration struct { TLS bool } +var configured atomic.Pointer[config.Redis] + +// Configure sets the connections Load reads. app.WithRedis calls it. +func Configure(redis config.Redis) { + configured.Store(&redis) +} + +// Load returns the named connection; the default when empty. func Load(connection string) (Configuration, error) { - prefix, err := connectionPrefix(connection) - if err != nil { - return Configuration{}, err + redis := configured.Load() + if redis == nil { + return Configuration{}, errors.New("[redis] no config: pass app.WithRedis") } - - configuration := Configuration{ - Mode: strings.ToLower(setting(prefix, "MODE", ModeSingle)), - MasterName: setting(prefix, "MASTER_NAME", ""), - Username: setting(prefix, "USERNAME", ""), - Password: setting(prefix, "PASSWORD", ""), - SentinelUsername: setting(prefix, "SENTINEL_USERNAME", ""), - SentinelPassword: setting(prefix, "SENTINEL_PASSWORD", ""), + if strings.TrimSpace(connection) == "" { + connection = DefaultConnection } - - addresses, err := loadAddresses(prefix) - if err != nil { - return Configuration{}, err + settings, found := redis.Connections[config.RedisConnectionType(connection)] + if !found { + return Configuration{}, fmt.Errorf("[redis] no connection %q in the config", connection) } - configuration.Addresses = addresses - database, err := strconv.Atoi(setting(prefix, "DATABASE", "0")) - if err != nil || database < 0 || database > 15 { - return Configuration{}, fmt.Errorf("%s_DATABASE must be between 0 and 15", prefix) + mode, addresses := ModeSingle, settings.Addresses + if settings.Mode != "" { + mode = settings.Mode.String() } - configuration.Database = database - - tlsEnabled, err := strconv.ParseBool(setting(prefix, "TLS", "false")) - if err != nil { - return Configuration{}, fmt.Errorf("%s_TLS must be true or false", prefix) + if len(addresses) == 0 && settings.Host != "" && settings.Port != "" { + addresses = []string{net.JoinHostPort(settings.Host, settings.Port)} } - configuration.TLS = tlsEnabled - if err := configuration.validate(prefix); err != nil { + configuration := Configuration{ + Mode: mode, + Addresses: addresses, + MasterName: settings.MasterName, + Username: settings.Username, + Password: settings.Password, + SentinelUsername: settings.SentinelUsername, + SentinelPassword: settings.SentinelPassword, + Database: settings.Database, + TLS: settings.TLS, + } + if err := configuration.validate(connection); err != nil { return Configuration{}, err } @@ -104,76 +113,27 @@ func (configuration Configuration) Options() *goredis.UniversalOptions { return options } -func (configuration Configuration) validate(prefix string) error { +func (configuration Configuration) validate(connection string) error { + if configuration.Database < 0 || configuration.Database > 15 { + return fmt.Errorf("[redis] connection %s: Database must be 0 to 15, got %d", connection, configuration.Database) + } + switch configuration.Mode { case ModeSingle: if len(configuration.Addresses) != 1 { - return fmt.Errorf("%s_ADDRESSES must contain one address in single mode", prefix) + return fmt.Errorf("[redis] connection %s: single mode needs exactly one address", connection) } case ModeSentinel: if configuration.MasterName == "" { - return fmt.Errorf("%s_MASTER_NAME is required in sentinel mode", prefix) + return fmt.Errorf("[redis] connection %s: sentinel mode needs a MasterName", connection) } case ModeCluster: if configuration.Database != 0 { - return fmt.Errorf("%s_DATABASE must be 0 in cluster mode", prefix) + return fmt.Errorf("[redis] connection %s: cluster mode needs Database 0", connection) } default: - return fmt.Errorf("%s_MODE must be single, sentinel, or cluster", prefix) + return fmt.Errorf("[redis] connection %s: unknown Mode %q", connection, configuration.Mode) } return nil } - -func loadAddresses(prefix string) ([]string, error) { - configured := setting(prefix, "ADDRESSES", "") - if configured == "" { - host := setting(prefix, "HOST", "") - port := setting(prefix, "PORT", "") - if host == "" || port == "" { - return nil, fmt.Errorf("%s_ADDRESSES or %s_HOST and %s_PORT are required", prefix, prefix, prefix) - } - configured = net.JoinHostPort(host, port) - } - - addresses := make([]string, 0) - for configuredAddress := range strings.SplitSeq(configured, ",") { - address := strings.TrimSpace(configuredAddress) - if address == "" { - continue - } - if _, _, err := net.SplitHostPort(address); err != nil { - return nil, fmt.Errorf("%s_ADDRESSES contains invalid address %q", prefix, address) - } - addresses = append(addresses, address) - } - if len(addresses) == 0 { - return nil, fmt.Errorf("%s_ADDRESSES must contain an address", prefix) - } - - return addresses, nil -} - -func setting(prefix, name, fallback string) string { - if value := strings.TrimSpace(os.Getenv(prefix + "_" + name)); value != "" { - return value - } - return fallback -} - -func connectionPrefix(connection string) (string, error) { - connection = strings.TrimSpace(connection) - if connection == "" || connection == DefaultConnection { - return "REDIS", nil - } - - for _, character := range connection { - if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' || - character >= '0' && character <= '9' || character == '_' { - continue - } - return "", fmt.Errorf("invalid Redis connection name %q", connection) - } - - return "REDIS_" + strings.ToUpper(connection), nil -} diff --git a/redis/connection_test.go b/redis/connection_test.go deleted file mode 100644 index 134274d..0000000 --- a/redis/connection_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package redis_test - -import ( - "context" - "os" - "testing" - "time" - - redisconnection "github.com/gonstruct/core/redis" -) - -func TestLoadUsesDefaultConnectionSettings(t *testing.T) { - configureSharedRedis(t) - - configuration, err := redisconnection.Load(redisconnection.DefaultConnection) - if err != nil { - t.Fatal(err) - } - if configuration.Mode != redisconnection.ModeSingle || - len(configuration.Addresses) != 1 || configuration.Addresses[0] != "shared-redis:6379" { - t.Fatalf("unexpected default Redis configuration: %#v", configuration) - } -} - -func TestLoadBuildsNamedSentinelConnection(t *testing.T) { - configureSharedRedis(t) - t.Setenv("REDIS_QUEUE_MODE", "sentinel") - t.Setenv("REDIS_QUEUE_ADDRESSES", "sentinel-1:26379, sentinel-2:26379, sentinel-3:26379") - t.Setenv("REDIS_QUEUE_MASTER_NAME", "example-queue") - t.Setenv("REDIS_QUEUE_SENTINEL_USERNAME", "sentinel-user") - t.Setenv("REDIS_QUEUE_SENTINEL_PASSWORD", "sentinel-secret") - - configuration, err := redisconnection.Load("queue") - if err != nil { - t.Fatal(err) - } - options := configuration.Options() - if configuration.Mode != redisconnection.ModeSentinel || len(options.Addrs) != 3 || - options.MasterName != "example-queue" || options.SentinelUsername != "sentinel-user" || - options.SentinelPassword != "sentinel-secret" { - t.Fatalf("unexpected Sentinel configuration: %#v", configuration) - } -} - -func TestLoadAllowsDedicatedCacheCluster(t *testing.T) { - configureSharedRedis(t) - t.Setenv("REDIS_CACHE_MODE", "cluster") - t.Setenv("REDIS_CACHE_ADDRESSES", "cache-1:6379,cache-2:6379,cache-3:6379") - t.Setenv("REDIS_CACHE_DATABASE", "0") - - configuration, err := redisconnection.Load("cache") - if err != nil { - t.Fatal(err) - } - options := configuration.Options() - if configuration.Mode != redisconnection.ModeCluster || !options.IsClusterMode || len(options.Addrs) != 3 { - t.Fatalf("unexpected cluster configuration: %#v", configuration) - } -} - -func TestLoadRejectsNonzeroClusterDatabase(t *testing.T) { - configureSharedRedis(t) - t.Setenv("REDIS_QUEUE_MODE", "cluster") - t.Setenv("REDIS_QUEUE_ADDRESSES", "queue-1:6379,queue-2:6379") - t.Setenv("REDIS_QUEUE_DATABASE", "2") - - if _, err := redisconnection.Load("queue"); err == nil || - err.Error() != "REDIS_QUEUE_DATABASE must be 0 in cluster mode" { - t.Fatalf("unexpected cluster database validation: %v", err) - } -} - -func TestLoadRejectsSentinelWithoutMasterName(t *testing.T) { - configureSharedRedis(t) - t.Setenv("REDIS_QUEUE_MODE", "sentinel") - t.Setenv("REDIS_QUEUE_ADDRESSES", "sentinel-1:26379") - t.Setenv("REDIS_QUEUE_MASTER_NAME", "") - - if _, err := redisconnection.Load("queue"); err == nil || - err.Error() != "REDIS_QUEUE_MASTER_NAME is required in sentinel mode" { - t.Fatalf("unexpected Sentinel validation: %v", err) - } -} - -func TestConfiguredClientConnectsToRedis(t *testing.T) { - if os.Getenv("REDIS_TOPOLOGY_INTEGRATION") != "1" { - t.Skip("set REDIS_TOPOLOGY_INTEGRATION=1 to run the Redis topology integration test") - } - - client, err := redisconnection.NewClient(redisconnection.DefaultConnection) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = client.Close() }) - - pingContext, cancel := context.WithTimeout(t.Context(), 2*time.Second) - defer cancel() - if err := client.Ping(pingContext).Err(); err != nil { - t.Fatalf("configured Redis client could not connect: %v", err) - } -} - -func configureSharedRedis(t *testing.T) { - t.Helper() - t.Setenv("REDIS_MODE", "single") - t.Setenv("REDIS_ADDRESSES", "") - t.Setenv("REDIS_HOST", "shared-redis") - t.Setenv("REDIS_PORT", "6379") - t.Setenv("REDIS_DATABASE", "0") - t.Setenv("REDIS_USERNAME", "") - t.Setenv("REDIS_PASSWORD", "") - t.Setenv("REDIS_MASTER_NAME", "") - t.Setenv("REDIS_SENTINEL_USERNAME", "") - t.Setenv("REDIS_SENTINEL_PASSWORD", "") - t.Setenv("REDIS_TLS", "false") -} diff --git a/routing/options.go b/routing/options.go index 5afea60..044c448 100644 --- a/routing/options.go +++ b/routing/options.go @@ -1,6 +1,9 @@ package routing -import "github.com/gonstruct/core/routing/response" +import ( + "github.com/gonstruct/core/config" + "github.com/gonstruct/core/routing/response" +) type Option func(*Routing) @@ -10,15 +13,10 @@ func WithRouters(routers ...func(*Engine)) Option { } } -func WithHealth(endpoint string) Option { +// WithConfig is required by Run. +func WithConfig(server config.Server) Option { return func(r *Routing) { - r.HealthEndpoint = endpoint - } -} - -func WithTrustedPlatform(platform string) Option { - return func(r *Routing) { - r.TrustedPlatform = platform + r.Config = &server } } diff --git a/routing/response/options.go b/routing/response/options.go index 3b5a5ff..b2c236c 100644 --- a/routing/response/options.go +++ b/routing/response/options.go @@ -3,7 +3,6 @@ package response import ( "fmt" "net/http" - "os" "sort" "github.com/gonstruct/core/routing/resource" @@ -13,6 +12,17 @@ import ( type ErrorsMap map[string]string +const showErrorsKey = "gonstruct.response.show-errors" + +// ShowErrors sets whether failed responses include their error. Routing +// adds it from config.Server.ShowErrors. +func ShowErrors(show bool) gin.HandlerFunc { + return func(context *gin.Context) { + context.Set(showErrorsKey, show) + context.Next() + } +} + type value[T any] struct { isSet bool value T @@ -86,7 +96,7 @@ func (options *responseOptions) resolve(context *gin.Context) { context.AbortWithStatusJSON(options.StatusCode, resource.Resource{ "message": resource.When(options.Message.isSet, func() string { return options.Message.value }), "code": resource.When(options.Code.isSet, func() string { return options.Code.value }), - "error": resource.When(options.Error.isSet && os.Getenv("APP_ENV") != "production", func() string { return options.Error.value.Error() }), + "error": resource.When(options.Error.isSet && context.GetBool(showErrorsKey), func() string { return options.Error.value.Error() }), "errors": resource.When(options.Errors.isSet, func() ErrorsMap { return options.Errors.value }), }) diff --git a/routing/routing.go b/routing/routing.go index f437b25..2f0a345 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -2,15 +2,16 @@ package routing import ( "context" + "errors" "fmt" "net" "net/http" "os" "os/signal" - "strconv" "syscall" "time" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/console" "github.com/gonstruct/core/routing/requestid" "github.com/gonstruct/core/routing/response" @@ -21,11 +22,10 @@ import ( ) type Routing struct { - Routers []func(*Engine) - Middlewares MiddlewareEngine - Recovery RecoveryHandler - HealthEndpoint string - TrustedPlatform string + Config *config.Server + Routers []func(*Engine) + Middlewares MiddlewareEngine + Recovery RecoveryHandler } type RecoveryHandler func(context *gin.Context, recovered any) response.Response @@ -44,8 +44,10 @@ func (r *Routing) Engine() *Engine { gin.SetMode(gin.ReleaseMode) router := NewEngine() + server := r.server() - router.TrustedPlatform = r.TrustedPlatform + router.TrustedPlatform = server.TrustedPlatform + router.Engine.Use(response.ShowErrors(server.ShowErrors)) router.ContextWithFallback = true router.RemoteIPHeaders = []string{ "CF-Connecting-IP", @@ -99,9 +101,9 @@ func (r *Routing) Engine() *Engine { return response.NotFound(response.WithMessage("Route not found")) }) - if r.HealthEndpoint != "" { + if server.HealthEndpoint != "" { startedAt := time.Now() - router.GET(r.HealthEndpoint, func(c *gin.Context) response.Response { + router.GET(server.HealthEndpoint, func(c *gin.Context) response.Response { return response.Success(response.WithRaw(map[string]any{ "status": "healthy", "uptime": time.Since(startedAt), @@ -118,26 +120,18 @@ func (r *Routing) Engine() *Engine { // Run serves until the process is asked to stop, by SIGTERM as a container // is or by an interrupt, then takes no new connections and lets the -// requests already in flight finish, for up to SHUTDOWN_TIMEOUT (30s when -// unset): a deploy that starts a new container beside this one and then -// stops it drops nothing. +// requests already in flight finish, for up to ShutdownTimeout: a deploy +// that starts a new container beside this one and then stops it drops +// nothing. func (r *Routing) Run() error { - engine := r.Engine() - - host := "0.0.0.0" - port := 80 - - if h := os.Getenv("HOST"); h != "" { - host = h + if r.Config == nil { + return errors.New("[routing] no config: pass routing.WithConfig") } + engine := r.Engine() - if p := os.Getenv("PORT"); p != "" { - if p, err := strconv.Atoi(p); err == nil { - port = p - } - } + settings := r.server() - hostWithPort := net.JoinHostPort(host, fmt.Sprint(port)) + hostWithPort := net.JoinHostPort(settings.Host, fmt.Sprint(settings.Port)) server := &http.Server{ Addr: hostWithPort, Handler: engine.Handler(), @@ -159,7 +153,7 @@ func (r *Routing) Run() error { case <-stopping.Done(): } - timeout := shutdownTimeout() + timeout := settings.ShutdownTimeout log.Info().Msgf("Stopping: finishing the requests in flight, for up to %s.", timeout) finishing, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() @@ -167,12 +161,24 @@ func (r *Routing) Run() error { return server.Shutdown(finishing) } -// shutdownTimeout is how long a stopping server waits for its requests in -// flight: SHUTDOWN_TIMEOUT as a duration, 30s when unset or unreadable. -func shutdownTimeout() time.Duration { - if value, err := time.ParseDuration(os.Getenv("SHUTDOWN_TIMEOUT")); err == nil && value > 0 { - return value +// server returns the config with defaults filled in. Engine works without +// a config, as tests use it. +func (r *Routing) server() config.Server { + host, port, timeout := "0.0.0.0", 80, 30*time.Second + if r.Config == nil { + return config.Server{Host: host, Port: port, ShutdownTimeout: timeout} + } + + server := *r.Config + if server.Host == "" { + server.Host = host + } + if server.Port == 0 { + server.Port = port + } + if server.ShutdownTimeout <= 0 { + server.ShutdownTimeout = timeout } - return 30 * time.Second + return server } diff --git a/scheduling/engine.go b/scheduling/engine.go index 8f594e7..c902306 100644 --- a/scheduling/engine.go +++ b/scheduling/engine.go @@ -3,7 +3,6 @@ package scheduling import ( "context" "fmt" - "os" "slices" "time" @@ -35,6 +34,9 @@ func NewSynchronousEngine() *Engine { type Engine struct { gocron.Scheduler + // Environment is matched against command.Environment(...). + Environment string + synchronous bool Commands []command.Command } @@ -50,8 +52,8 @@ func (e *Engine) Command(cmd command.Command, options ...command.Option) { opts := command.NewOptions(options...) - if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, os.Getenv("APP_ENV")) { - log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), os.Getenv("APP_ENV")) + if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, e.Environment) { + log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), e.Environment) return } diff --git a/scheduling/options.go b/scheduling/options.go index f6df823..c722005 100644 --- a/scheduling/options.go +++ b/scheduling/options.go @@ -2,6 +2,13 @@ package scheduling type Option func(*Scheduling) +// WithEnvironment is set by app.WithScheduling. +func WithEnvironment(environment string) Option { + return func(r *Scheduling) { + r.Environment = environment + } +} + func WithSchedulers(schedulers ...func(*Engine)) Option { return func(r *Scheduling) { r.Schedulers = append(r.Schedulers, schedulers...) diff --git a/scheduling/scheduling.go b/scheduling/scheduling.go index 540e7ba..fb21481 100644 --- a/scheduling/scheduling.go +++ b/scheduling/scheduling.go @@ -2,6 +2,8 @@ package scheduling type Scheduling struct { Schedulers []func(*Engine) + // Environment is matched against command.Environment(...). + Environment string } func New(options ...Option) *Scheduling { @@ -19,6 +21,7 @@ func (s *Scheduling) Run() error { if err != nil { return err } + scheduler.Environment = s.Environment for _, f := range s.Schedulers { f(scheduler) diff --git a/app/container_test.go b/tests/app/container_test.go similarity index 94% rename from app/container_test.go rename to tests/app/container_test.go index f9c9c6b..db3826b 100644 --- a/app/container_test.go +++ b/tests/app/container_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gonstruct/core/app" + "github.com/gonstruct/core/config" ) type service struct{ built int } @@ -13,9 +14,8 @@ type service struct{ built int } // entrypoint does. func boot(t *testing.T, bindings ...app.Binding) { t.Helper() - t.Setenv("APP_ENV", "testing") - app.New(app.WithSingletons(app.Singletons(bindings...))).SetInstance() + app.New(config.App{Environment: config.TestingEnvironment}, app.WithSingletons(app.Singletons(bindings...))).SetInstance() } func TestSingletonBuildsOnceAndShares(t *testing.T) { 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 bd80a9b..4ec1280 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() diff --git a/tests/redis/connection_test.go b/tests/redis/connection_test.go new file mode 100644 index 0000000..ae878b7 --- /dev/null +++ b/tests/redis/connection_test.go @@ -0,0 +1,107 @@ +package redis_test + +import ( + "context" + "os" + "strings" + "testing" + "time" + + "github.com/gonstruct/core/config" + redisconnection "github.com/gonstruct/core/redis" +) + +func configure(connections map[config.RedisConnectionType]config.RedisConnection) { + redisconnection.Configure(config.Redis{Connections: connections}) +} + +func TestAConnectionNeedsAConfig(t *testing.T) { + // Before any Configure in this process: the first test to run. + if _, err := redisconnection.Load("default"); err == nil || !strings.Contains(err.Error(), "no config") { + t.Fatalf("expected no config, got %v", err) + } +} + +func TestLoadUsesTheDefaultConnection(t *testing.T) { + configure(map[config.RedisConnectionType]config.RedisConnection{ + config.DefaultRedisConnection: {Host: "shared-redis", Port: "6379"}, + }) + + configuration, err := redisconnection.Load("") + if err != nil { + t.Fatal(err) + } + if configuration.Mode != redisconnection.ModeSingle || len(configuration.Addresses) != 1 || configuration.Addresses[0] != "shared-redis:6379" { + t.Fatalf("unexpected default Redis configuration: %#v", configuration) + } +} + +func TestLoadBuildsANamedSentinelConnection(t *testing.T) { + configure(map[config.RedisConnectionType]config.RedisConnection{ + "queue": { + Mode: config.SentinelRedisMode, + Addresses: []string{"sentinel-1:26379", "sentinel-2:26379", "sentinel-3:26379"}, + MasterName: "example-queue", + SentinelUsername: "sentinel-user", + SentinelPassword: "sentinel-secret", + }, + }) + + configuration, err := redisconnection.Load("queue") + if err != nil { + t.Fatal(err) + } + options := configuration.Options() + if len(options.Addrs) != 3 || options.MasterName != "example-queue" || options.SentinelUsername != "sentinel-user" || + options.SentinelPassword != "sentinel-secret" { + t.Fatalf("unexpected Sentinel configuration: %#v", configuration) + } +} + +func TestLoadAllowsACluster(t *testing.T) { + configure(map[config.RedisConnectionType]config.RedisConnection{ + "cache": {Mode: config.ClusterRedisMode, Addresses: []string{"cache-1:6379", "cache-2:6379", "cache-3:6379"}}, + }) + + configuration, err := redisconnection.Load("cache") + if err != nil || !configuration.Options().IsClusterMode || len(configuration.Options().Addrs) != 3 { + t.Fatalf("unexpected cluster configuration: %#v (%v)", configuration, err) + } +} + +func TestLoadRefuses(t *testing.T) { + configure(map[config.RedisConnectionType]config.RedisConnection{ + "no-address": {}, + "no-master": {Mode: config.SentinelRedisMode, Addresses: []string{"sentinel-1:26379"}}, + "cluster-db": {Mode: config.ClusterRedisMode, Addresses: []string{"cache-1:6379"}, Database: 2}, + "bad-mode": {Mode: "ring", Addresses: []string{"a:1"}}, + "bad-db": {Host: "a", Port: "1", Database: 16}, + }) + + for _, name := range []string{"no-address", "no-master", "cluster-db", "bad-mode", "bad-db", "missing"} { + if _, err := redisconnection.Load(name); err == nil { + t.Errorf("expected %s refused", name) + } + } +} + +func TestConfiguredClientConnectsToRedis(t *testing.T) { + if os.Getenv("REDIS_TOPOLOGY_INTEGRATION") != "1" { + t.Skip("set REDIS_TOPOLOGY_INTEGRATION=1, REDIS_HOST and REDIS_PORT to run the Redis topology integration test") + } + configure(map[config.RedisConnectionType]config.RedisConnection{ + config.DefaultRedisConnection: {Host: os.Getenv("REDIS_HOST"), Port: os.Getenv("REDIS_PORT")}, + }) + + client, err := redisconnection.NewClient(redisconnection.DefaultConnection) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = client.Close() }) + + pingContext, cancel := context.WithTimeout(t.Context(), 2*time.Second) + defer cancel() + if err := client.Ping(pingContext).Err(); err != nil { + t.Fatalf("configured Redis client could not connect: %v", err) + } +} diff --git a/tests/routing/errors_test.go b/tests/routing/errors_test.go new file mode 100644 index 0000000..17525b9 --- /dev/null +++ b/tests/routing/errors_test.go @@ -0,0 +1,31 @@ +package routing_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gonstruct/core/config" + "github.com/gonstruct/core/routing" + "github.com/gonstruct/core/routing/response" + + "github.com/gin-gonic/gin" +) + +func TestFailedResponsesShowTheirErrorOnlyWhenAsked(t *testing.T) { + for _, show := range []bool{true, false} { + engine := routing.New(routing.WithConfig(config.Server{ShowErrors: show}), routing.WithRouters(func(engine *routing.Engine) { + engine.GET("/broken", func(*gin.Context) response.Response { + return response.Error(errors.New("the database is down")) + }) + })).Engine() + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/broken", nil)) + + if said := strings.Contains(recorder.Body.String(), "the database is down"); said != show { + t.Errorf("showing errors %v: the response said it %v: %s", show, said, recorder.Body.String()) + } + } +} diff --git a/routing/routing_test.go b/tests/routing/routing_test.go similarity index 65% rename from routing/routing_test.go rename to tests/routing/routing_test.go index 34373bb..6d13c92 100644 --- a/routing/routing_test.go +++ b/tests/routing/routing_test.go @@ -5,11 +5,14 @@ import ( "io" "net" "net/http" + "net/http/httptest" "os" + "strings" "syscall" "testing" "time" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/routing" "github.com/gonstruct/core/routing/response" @@ -27,12 +30,10 @@ func TestRunFinishesTheRequestsInFlightWhenStopped(t *testing.T) { if err := listener.Close(); err != nil { t.Fatal(err) } - t.Setenv("HOST", "127.0.0.1") - t.Setenv("PORT", fmt.Sprint(port)) - t.Setenv("SHUTDOWN_TIMEOUT", "5s") started := make(chan struct{}) - server := routing.New(routing.WithRouters(func(engine *routing.Engine) { + listening := config.Server{Host: "127.0.0.1", Port: port, ShutdownTimeout: 5 * time.Second} + server := routing.New(routing.WithConfig(listening), routing.WithRouters(func(engine *routing.Engine) { engine.GET("/slow", func(*gin.Context) response.Response { close(started) time.Sleep(300 * time.Millisecond) @@ -93,3 +94,25 @@ func TestRunFinishesTheRequestsInFlightWhenStopped(t *testing.T) { t.Fatal("expected the stopped server to take no new connections") } } + +func TestRunNeedsAConfig(t *testing.T) { + if err := routing.New().Run(); err == nil || !strings.Contains(err.Error(), "no config") { + t.Fatalf("expected no config, got %v", err) + } +} + +func TestTheHealthEndpointIsTheConfigs(t *testing.T) { + healthy := routing.New(routing.WithConfig(config.Server{HealthEndpoint: "/health"})).Engine().Handler() + recorder := httptest.NewRecorder() + healthy.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/health", nil)) + if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "healthy") { + t.Fatalf("expected healthy, got %d: %s", recorder.Code, recorder.Body) + } + + bare := routing.New(routing.WithConfig(config.Server{})).Engine().Handler() + recorder = httptest.NewRecorder() + bare.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/health", nil)) + if recorder.Code != http.StatusNotFound { + t.Fatalf("expected no health endpoint, got %d", recorder.Code) + } +} diff --git a/tests/scheduling/environment_test.go b/tests/scheduling/environment_test.go new file mode 100644 index 0000000..ab19e6b --- /dev/null +++ b/tests/scheduling/environment_test.go @@ -0,0 +1,34 @@ +package scheduling_test + +import ( + "context" + "testing" + + "github.com/gonstruct/core/scheduling" + "github.com/gonstruct/core/scheduling/command" +) + +type nightly struct{} + +func (nightly) Name() string { return "nightly" } +func (nightly) Handle(context.Context) error { return nil } + +func TestCommandsRunInTheirEnvironmentsOnly(t *testing.T) { + t.Setenv("APP_ENV", "production") + + for _, each := range []struct { + environment string + registered bool + }{{"production", true}, {"staging", false}} { + engine, err := scheduling.NewEngine() + if err != nil { + t.Fatal(err) + } + engine.Environment = each.environment + engine.Command(nightly{}, command.EveryMinute(), command.Environment[string]("production")) + + if got := len(engine.Jobs()) > 0; got != each.registered { + t.Errorf("in %s: expected registered %v, got %v", each.environment, each.registered, got) + } + } +}