-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathredis.go
More file actions
393 lines (334 loc) · 9.25 KB
/
redis.go
File metadata and controls
393 lines (334 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package eventbus
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strings"
"sync"
"sync/atomic"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// RedisEventBus implements EventBus using Redis pub/sub
type RedisEventBus struct {
config *RedisConfig
client *redis.Client
subscriptions map[string]map[string]*redisSubscription
topicMutex sync.RWMutex
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
isStarted atomic.Bool
}
// RedisConfig holds Redis-specific configuration
type RedisConfig struct {
URL string `json:"url"`
DB int `json:"db"`
Username string `json:"username"`
Password string `json:"password"` //nolint:gosec // config field, not a hardcoded secret
PoolSize int `json:"poolSize"`
}
// redisSubscription represents a subscription in the Redis event bus
type redisSubscription struct {
id string
topic string
handler EventHandler
isAsync bool
pubsub *redis.PubSub
done chan struct{}
cancelled bool
mutex sync.RWMutex
bus *RedisEventBus
}
// Topic returns the topic of the subscription
func (s *redisSubscription) Topic() string {
return s.topic
}
// ID returns the unique identifier for the subscription
func (s *redisSubscription) ID() string {
return s.id
}
// IsAsync returns whether the subscription is asynchronous
func (s *redisSubscription) IsAsync() bool {
return s.isAsync
}
// Cancel cancels the subscription
func (s *redisSubscription) Cancel() error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.cancelled {
return nil
}
s.cancelled = true
if s.pubsub != nil {
s.pubsub.Close()
}
close(s.done)
return nil
}
// NewRedisEventBus creates a new Redis-based event bus
func NewRedisEventBus(config map[string]interface{}) (EventBus, error) {
redisConfig := &RedisConfig{
URL: "redis://localhost:6379",
DB: 0,
PoolSize: 10,
}
// Parse configuration
if url, ok := config["url"].(string); ok {
redisConfig.URL = url
}
if db, ok := config["db"].(int); ok {
redisConfig.DB = db
}
if username, ok := config["username"].(string); ok {
redisConfig.Username = username
}
if password, ok := config["password"].(string); ok {
redisConfig.Password = password
}
if poolSize, ok := config["poolSize"].(int); ok {
redisConfig.PoolSize = poolSize
}
// Parse Redis connection URL
opts, err := redis.ParseURL(redisConfig.URL)
if err != nil {
return nil, fmt.Errorf("invalid Redis URL: %w", err)
}
// Override with explicit config
opts.DB = redisConfig.DB
opts.PoolSize = redisConfig.PoolSize
if redisConfig.Username != "" {
opts.Username = redisConfig.Username
}
if redisConfig.Password != "" {
opts.Password = redisConfig.Password
}
client := redis.NewClient(opts)
return &RedisEventBus{
config: redisConfig,
client: client,
subscriptions: make(map[string]map[string]*redisSubscription),
}, nil
}
// Start initializes the Redis event bus
func (r *RedisEventBus) Start(ctx context.Context) error {
if r.isStarted.Load() {
return nil
}
// Test connection
_, err := r.client.Ping(ctx).Result()
if err != nil {
return fmt.Errorf("failed to connect to Redis: %w", err)
}
r.ctx, r.cancel = context.WithCancel(ctx) //nolint:gosec // G118: cancel is stored in r.cancel and called in Stop()
r.isStarted.Store(true)
return nil
}
// Stop shuts down the Redis event bus
func (r *RedisEventBus) Stop(ctx context.Context) error {
if !r.isStarted.Load() {
return nil
}
// Cancel context to signal all workers to stop
if r.cancel != nil {
r.cancel()
}
// Cancel all subscriptions
r.topicMutex.Lock()
for _, subs := range r.subscriptions {
for _, sub := range subs {
if err := sub.Cancel(); err != nil {
slog.Warn("failed to cancel Redis subscription during shutdown", "error", err)
}
}
}
r.subscriptions = make(map[string]map[string]*redisSubscription)
r.topicMutex.Unlock()
// Wait for all workers to finish
done := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
slog.Error("panic recovered in Redis eventbus shutdown waiter", "error", r)
}
}()
r.wg.Wait()
close(done)
}()
select {
case <-done:
// All workers exited gracefully
case <-ctx.Done():
return ErrEventBusShutdownTimeout
}
// Close Redis client
if err := r.client.Close(); err != nil {
return fmt.Errorf("error closing Redis client: %w", err)
}
r.isStarted.Store(false)
return nil
}
// Publish sends an event to the specified topic using Redis pub/sub
func (r *RedisEventBus) Publish(ctx context.Context, event Event) error {
if !r.isStarted.Load() {
return ErrEventBusNotStarted
}
eventData, err := json.Marshal(event)
if err != nil {
return fmt.Errorf("failed to serialize event: %w", err)
}
// Publish to Redis
err = r.client.Publish(ctx, event.Type(), eventData).Err()
if err != nil {
return fmt.Errorf("failed to publish to Redis: %w", err)
}
return nil
}
// Subscribe registers a handler for a topic
func (r *RedisEventBus) Subscribe(ctx context.Context, topic string, handler EventHandler) (Subscription, error) {
return r.subscribe(ctx, topic, handler, false)
}
// SubscribeAsync registers a handler for a topic with asynchronous processing
func (r *RedisEventBus) SubscribeAsync(ctx context.Context, topic string, handler EventHandler) (Subscription, error) {
return r.subscribe(ctx, topic, handler, true)
}
// subscribe is the internal implementation for both Subscribe and SubscribeAsync
func (r *RedisEventBus) subscribe(ctx context.Context, topic string, handler EventHandler, isAsync bool) (Subscription, error) {
if !r.isStarted.Load() {
return nil, ErrEventBusNotStarted
}
if handler == nil {
return nil, ErrEventHandlerNil
}
// Create Redis subscription
var pubsub *redis.PubSub
if strings.Contains(topic, "*") {
// Use pattern subscription for wildcard topics
pubsub = r.client.PSubscribe(ctx, topic)
} else {
// Use regular subscription for exact topics
pubsub = r.client.Subscribe(ctx, topic)
}
// Create subscription object
sub := &redisSubscription{
id: uuid.New().String(),
topic: topic,
handler: handler,
isAsync: isAsync,
pubsub: pubsub,
done: make(chan struct{}),
cancelled: false,
bus: r,
}
// Add to subscriptions map
r.topicMutex.Lock()
if _, ok := r.subscriptions[topic]; !ok {
r.subscriptions[topic] = make(map[string]*redisSubscription)
}
r.subscriptions[topic][sub.id] = sub
r.topicMutex.Unlock()
// Start message listener goroutine (explicit Add/go because handleMessages manages Done)
r.wg.Add(1)
go r.handleMessages(sub)
return sub, nil
}
// Unsubscribe removes a subscription
func (r *RedisEventBus) Unsubscribe(ctx context.Context, subscription Subscription) error {
if !r.isStarted.Load() {
return ErrEventBusNotStarted
}
sub, ok := subscription.(*redisSubscription)
if !ok {
return ErrInvalidSubscriptionType
}
// Cancel the subscription
err := sub.Cancel()
if err != nil {
return err
}
// Remove from subscriptions map
r.topicMutex.Lock()
defer r.topicMutex.Unlock()
if subs, ok := r.subscriptions[sub.topic]; ok {
delete(subs, sub.id)
if len(subs) == 0 {
delete(r.subscriptions, sub.topic)
}
}
return nil
}
// Topics returns a list of all active topics
func (r *RedisEventBus) Topics() []string {
r.topicMutex.RLock()
defer r.topicMutex.RUnlock()
topics := make([]string, 0, len(r.subscriptions))
for topic := range r.subscriptions {
topics = append(topics, topic)
}
return topics
}
// SubscriberCount returns the number of subscribers for a topic
func (r *RedisEventBus) SubscriberCount(topic string) int {
r.topicMutex.RLock()
defer r.topicMutex.RUnlock()
if subs, ok := r.subscriptions[topic]; ok {
return len(subs)
}
return 0
}
// handleMessages processes messages for a Redis subscription
func (r *RedisEventBus) handleMessages(sub *redisSubscription) {
defer r.wg.Done()
defer func() {
if r := recover(); r != nil {
slog.Error("panic recovered in Redis message handler", "error", r, "topic", sub.topic)
}
}()
ch := sub.pubsub.Channel()
for {
select {
case <-r.ctx.Done():
// Event bus is shutting down
return
case <-sub.done:
// Subscription was cancelled
return
case msg := <-ch:
if msg == nil {
continue
}
// Deserialize event
var event Event
err := json.Unmarshal([]byte(msg.Payload), &event)
if err != nil {
slog.Error("Failed to deserialize Redis message", "error", err, "topic", msg.Channel)
continue
}
// Process the event
if sub.isAsync {
// For async subscriptions, process in a separate goroutine
go r.processEventAsync(sub, event)
} else {
// For sync subscriptions, process immediately
r.processEvent(sub, event)
}
}
}
}
// processEvent processes an event synchronously
func (r *RedisEventBus) processEvent(sub *redisSubscription, event Event) {
err := sub.handler(r.ctx, event)
if err != nil {
slog.Error("Redis event handler failed", "error", err, "topic", event.Type())
}
}
// processEventAsync processes an event asynchronously
func (r *RedisEventBus) processEventAsync(sub *redisSubscription, event Event) {
defer func() {
if r := recover(); r != nil {
slog.Error("panic recovered in Redis async event handler", "error", r, "topic", event.Type())
}
}()
r.processEvent(sub, event)
}