Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat: add POSTA_REDIS_URL for redis connection

Mike Kosulind6517554e837
diff --git a/.env.example b/.env.example
index 6e5dde2..9564763 100644
--- a/.env.example
+++ b/.env.example
@@ -15,8 +15,12 @@ POSTA_DB_SSL_MODE=disable
POSTA_DB_URL=
# Redis
+# URL overrides the settings below
+POSTA_REDIS_URL=
POSTA_REDIS_ADDR=localhost:6379
+POSTA_REDIS_USERNAME=
POSTA_REDIS_PASSWORD=
+POSTA_REDIS_DB=0
# JWT signing secret — change this in production!
POSTA_JWT_SECRET=change-me-in-production
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index c63ebab..a5950c3 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -145,7 +145,7 @@ func runServer(cli *okapicli.CLI) {
}
if !cfg.DevMode {
- res.producer = worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ res.producer = worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)
if cfg.EmbeddedWorker {
startEmbeddedWorker(res.db, cfg, res.blobStore, notifier, inboundBus)
}
@@ -377,7 +377,7 @@ func startEmbeddedWorker(db *gorm.DB,
}
srv := asynq.NewServer(
- asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
+ cfg.Redis.AsynqRedisOpt(),
asynq.Config{
Concurrency: cfg.WorkerConcurrency,
Queues: map[string]int{
@@ -390,7 +390,7 @@ func startEmbeddedWorker(db *gorm.DB,
)
// Campaign processor
- campaignProducer := worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ campaignProducer := worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)
trackingRepo := repositories.NewTrackingRepository(db)
trackingService := tracking.NewService(trackingRepo, cfg.AppWebURL, []byte(cfg.JWTSecret))
campaignDispatcher := newWebhookDispatcher(db, cfg)
@@ -432,7 +432,7 @@ func startEmbeddedWorker(db *gorm.DB,
inboundHandler.OnFailed(metrics.IncrementInboundFailed)
mux.HandleFunc(worker.TypeInboundProcess, inboundHandler.ProcessTask)
- parseProducer := worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ parseProducer := worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)
parseSvc := newInboundServiceForWorker(db, cfg, blobStore, parseProducer, bus)
parseHandler := worker.NewInboundParseHandler(
repositories.NewInboundEmailRepository(db),
@@ -461,10 +461,7 @@ func initCronManager(
blobStore blob.Store,
producer *worker.Producer,
) *cronpkg.Manager {
- cronClient := asynq.NewClient(asynq.RedisClientOpt{
- Addr: cfg.Redis.Addr,
- Password: cfg.Redis.Password,
- })
+ cronClient := asynq.NewClient(cfg.Redis.AsynqRedisOpt())
settingsProvider := settings.NewProvider(repositories.NewSettingRepository(db))
manager := cronpkg.NewManager(cronClient)
diff --git a/cmd/posta/worker.go b/cmd/posta/worker.go
index 496afb2..4483bac 100644
--- a/cmd/posta/worker.go
+++ b/cmd/posta/worker.go
@@ -117,7 +117,7 @@ func runWorker() error {
}
srv := asynq.NewServer(
- asynq.RedisClientOpt{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password},
+ cfg.Redis.AsynqRedisOpt(),
asynq.Config{
Concurrency: cfg.WorkerConcurrency,
Queues: map[string]int{
@@ -130,7 +130,7 @@ func runWorker() error {
)
// Campaign processor
- campaignProducer := worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ campaignProducer := worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)
trackingRepo := repositories.NewTrackingRepository(db)
trackingService := tracking.NewService(trackingRepo, cfg.AppWebURL, []byte(cfg.JWTSecret))
campaignDispatcher := newWebhookDispatcher(db, cfg)
@@ -178,7 +178,7 @@ func runWorker() error {
inboundHandler.OnFailed(metrics.IncrementInboundFailed)
mux.HandleFunc(worker.TypeInboundProcess, inboundHandler.ProcessTask)
- parseProducer := worker.NewProducer(cfg.Redis.Addr, cfg.Redis.Password, cfg.WorkerMaxRetries)
+ parseProducer := worker.NewProducer(cfg.Redis.AsynqRedisOpt(), cfg.WorkerMaxRetries)
parseBus := eventbus.New(repositories.NewEventRepository(db))
parseSvc := inbound.NewService(
repositories.NewInboundEmailRepository(db),
diff --git a/docs/docs/getting-started/configuration.md b/docs/docs/getting-started/configuration.md
index 2ca1708..851974d 100644
--- a/docs/docs/getting-started/configuration.md
+++ b/docs/docs/getting-started/configuration.md
@@ -35,8 +35,11 @@ Posta is configured via environment variables. All variables are prefixed with `
| Variable | Default | Description |
|----------|---------|-------------|
-| `POSTA_REDIS_ADDR` | `localhost:6379` | Redis address |
+| `POSTA_REDIS_URL` | — | Full connection string, e.g. `redis://user:pass@host:6379/2`. When set, it overrides `POSTA_REDIS_ADDR`, `POSTA_REDIS_USERNAME`, `POSTA_REDIS_PASSWORD` and `POSTA_REDIS_DB`. |
+| `POSTA_REDIS_ADDR` | `localhost:6379` | Redis address (`host:port`) |
+| `POSTA_REDIS_USERNAME` | — | Redis ACL username (Redis 6+) |
| `POSTA_REDIS_PASSWORD` | — | Redis password |
+| `POSTA_REDIS_DB` | `0` | Redis database number to select |
## Security
diff --git a/examples/.env.example b/examples/.env.example
index 76c29e2..c83d193 100644
--- a/examples/.env.example
+++ b/examples/.env.example
@@ -15,8 +15,12 @@ POSTA_DB_SSL_MODE=disable
POSTA_DB_URL=
# Redis
+# URL overrides the settings below
+POSTA_REDIS_URL=
POSTA_REDIS_ADDR=localhost:6379
+POSTA_REDIS_USERNAME=
POSTA_REDIS_PASSWORD=
+POSTA_REDIS_DB=0
# JWT signing secret — change this in production!
POSTA_JWT_SECRET=change-me-in-production
diff --git a/internal/config/config.go b/internal/config/config.go
index f527081..65eeb62 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -23,6 +23,7 @@ import (
errorhandlers "github.com/goposta/posta/internal/error_handlers"
"github.com/goposta/posta/internal/storage"
+ "github.com/hibiken/asynq"
goutils "github.com/jkaninda/go-utils"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
@@ -145,8 +146,56 @@ type DatabaseConfig struct {
type RedisConfig struct {
Client *redis.Client
Addr string
+ Username string
Password string
+ DB int
+ // URL, when set, overrides the discrete fields above (e.g. redis://user:pass@host:6379/2).
+ URL string
}
+
+// newRedisConfig reads Redis settings from the env; POSTA_REDIS_URL, if set,
+// is parsed and overrides the discrete POSTA_REDIS_* vars (mirrors POSTA_DB_URL).
+func newRedisConfig() RedisConfig {
+ rc := RedisConfig{
+ Addr: goutils.Env("POSTA_REDIS_ADDR", "localhost:6379"),
+ Username: goutils.Env("POSTA_REDIS_USERNAME", ""),
+ Password: goutils.Env("POSTA_REDIS_PASSWORD", ""),
+ DB: goutils.EnvInt("POSTA_REDIS_DB", 0),
+ URL: goutils.Env("POSTA_REDIS_URL", ""),
+ }
+ if rc.URL != "" {
+ opt, err := redis.ParseURL(rc.URL)
+ if err != nil {
+ logger.Fatal("invalid POSTA_REDIS_URL", "error", err)
+ }
+ rc.Addr = opt.Addr
+ rc.Username = opt.Username
+ rc.Password = opt.Password
+ rc.DB = opt.DB
+ }
+ return rc
+}
+
+// RedisOptions returns the go-redis client options.
+func (r RedisConfig) RedisOptions() *redis.Options {
+ return &redis.Options{
+ Addr: r.Addr,
+ Username: r.Username,
+ Password: r.Password,
+ DB: r.DB,
+ }
+}
+
+// AsynqRedisOpt returns the Asynq Redis connection options.
+func (r RedisConfig) AsynqRedisOpt() asynq.RedisClientOpt {
+ return asynq.RedisClientOpt{
+ Addr: r.Addr,
+ Username: r.Username,
+ Password: r.Password,
+ DB: r.DB,
+ }
+}
+
type JWTConfig struct {
Secret string
Issuer string
@@ -171,10 +220,7 @@ func New() *Config {
sslMode: goutils.Env("POSTA_DB_SSL_MODE", "disable"),
url: goutils.Env("POSTA_DB_URL", ""),
},
- Redis: RedisConfig{
- Addr: goutils.Env("POSTA_REDIS_ADDR", "localhost:6379"),
- Password: goutils.Env("POSTA_REDIS_PASSWORD", ""),
- },
+ Redis: newRedisConfig(),
Port: goutils.EnvInt("POSTA_PORT", 9000),
Env: goutils.Env("POSTA_ENV", "dev"),
JWTSecret: goutils.Env("POSTA_JWT_SECRET", "change-me-in-production"),
@@ -367,7 +413,7 @@ func (c *Config) InitStorage() {
}
c.Database.DB = dbConn
- redisClient, err := storage.NewRedis(c.Redis.Addr, c.Redis.Password)
+ redisClient, err := storage.NewRedis(c.Redis.RedisOptions())
if err != nil {
logger.Fatal("failed to connect to redis", "error", err)
}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
new file mode 100644
index 0000000..9f0965a
--- /dev/null
+++ b/internal/config/config_test.go
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package config
+
+import (
+ "os"
+ "testing"
+)
+
+// clearRedisEnv unsets every POSTA_REDIS_* var (Setenv registers restore,
+// Unsetenv removes it so goutils.Env falls back to its default).
+func clearRedisEnv(t *testing.T) {
+ for _, k := range []string{
+ "POSTA_REDIS_ADDR",
+ "POSTA_REDIS_USERNAME",
+ "POSTA_REDIS_PASSWORD",
+ "POSTA_REDIS_DB",
+ "POSTA_REDIS_URL",
+ } {
+ t.Setenv(k, "")
+ os.Unsetenv(k)
+ }
+}
+
+// TestNewRedisConfigBackwardCompatible: legacy addr/password (or nothing) keeps
+// the same connection settings as before DB/URL support was added.
+func TestNewRedisConfigBackwardCompatible(t *testing.T) {
+ t.Run("defaults unchanged", func(t *testing.T) {
+ clearRedisEnv(t)
+ rc := newRedisConfig()
+ if rc.Addr != "localhost:6379" {
+ t.Fatalf("Addr = %q, want localhost:6379", rc.Addr)
+ }
+ if rc.Password != "" || rc.Username != "" {
+ t.Fatalf("credentials = %q/%q, want empty", rc.Username, rc.Password)
+ }
+ if rc.DB != 0 {
+ t.Fatalf("DB = %d, want 0", rc.DB)
+ }
+ })
+
+ t.Run("legacy addr+password still honored", func(t *testing.T) {
+ clearRedisEnv(t)
+ t.Setenv("POSTA_REDIS_ADDR", "redis.internal:6380")
+ t.Setenv("POSTA_REDIS_PASSWORD", "s3cret")
+ rc := newRedisConfig()
+ if rc.Addr != "redis.internal:6380" || rc.Password != "s3cret" {
+ t.Fatalf("got %q/%q", rc.Addr, rc.Password)
+ }
+ if rc.DB != 0 {
+ t.Fatalf("DB = %d, want 0", rc.DB)
+ }
+ })
+}
+
+// TestNewRedisConfigDB verifies the new POSTA_REDIS_DB selector.
+func TestNewRedisConfigDB(t *testing.T) {
+ clearRedisEnv(t)
+ t.Setenv("POSTA_REDIS_ADDR", "localhost:6379")
+ t.Setenv("POSTA_REDIS_DB", "3")
+ rc := newRedisConfig()
+ if rc.DB != 3 {
+ t.Fatalf("DB = %d, want 3", rc.DB)
+ }
+ if got := rc.RedisOptions().DB; got != 3 {
+ t.Fatalf("RedisOptions().DB = %d, want 3", got)
+ }
+ if got := rc.AsynqRedisOpt().DB; got != 3 {
+ t.Fatalf("AsynqRedisOpt().DB = %d, want 3", got)
+ }
+}
+
+// TestNewRedisConfigURL: POSTA_REDIS_URL is parsed, overrides the discrete
+// fields, and flows through both option builders.
+func TestNewRedisConfigURL(t *testing.T) {
+ clearRedisEnv(t)
+ // Discrete values are set but must be overridden by the URL.
+ t.Setenv("POSTA_REDIS_ADDR", "ignored:1111")
+ t.Setenv("POSTA_REDIS_PASSWORD", "ignored")
+ t.Setenv("POSTA_REDIS_URL", "redis://alice:[email protected]:6390/5")
+
+ rc := newRedisConfig()
+ if rc.Addr != "cache.example.com:6390" {
+ t.Fatalf("Addr = %q", rc.Addr)
+ }
+ if rc.Username != "alice" || rc.Password != "hunter2" {
+ t.Fatalf("creds = %q/%q", rc.Username, rc.Password)
+ }
+ if rc.DB != 5 {
+ t.Fatalf("DB = %d, want 5", rc.DB)
+ }
+
+ ro := rc.RedisOptions()
+ if ro.Addr != "cache.example.com:6390" || ro.Username != "alice" || ro.Password != "hunter2" || ro.DB != 5 {
+ t.Fatalf("RedisOptions mismatch: %+v", ro)
+ }
+ ao := rc.AsynqRedisOpt()
+ if ao.Addr != "cache.example.com:6390" || ao.Username != "alice" || ao.Password != "hunter2" || ao.DB != 5 {
+ t.Fatalf("AsynqRedisOpt mismatch: %+v", ao)
+ }
+}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index cf5387a..95443a9 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -206,10 +206,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
userHandler := handlers.NewUserHandler(userRepo, cfg.JWTSecret, userSeeder, bus)
userHandler.SetSettings(settingsProvider)
userHandler.SetMigrator(db, migrator)
- inspector := asynq.NewInspector(asynq.RedisClientOpt{
- Addr: cfg.Redis.Addr,
- Password: cfg.Redis.Password,
- })
+ inspector := asynq.NewInspector(cfg.Redis.AsynqRedisOpt())
// Seed default platform settings
go seeder.SeedDefaultSettings(settingRepo)
diff --git a/internal/storage/redis.go b/internal/storage/redis.go
index 30b122b..6055403 100644
--- a/internal/storage/redis.go
+++ b/internal/storage/redis.go
@@ -25,11 +25,8 @@ import (
"github.com/redis/go-redis/v9"
)
-func NewRedis(addr, password string) (*redis.Client, error) {
- client := redis.NewClient(&redis.Options{
- Addr: addr,
- Password: password,
- })
+func NewRedis(opts *redis.Options) (*redis.Client, error) {
+ client := redis.NewClient(opts)
if err := client.Ping(context.Background()).Err(); err != nil {
return nil, fmt.Errorf("failed to connect to redis: %w", err)
diff --git a/internal/worker/producer.go b/internal/worker/producer.go
index 0c45d8e..944f992 100644
--- a/internal/worker/producer.go
+++ b/internal/worker/producer.go
@@ -31,11 +31,8 @@ type Producer struct {
maxRetries int
}
-func NewProducer(redisAddr, redisPassword string, maxRetries int) *Producer {
- client := asynq.NewClient(asynq.RedisClientOpt{
- Addr: redisAddr,
- Password: redisPassword,
- })
+func NewProducer(redisOpt asynq.RedisClientOpt, maxRetries int) *Producer {
+ client := asynq.NewClient(redisOpt)
return &Producer{
client: client,
maxRetries: maxRetries,