forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.go
More file actions
485 lines (389 loc) · 11.1 KB
/
redis.go
File metadata and controls
485 lines (389 loc) · 11.1 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
package mercure
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"sync"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
"golang.org/x/oauth2/google"
)
const (
lastEventIDKey = "lastEventID"
defaultHistorySize = 1000
historyStreamSuffix = ":history"
publishScript = `
redis.call("SET", KEYS[1], ARGV[1])
redis.call("XADD", KEYS[2], "MAXLEN", "~", ARGV[4], "*", "id", ARGV[1], "payload", ARGV[3])
redis.call("PUBLISH", ARGV[2], ARGV[3])
return true
`
)
var errAuthFailed = errors.New("AUTH failed")
type RedisTransport struct {
sync.RWMutex
logger Logger
client *redis.Client
subscribers *SubscriberList
closed chan any
publishScript *redis.Script
closedOnce sync.Once
redisChannel string
historyStreamKey string
historySize int
}
// RedisConfig holds configuration for Redis connection.
type RedisConfig struct {
Address string
Username string
Password string
SubscribersSize int
RedisChannel string
HistorySize int
// IAM authentication for Google Cloud Memorystore.
UseIAMAuth bool
ProjectID string
Location string
InstanceID string
}
func NewRedisTransport(
logger Logger,
address string,
username string,
password string,
subscribersSize int,
redisChannel string,
historySize int,
) (*RedisTransport, error) {
config := &RedisConfig{
Address: address,
Username: username,
Password: password,
SubscribersSize: subscribersSize,
RedisChannel: redisChannel,
HistorySize: historySize,
UseIAMAuth: false,
}
return NewRedisTransportWithConfig(logger, config)
}
// NewRedisTransportWithIAM creates a Redis transport with IAM authentication for Google Cloud Memorystore.
func NewRedisTransportWithIAM(
logger Logger,
projectID string,
location string,
instanceID string,
subscribersSize int,
redisChannel string,
historySize int,
) (*RedisTransport, error) {
// For Google Cloud Memorystore, the address should be the actual Redis endpoint
// The format is typically: <instance-ip>:6379
// We'll need to construct this properly or accept the full address
config := &RedisConfig{
Address: fmt.Sprintf("%s:%s:%s", projectID, location, instanceID),
SubscribersSize: subscribersSize,
RedisChannel: redisChannel,
HistorySize: historySize,
UseIAMAuth: true,
ProjectID: projectID,
Location: location,
InstanceID: instanceID,
}
return NewRedisTransportWithConfig(logger, config)
}
// NewRedisTransportWithIAMAddress creates a Redis transport with IAM authentication using the full Memorystore address.
func NewRedisTransportWithIAMAddress(
logger Logger,
address string,
projectID string,
subscribersSize int,
redisChannel string,
historySize int,
) (*RedisTransport, error) {
config := &RedisConfig{
Address: address,
SubscribersSize: subscribersSize,
RedisChannel: redisChannel,
HistorySize: historySize,
UseIAMAuth: true,
ProjectID: projectID,
}
return NewRedisTransportWithConfig(logger, config)
}
// NewRedisTransportWithConfig creates a Redis transport with the given configuration.
func NewRedisTransportWithConfig(logger Logger, config *RedisConfig) (*RedisTransport, error) {
var client *redis.Client
var err error
if config.UseIAMAuth {
// Use IAM authentication for Google Cloud Memorystore
client, err = createRedisClientWithIAM(config)
if err != nil {
return nil, fmt.Errorf("failed to create Redis client with IAM auth: %w", err)
}
} else {
// Use traditional username/password authentication
client = redis.NewClient(&redis.Options{
Username: config.Username,
Password: config.Password,
Addr: config.Address,
})
}
if pong := client.Ping(context.Background()); pong.String() != "ping: PONG" {
return nil, fmt.Errorf("failed to connect to Redis: %w", pong.Err())
}
// Log successful Redis connection
logger.Info("Redis connection established",
zap.String("address", config.Address),
zap.Bool("useIAM", config.UseIAMAuth),
)
return NewRedisTransportInstance(logger, client, config.SubscribersSize, config.RedisChannel, config.HistorySize)
}
// createRedisClientWithIAM creates a Redis client with IAM authentication.
func createRedisClientWithIAM(config *RedisConfig) (*redis.Client, error) {
ctx := context.Background()
// The correct scope for Memorystore IAM is:
// "https://www.googleapis.com/auth/cloud-platform"
tokenSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
if err != nil {
return nil, fmt.Errorf("failed to get default token source: %w", err)
}
// Create Redis client with IAM authentication
client := redis.NewClient(&redis.Options{
Addr: config.Address,
// Use custom dialer for IAM authentication
Dialer: func(_ context.Context, network, addr string) (net.Conn, error) {
// Get the token
token, err := tokenSource.Token()
if err != nil {
return nil, fmt.Errorf("failed to get token: %w", err)
}
// Create connection
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, network, addr)
if err != nil {
return nil, fmt.Errorf("failed to dial connection: %w", err)
}
// For Google Cloud Memorystore, we need to send the token in the AUTH command
// The format is: AUTH <token>
authCommand := fmt.Sprintf("AUTH %s\r\n", token.AccessToken)
_, err = conn.Write([]byte(authCommand))
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to send AUTH command: %w", err)
}
// Read response
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to read AUTH response: %w", err)
}
response := string(buf[:n])
if response != "+OK\r\n" {
conn.Close()
return nil, fmt.Errorf("%w: %s", errAuthFailed, response)
}
return conn, nil
},
})
return client, nil
}
func NewRedisTransportInstance(
logger Logger,
client *redis.Client,
subscribersSize int,
redisChannel string,
historySize int,
) (*RedisTransport, error) {
if historySize <= 0 {
historySize = defaultHistorySize
}
subscriber := client.PSubscribe(context.Background(), redisChannel)
subscribeCtx, subscribeCancel := context.WithCancel(context.Background())
transport := &RedisTransport{
logger: logger,
client: client,
subscribers: NewSubscriberList(subscribersSize),
publishScript: redis.NewScript(publishScript),
closed: make(chan any),
redisChannel: redisChannel,
historyStreamKey: redisChannel + historyStreamSuffix,
historySize: historySize,
}
go func() {
select {
case <-transport.closed:
if err := subscriber.Close(); err != nil && !errors.Is(err, redis.ErrClosed) {
logger.Error(err.Error())
}
<-subscribeCtx.Done()
if err := client.Close(); err != nil && !errors.Is(err, redis.ErrClosed) {
logger.Error(err.Error())
}
// Log Redis connection closure
logger.Info("Redis connection closed",
zap.String("address", transport.client.Options().Addr),
)
case <-subscribeCtx.Done():
}
}()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
transport.subscribe(subscribeCtx, subscribeCancel, subscriber)
}()
return transport, nil
}
func (u Update) MarshalBinary() ([]byte, error) {
bytes, err := json.Marshal(u)
if err != nil {
return nil, fmt.Errorf("unable to marshal: %w", err)
}
return bytes, nil
}
func (t *RedisTransport) Dispatch(update *Update) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
AssignUUID(update)
keys := []string{lastEventIDKey, t.historyStreamKey}
arguments := []interface{}{update.ID, t.redisChannel, update, t.historySize}
_, err := t.publishScript.Run(context.Background(), t.client, keys, arguments...).Result()
if err != nil {
return fmt.Errorf("redis failed to publish: %w", err)
}
return nil
}
func (t *RedisTransport) AddSubscriber(s *LocalSubscriber) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
t.Lock()
t.subscribers.Add(s)
t.Unlock()
if s.RequestLastEventID != "" {
t.dispatchHistory(s)
}
s.Ready()
return nil
}
func (t *RedisTransport) RemoveSubscriber(s *LocalSubscriber) error {
select {
case <-t.closed:
return ErrClosedTransport
default:
}
t.Lock()
defer t.Unlock()
t.subscribers.Remove(s)
return nil
}
func (t *RedisTransport) GetSubscribers() (string, []*Subscriber, error) {
select {
case <-t.closed:
return "", nil, ErrClosedTransport
default:
}
t.RLock()
defer t.RUnlock()
lastEventID, err := t.client.Get(context.Background(), lastEventIDKey).Result()
if err != nil {
return "", nil, fmt.Errorf("redis failed to get last event id: %w", err)
}
return lastEventID, getSubscribers(t.subscribers), nil
}
func (t *RedisTransport) Close() (err error) {
t.closedOnce.Do(func() {
t.Lock()
defer t.Unlock()
// Log transport shutdown
t.logger.Info("Redis transport shutting down",
zap.String("address", t.client.Options().Addr),
)
t.subscribers.Walk(0, func(s *LocalSubscriber) bool {
s.Disconnect()
return true
})
close(t.closed)
})
return nil
}
func (t *RedisTransport) dispatchHistory(s *LocalSubscriber) {
entries, err := t.client.XRange(context.Background(), t.historyStreamKey, "-", "+").Result()
if err != nil {
t.logger.Error("failed to read history stream", zap.Error(err))
s.HistoryDispatched(EarliestLastEventID)
return
}
afterLastEventID := s.RequestLastEventID == EarliestLastEventID
responseLastEventID := EarliestLastEventID
for _, entry := range entries {
eventID, _ := entry.Values["id"].(string)
if !afterLastEventID {
responseLastEventID = eventID
if eventID == s.RequestLastEventID {
afterLastEventID = true
}
continue
}
payload, ok := entry.Values["payload"].(string)
if !ok {
continue
}
var update Update
if err := json.Unmarshal([]byte(payload), &update); err != nil {
t.logger.Error("failed to unmarshal history entry", zap.Error(err))
continue
}
if s.Match(&update) {
if !s.Dispatch(&update, true) {
s.HistoryDispatched(responseLastEventID)
return
}
}
responseLastEventID = eventID
}
s.HistoryDispatched(responseLastEventID)
if !afterLastEventID {
if c := t.logger.Check(zap.DebugLevel, "Can't find requested LastEventID"); c != nil {
c.Write(zap.String("LastEventID", s.RequestLastEventID))
}
}
}
func (t *RedisTransport) subscribe(ctx context.Context, cancel context.CancelFunc, subscriber *redis.PubSub) {
for {
message, err := subscriber.ReceiveMessage(ctx)
if err != nil {
if errors.Is(err, redis.ErrClosed) {
cancel()
return
}
t.logger.Error(err.Error())
continue
}
var update Update
if err := json.Unmarshal([]byte(message.Payload), &update); err != nil {
t.logger.Error(err.Error())
continue
}
topics := make([]string, len(update.Topics))
copy(topics, update.Topics)
t.Lock()
for _, subscriber := range t.subscribers.MatchAny(&update) {
update.Topics = topics
subscriber.Dispatch(&update, false)
}
t.Unlock()
}
}
var (
_ Transport = (*RedisTransport)(nil)
_ TransportSubscribers = (*RedisTransport)(nil)
)