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
3 changes: 1 addition & 2 deletions cmd/ingest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
"github.com/metabrainz/synapse/internal/observability"
"github.com/metabrainz/synapse/internal/store"
"github.com/metabrainz/synapse/internal/store/subscriptions"
"github.com/redis/go-redis/v9"
)

func main() {
Expand Down Expand Up @@ -87,7 +86,7 @@ func main() {
fan := fanout.New(cache, adapter.MaxAttemptsFor, reg).
WithExpiry(fanout.NewExpiry(cfg.TenantInAppRetentionDays()))
// No ping: publishing is best-effort, ingest must not depend on Redis.
rdb := redis.NewClient(&redis.Options{Addr: cfg.Redis.Addr, Password: cfg.Redis.Password, DB: cfg.Redis.DB})
rdb := store.NewRedisClient(cfg.Redis)
defer rdb.Close()

consumer := ingest.NewConsumer(pool, fan, reg, live.NewPublisher(rdb))
Expand Down
1 change: 1 addition & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ redis:
addr: localhost:6379
password: ""
db: 0
namespace: ""

oauth:
client_id: ""
Expand Down
8 changes: 5 additions & 3 deletions deploy/config.yaml.ctmpl
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,20 @@ http:
postgres:
host: {{ if $pg }}{{ with index $pg 0 }}{{ .Address }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_pgbouncer-master{{ end }}
port: {{ if $pg }}{{ with index $pg 0 }}{{ .Port }}{{ end }}{{ else }}0{{ end }}
user: synapse
user: {{ template "KEY" "pg_user" }}
password: "{{ template "KEY" "pg_password" }}"
dbname: synapse
dbname: {{ template "KEY" "pg_dbname" }}
sslmode: disable
pgbouncer: true
direct_dsn: "postgres://synapse:{{ template "KEY" "pg_password" }}@{{ if $pgdirect }}{{ with index $pgdirect 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_virtual-postgres-master{{ end }}/synapse?sslmode=disable"
direct_dsn: "postgres://{{ template "KEY" "pg_user" }}:{{ template "KEY" "pg_password" }}@{{ if $pgdirect }}{{ with index $pgdirect 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_virtual-postgres-master{{ end }}/{{ template "KEY" "pg_dbname" }}?sslmode=disable"

{{ $redis := service "synapse-redis" -}}
redis:
addr: {{ if $redis }}{{ with index $redis 0 }}{{ .Address }}:{{ .Port }}{{ end }}{{ else }}SERVICEDOESNOTEXIST_synapse-redis{{ end }}
password: ""
db: 0
# Environments that share this Redis set a namespace so their keys and channels stay apart.
namespace: "{{ template "OPTKEY" "redis_namespace" }}"

{{ $rmq := service "rabbitmq-listenbrainz" -}}
rabbitmq:
Expand Down
10 changes: 4 additions & 6 deletions e2e/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ import (
"time"

"github.com/jackc/pgx/v5/pgxpool"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/redis/go-redis/v9"

"github.com/metabrainz/synapse/internal/adapter"
"github.com/metabrainz/synapse/internal/api"
"github.com/metabrainz/synapse/internal/broker"
Expand All @@ -40,6 +37,7 @@ import (
"github.com/metabrainz/synapse/internal/store/usertenant"
"github.com/metabrainz/synapse/internal/worker"
"github.com/metabrainz/synapse/testutil"
amqp "github.com/rabbitmq/amqp091-go"
)

const (
Expand All @@ -52,7 +50,7 @@ type env struct {
ctx context.Context
t *testing.T
pool *pgxpool.Pool
rdb *redis.Client
rdb *store.Redis
server *httptest.Server
amqpURL string
apiKey string // static tenant API key for testTenantID
Expand All @@ -66,7 +64,7 @@ type env struct {
// wires the full HTTP router, and returns a ready env. Cleanup is registered via
// t.Cleanup in LIFO order: cancel → pool.Close → container teardown.
// setup builds the test environment; opts adjust the API config.
func setup(t *testing.T, opts ...func(*api.Config, *redis.Client)) *env {
func setup(t *testing.T, opts ...func(*api.Config, *store.Redis)) *env {
t.Helper()

ctx, cancel := context.WithCancel(context.Background())
Expand Down Expand Up @@ -106,7 +104,7 @@ func setup(t *testing.T, opts ...func(*api.Config, *redis.Client)) *env {
t.Fatalf("rabbitmq topology: %v", err)
}

rdb, err := store.NewRedis(ctx, config.RedisConfig{Addr: rdbAddr})
rdb, err := store.NewRedis(ctx, config.RedisConfig{Addr: rdbAddr, Namespace: "e2e"})
if err != nil {
t.Fatalf("redis client: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion e2e/live_publish_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func (e *env) subscribe(user string) <-chan live.Nudge {
e.t.Helper()
sub := e.rdb.Subscribe(e.ctx, live.Channel(user))
sub := e.rdb.Subscribe(e.ctx, live.Channel(e.rdb.Namespace, user))
e.t.Cleanup(func() { sub.Close() })
if _, err := sub.Receive(e.ctx); err != nil {
e.t.Fatalf("subscribe: %v", err)
Expand Down
5 changes: 2 additions & 3 deletions e2e/me_cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import (
"strings"
"testing"

"github.com/redis/go-redis/v9"

"github.com/metabrainz/synapse/internal/api"
"github.com/metabrainz/synapse/internal/oauth"
"github.com/metabrainz/synapse/internal/store"
)

const (
Expand Down Expand Up @@ -108,7 +107,7 @@ func TestMeCORSPreflight(t *testing.T) {
func TestMeCORSTenantScoped(t *testing.T) {
const bbOrigin = "https://bookbrainz.org"
// The registry knows only testTenantID; "bookbrainz" exists only in the origins config.
e := setup(t, func(c *api.Config, _ *redis.Client) {
e := setup(t, func(c *api.Config, _ *store.Redis) {
c.StreamOrigins = map[string][]string{testTenantID: {lbOrigin}, "bookbrainz": {bbOrigin}}
})
tok := e.token("user-a")
Expand Down
7 changes: 3 additions & 4 deletions e2e/stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ import (
"testing"
"time"

"github.com/redis/go-redis/v9"

"github.com/metabrainz/synapse/internal/api"
"github.com/metabrainz/synapse/internal/live"
"github.com/metabrainz/synapse/internal/ratelimit"
"github.com/metabrainz/synapse/internal/store"
)

const lbOrigin = "https://listenbrainz.org"
Expand Down Expand Up @@ -251,7 +250,7 @@ func TestStreamIntrospectionDown(t *testing.T) {
}

func TestStreamOpensAreRateLimited(t *testing.T) {
e := setup(t, func(c *api.Config, rdb *redis.Client) { c.Limiter = ratelimit.New(rdb, 2, 1) })
e := setup(t, func(c *api.Config, rdb *store.Redis) { c.Limiter = ratelimit.New(rdb, 2, 1) })
tok := e.token("alice")
for range 2 {
e.openOK(tenantStreamPath, tok)
Expand Down Expand Up @@ -376,7 +375,7 @@ func TestStreamEndToEnd(t *testing.T) {
}

func TestStreamDeliversToManyStreams(t *testing.T) {
e := setup(t, func(c *api.Config, _ *redis.Client) { c.StreamLifetime = time.Minute })
e := setup(t, func(c *api.Config, _ *store.Redis) { c.StreamLifetime = time.Minute })
const users = 2000
got := make([]chan string, users)
var wg sync.WaitGroup
Expand Down
4 changes: 2 additions & 2 deletions internal/adapter/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (

"github.com/go-chi/chi/v5"
"github.com/metabrainz/synapse/internal/fanout"
"github.com/metabrainz/synapse/internal/store"
"github.com/metabrainz/synapse/internal/store/userchannels"
"github.com/redis/go-redis/v9"
)

// Adapter delivers a single WorkerMessage to its target channel.
Expand All @@ -31,7 +31,7 @@ type Starter interface {
// NewRouter calls MountRoutes once at startup for every registered adapter
// that satisfies this interface.
type RouteProvider interface {
MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *redis.Client, channels *userchannels.Repo)
MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *store.Redis, channels *userchannels.Repo)
}

// ConfigValidator is implemented by adapters that can validate a proposed channel
Expand Down
4 changes: 2 additions & 2 deletions internal/adapter/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package adapter

import (
"github.com/metabrainz/synapse/internal/eventtype"
"github.com/redis/go-redis/v9"
"github.com/metabrainz/synapse/internal/store"
)

// TelegramOptions configures the Telegram adapter.
Expand Down Expand Up @@ -33,7 +33,7 @@ type Options struct {
Webhook WebhookOptions
Telegram TelegramOptions
MailService MailServiceOptions
Redis *redis.Client
Redis *store.Redis
// Registry supplies event templates to the Telegram adapter.
Registry *eventtype.Registry
}
4 changes: 2 additions & 2 deletions internal/adapter/telegram/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

"github.com/metabrainz/synapse/internal/eventtype"
"github.com/metabrainz/synapse/internal/fanout"
"github.com/redis/go-redis/v9"
"github.com/metabrainz/synapse/internal/store"
)

type channelConfig struct {
Expand All @@ -29,7 +29,7 @@ type Adapter struct {
// New creates the Telegram adapter.
// rdb may be nil; when nil, the per-chat and global rate limit pre-checks are
// skipped (the adapter still handles 429 responses from the API gracefully).
func New(botToken, webhookURL, webhookSecret string, rdb *redis.Client, reg *eventtype.Registry) *Adapter {
func New(botToken, webhookURL, webhookSecret string, rdb *store.Redis, reg *eventtype.Registry) *Adapter {
a := &Adapter{
bot: NewBot(botToken),
webhookURL: webhookURL,
Expand Down
25 changes: 15 additions & 10 deletions internal/adapter/telegram/connect.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import (

"github.com/go-chi/chi/v5"
"github.com/metabrainz/synapse/internal/api/middleware"
"github.com/metabrainz/synapse/internal/store"
"github.com/metabrainz/synapse/internal/store/userchannels"
"github.com/redis/go-redis/v9"
)

const (
Expand All @@ -27,13 +27,18 @@ const (

type connectHandler struct {
bot *Bot
rdb *redis.Client
rdb *store.Redis
channels *userchannels.Repo
secret string
}

func connectKey(token string) string { return "synapse:tg:connect:" + token }
func connectDoneKey(token string) string { return "synapse:tg:connect:done:" + token }
func (h *connectHandler) connectKey(token string) string {
return h.rdb.Name("synapse:tg:connect:" + token)
}

func (h *connectHandler) connectDoneKey(token string) string {
return h.rdb.Name("synapse:tg:connect:done:" + token)
}

func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
Expand All @@ -56,7 +61,7 @@ func requireUser(w http.ResponseWriter, r *http.Request) (string, bool) {

// MountRoutes registers the Telegram connect flow under the given root router.
// It is a no-op if the adapter has no bot configured.
func (a *Adapter) MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *redis.Client, channels *userchannels.Repo) {
func (a *Adapter) MountRoutes(r chi.Router, userMW func(http.Handler) http.Handler, rdb *store.Redis, channels *userchannels.Repo) {
if a.bot == nil {
return
}
Expand Down Expand Up @@ -84,7 +89,7 @@ func (h *connectHandler) initiate(w http.ResponseWriter, req *http.Request) {
token := hex.EncodeToString(raw)

ctx := req.Context()
if err := h.rdb.Set(ctx, connectKey(token), uid, connectTTL).Err(); err != nil {
if err := h.rdb.Set(ctx, h.connectKey(token), uid, connectTTL).Err(); err != nil {
writeError(w, http.StatusInternalServerError, "token storage failed")
return
}
Expand Down Expand Up @@ -113,12 +118,12 @@ func (h *connectHandler) status(w http.ResponseWriter, req *http.Request) {
token := chi.URLParam(req, "token")
ctx := req.Context()

if owner, err := h.rdb.Get(ctx, connectKey(token)).Result(); err == nil && owner != uid {
if owner, err := h.rdb.Get(ctx, h.connectKey(token)).Result(); err == nil && owner != uid {
writeError(w, http.StatusForbidden, "token does not belong to this user")
return
}

channelID, err := h.rdb.Get(ctx, connectDoneKey(token)).Result()
channelID, err := h.rdb.Get(ctx, h.connectDoneKey(token)).Result()
if err != nil {
writeJSON(w, http.StatusOK, map[string]string{"status": "pending"})
return
Expand Down Expand Up @@ -177,7 +182,7 @@ func (h *connectHandler) webhook(w http.ResponseWriter, req *http.Request) {
}

func (h *connectHandler) handleConnect(ctx context.Context, chatID, token, firstName string) {
userID, err := h.rdb.GetDel(ctx, connectKey(token)).Result()
userID, err := h.rdb.GetDel(ctx, h.connectKey(token)).Result()
if err != nil {
_ = h.bot.Send(ctx, chatID, "This link has expired or is invalid. Please generate a new one from the Synapse UI.")
return
Expand All @@ -200,6 +205,6 @@ func (h *connectHandler) handleConnect(ctx context.Context, chatID, token, first
return
}

h.rdb.Set(ctx, connectDoneKey(token), strconv.FormatInt(channelID, 10), connectTTL)
h.rdb.Set(ctx, h.connectDoneKey(token), strconv.FormatInt(channelID, 10), connectTTL)
_ = h.bot.Send(ctx, chatID, "✓ Connected! You'll receive Synapse notifications here.")
}
25 changes: 25 additions & 0 deletions internal/adapter/telegram/connect_key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package telegram

import (
"testing"

"github.com/metabrainz/synapse/internal/store"
)

func TestConnectKeysFollowTheNamespace(t *testing.T) {
plain := &connectHandler{rdb: &store.Redis{}}
if got := plain.connectKey("tok"); got != "synapse:tg:connect:tok" {
t.Errorf("connectKey = %q", got)
}
if got := plain.connectDoneKey("tok"); got != "synapse:tg:connect:done:tok" {
t.Errorf("connectDoneKey = %q", got)
}

ns := &connectHandler{rdb: &store.Redis{Namespace: "test"}}
if got := ns.connectKey("tok"); got != "test:synapse:tg:connect:tok" {
t.Errorf("namespaced connectKey = %q", got)
}
if got := ns.connectDoneKey("tok"); got != "test:synapse:tg:connect:done:tok" {
t.Errorf("namespaced connectDoneKey = %q", got)
}
}
4 changes: 2 additions & 2 deletions internal/adapter/telegram/ratelimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (

"github.com/metabrainz/synapse/internal/fanout"
"github.com/metabrainz/synapse/internal/ratelimit"
"github.com/redis/go-redis/v9"
"github.com/metabrainz/synapse/internal/store"
)

const (
Expand All @@ -33,7 +33,7 @@ type rateLimiter struct {
global *ratelimit.Limiter // burst=30, rate=30/s — key: synapse:rl:tg:global
}

func newRateLimiter(rdb *redis.Client) *rateLimiter {
func newRateLimiter(rdb *store.Redis) *rateLimiter {
return &rateLimiter{
perChat: ratelimit.New(rdb, perChatRate, perChatRate),
global: ratelimit.New(rdb, globalRate, globalRate),
Expand Down
4 changes: 2 additions & 2 deletions internal/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ import (
"github.com/metabrainz/synapse/internal/live"
"github.com/metabrainz/synapse/internal/oauth"
"github.com/metabrainz/synapse/internal/ratelimit"
"github.com/metabrainz/synapse/internal/store"
"github.com/metabrainz/synapse/internal/store/notifications"
"github.com/metabrainz/synapse/internal/store/preferences"
"github.com/metabrainz/synapse/internal/store/userchannels"
"github.com/metabrainz/synapse/internal/store/usereventsubs"
"github.com/metabrainz/synapse/internal/store/users"
"github.com/metabrainz/synapse/internal/store/usertenant"
"github.com/redis/go-redis/v9"
)

// HealthChecks holds optional probe functions for /health/ready.
Expand All @@ -51,7 +51,7 @@ type Config struct {
// Deps bundles the data-layer dependencies injected into the router.
type Deps struct {
Pool *pgxpool.Pool
Redis *redis.Client
Redis *store.Redis
Users *users.Repo
UserChannels *userchannels.Repo
TenantMappings *usertenant.Repo
Expand Down
7 changes: 4 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,10 @@ func (c PostgresConfig) URL() string {
}

type RedisConfig struct {
Addr string `yaml:"addr"`
Password string `yaml:"password"`
DB int `yaml:"db"`
Addr string `yaml:"addr"`
Password string `yaml:"password"`
DB int `yaml:"db"`
Namespace string `yaml:"namespace"`
}

type RabbitMQConfig struct {
Expand Down
1 change: 1 addition & 0 deletions internal/config/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ func applyEnv(cfg *Config) error {
str(&cfg.Postgres.DBName, "SYNAPSE_PG_DBNAME")
str(&cfg.Postgres.DirectDSN, "SYNAPSE_PG_DIRECT_DSN")
str(&cfg.Redis.Addr, "SYNAPSE_REDIS_ADDR")
str(&cfg.Redis.Namespace, "SYNAPSE_REDIS_NAMESPACE")
str(&cfg.RabbitMQ.URL, "SYNAPSE_RABBITMQ_URL")
str(&cfg.OAuth.ClientID, "SYNAPSE_OAUTH_CLIENT_ID")
str(&cfg.OAuth.ClientSecret, "SYNAPSE_OAUTH_CLIENT_SECRET")
Expand Down
Loading