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
10 changes: 10 additions & 0 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,14 @@ func WithSeeders(seeders seeder.Seeders) option {
}
}

// WithRedis registers the app's Redis connections, which the queue and the
// cache use by name.
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 Down
38 changes: 34 additions & 4 deletions config/redis.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,49 @@
package config

// Redis is the Redis connections the app uses, by name, handed to
// app.WithRedis: the queue and the cache name the one they use.
type Redis struct {
Options any
Connections map[RedisConnectionType]RedisConnection
}

// RedisConnection is one Redis: a single server, a Sentinel-watched one, or
// a cluster.
type RedisConnection struct {
Host string
Port string
Username string
Password string
// Mode is single (the default when empty), sentinel or cluster.
Mode redisMode
// Addresses is its servers, or its sentinels; or Host and Port for one.
Addresses []string
Host string
Port string
// MasterName is the master the sentinels watch, in sentinel mode.
MasterName string
Username string
Password string
SentinelUsername string
SentinelPassword string
// Database is 0 to 15; always 0 in cluster mode.
Database int
TLS bool
}

// redisMode is how a Redis connection reaches its servers.
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

const (
Expand Down
140 changes: 51 additions & 89 deletions redis/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,23 @@ 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"
)

const (
DefaultConnection = "default"

ModeSingle = "single"
ModeSentinel = "sentinel"
ModeCluster = "cluster"
ModeSingle = string(config.SingleRedisMode)
ModeSentinel = string(config.SentinelRedisMode)
ModeCluster = string(config.ClusterRedisMode)
)

type Configuration struct {
Expand All @@ -31,40 +33,49 @@ type Configuration struct {
TLS bool
}

// configured is the app's connections, by name.
var configured atomic.Pointer[config.Redis]

// Configure registers the app's Redis connections. app.WithRedis calls it.
func Configure(redis config.Redis) {
configured.Store(&redis)
}

// Load is the connection by that name, as configured: the default one 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
}

Expand Down Expand Up @@ -104,76 +115,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 has Database %d: 0 to 15", 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 needs one address in single mode", connection)
}
case ModeSentinel:
if configuration.MasterName == "" {
return fmt.Errorf("%s_MASTER_NAME is required in sentinel mode", prefix)
return fmt.Errorf("[redis] connection %s needs a MasterName in sentinel mode", 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 must use Database 0 in cluster mode", connection)
}
default:
return fmt.Errorf("%s_MODE must be single, sentinel, or cluster", prefix)
return fmt.Errorf("[redis] connection %s has Mode %q: single, sentinel or cluster", 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
}
116 changes: 0 additions & 116 deletions redis/connection_test.go

This file was deleted.

Loading