-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcoverage.html
More file actions
1314 lines (1110 loc) · 56.3 KB
/
coverage.html
File metadata and controls
1314 lines (1110 loc) · 56.3 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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>load-balancing: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/handcoding-labs/redis-stream-client-go/examples/load-balancing/main.go (0.0%)</option>
<option value="file1">github.com/handcoding-labs/redis-stream-client-go/impl/helpers.go (0.0%)</option>
<option value="file2">github.com/handcoding-labs/redis-stream-client-go/impl/init.go (0.0%)</option>
<option value="file3">github.com/handcoding-labs/redis-stream-client-go/impl/opts.go (0.0%)</option>
<option value="file4">github.com/handcoding-labs/redis-stream-client-go/impl/relredis.go (0.0%)</option>
<option value="file5">github.com/handcoding-labs/redis-stream-client-go/notifs/broker.go (0.0%)</option>
<option value="file6">github.com/handcoding-labs/redis-stream-client-go/notifs/lbsmsg.go (0.0%)</option>
<option value="file7">github.com/handcoding-labs/redis-stream-client-go/notifs/relredisnotif.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/redis/go-redis/v9"
"github.com/handcoding-labs/redis-stream-client-go/impl"
"github.com/handcoding-labs/redis-stream-client-go/notifs"
"github.com/handcoding-labs/redis-stream-client-go/types"
)
func main() <span class="cov0" title="0">{
// Check if this is running as a producer
if len(os.Args) > 1 && os.Args[1] == "producer" </span><span class="cov0" title="0">{
runProducer()
return
}</span>
// Run as consumer
<span class="cov0" title="0">runConsumer()</span>
}
func runConsumer() <span class="cov0" title="0">{
// Set up context with cancellation
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Handle graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Get consumer ID from environment
consumerID := os.Getenv("POD_NAME")
if consumerID == "" </span><span class="cov0" title="0">{
consumerID = fmt.Sprintf("consumer-%d", time.Now().Unix())
os.Setenv("POD_NAME", consumerID)
}</span>
<span class="cov0" title="0">slog.Info("Starting consumer", "consumer_id", consumerID)
// Create Redis client
// Use environment variable for Redis address, default to localhost for local development
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" </span><span class="cov0" title="0">{
redisAddr = "localhost:6379"
}</span>
<span class="cov0" title="0">redisClient := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{redisAddr},
DB: 0,
})
defer redisClient.Close()
// Test Redis connection
if err := redisClient.Ping(ctx).Err(); err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to connect to Redis", "error", err)
os.Exit(1)
}</span>
// Enable keyspace notifications
<span class="cov0" title="0">if err := redisClient.ConfigSet(ctx, "notify-keyspace-events", "Ex").Err(); err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to enable keyspace notifications", "error", err)
os.Exit(1)
}</span>
// Create Redis Stream Client
<span class="cov0" title="0">client, err := impl.NewRedisStreamClient(redisClient, "load-balance-demo")
if err != nil </span><span class="cov0" title="0">{
slog.Error("could not initialize", "error", err.Error())
}</span>
<span class="cov0" title="0">slog.Info("Created client", "client_id", client.ID())
// Initialize the client
outputChan, err := client.Init(ctx)
if err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to initialize client", "error", err)
os.Exit(1)
}</span>
// Track processed streams
<span class="cov0" title="0">var processedStreams sync.Map
var streamCount int32
// Process notifications
// The internal NotificationBroker ensures thread-safe delivery from multiple sources:
// - LBS stream reader
// - Keyspace notification listener
// - Key extenders (one per active stream)
go func() </span><span class="cov0" title="0">{
for notification := range outputChan </span><span class="cov0" title="0">{
switch notification.Type </span>{
case notifs.StreamAdded:<span class="cov0" title="0">
slog.Info("🎉 New stream assigned", "consumer_id", consumerID)
go handleStreamAdded(ctx, client, notification, &processedStreams, &streamCount)</span>
case notifs.StreamExpired:<span class="cov0" title="0">
slog.Warn("⚠️ Stream expired, attempting to claim", "consumer_id", consumerID, "payload", notification.Payload)
if err := client.Claim(ctx, notification.Payload); err != nil </span><span class="cov0" title="0">{
slog.Error("❌ Failed to claim expired stream", "consumer_id", consumerID, "error", err)
}</span> else<span class="cov0" title="0"> {
slog.Info("✅ Successfully claimed expired stream", "consumer_id", consumerID)
go handleClaimedStream(ctx, client, notification.Payload.DataStreamName, &processedStreams, &streamCount)
}</span>
case notifs.StreamDisowned:<span class="cov0" title="0">
slog.Warn("❌ Stream disowned", "consumer_id", consumerID, "payload", notification.Payload)</span>
case notifs.StreamTerminated:<span class="cov0" title="0">
// This notification indicates the channel is closing
// The reason is available in AdditionalInfo
reason := "unknown"
if info, ok := notification.AdditionalInfo["info"].(string); ok </span><span class="cov0" title="0">{
reason = info
}</span>
<span class="cov0" title="0">slog.Info("📴 Notification channel terminating", "consumer_id", consumerID, "reason", reason)</span>
}
}
<span class="cov0" title="0">slog.Info("Notification channel closed", "consumer_id", consumerID)</span>
}()
// Print statistics periodically
<span class="cov0" title="0">go printStatistics(ctx, consumerID, &processedStreams, &streamCount)
// Wait for shutdown signal
<-sigChan
slog.Info("🛑 Shutdown signal received, cleaning up...", "consumer_id", consumerID)
// Graceful shutdown
// Done() ensures all pending notifications are drained via the NotificationBroker
// before the output channel is closed
if err := client.Done(ctx); err != nil </span><span class="cov0" title="0">{
slog.Error("❌ Error during cleanup", "consumer_id", consumerID, "error", err)
}</span> else<span class="cov0" title="0"> {
slog.Info("✅ Client cleanup completed", "consumer_id", consumerID)
}</span>
}
func runProducer() <span class="cov0" title="0">{
ctx := context.Background()
slog.Info("🏭 Starting producer...")
// Create Redis client
// Use environment variable for Redis address, default to localhost for local development
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" </span><span class="cov0" title="0">{
redisAddr = "localhost:6379"
}</span>
<span class="cov0" title="0">redisClient := redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{redisAddr},
DB: 0,
})
defer redisClient.Close()
// Test connection
if err := redisClient.Ping(ctx).Err(); err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to connect to Redis", "error", err)
os.Exit(1)
}</span>
// Produce messages continuously
<span class="cov0" title="0">messageID := 0
for </span><span class="cov0" title="0">{
// Create batch of messages
for i := 0; i < 5; i++ </span><span class="cov0" title="0">{
lbsMessage := notifs.LBSInputMessage{
DataStreamName: fmt.Sprintf("order-stream-%d", messageID),
Info: map[string]interface{}{
"order_id": fmt.Sprintf("order-%d", messageID),
"customer_id": fmt.Sprintf("customer-%d", messageID%100),
"amount": float64(messageID%1000 + 100),
"created_at": time.Now().Format(time.RFC3339),
"status": "pending",
"priority": []string{"low", "normal", "high"}[messageID%3],
},
}
messageData, err := json.Marshal(lbsMessage)
if err != nil </span><span class="cov0" title="0">{
slog.Error("❌ Failed to marshal message", "error", err)
continue</span>
}
<span class="cov0" title="0">result := redisClient.XAdd(ctx, &redis.XAddArgs{
Stream: "load-balance-demo-input",
Values: map[string]interface{}{
"lbs-input": string(messageData),
},
})
if result.Err() != nil </span><span class="cov0" title="0">{
slog.Error("❌ Failed to add message", "error", result.Err())
}</span> else<span class="cov0" title="0"> {
slog.Info("📤 Produced message", "message_id", messageID, "stream_name", lbsMessage.DataStreamName)
}</span>
<span class="cov0" title="0">messageID++</span>
}
// Wait before next batch
<span class="cov0" title="0">time.Sleep(3 * time.Second)</span>
}
}
func handleStreamAdded(ctx context.Context, client types.RedisStreamClient, notification notifs.RecoverableRedisNotification, processedStreams *sync.Map, streamCount *int32) <span class="cov0" title="0">{
consumerID := client.ID()
streamName := notification.Payload.DataStreamName
slog.Info("🔄 Processing stream", "consumer_id", consumerID, "stream_name", streamName)
slog.Debug("📋 Stream details", "consumer_id", consumerID, "stream_info", notification.Payload)
// Simulate processing time (varies by priority)
processingTime := 2 * time.Second
if priority, ok := notification.AdditionalInfo["priority"].(string); ok </span><span class="cov0" title="0">{
switch priority </span>{
case "high":<span class="cov0" title="0">
processingTime = 1 * time.Second</span>
case "low":<span class="cov0" title="0">
processingTime = 4 * time.Second</span>
}
}
// Simulate work
<span class="cov0" title="0">time.Sleep(processingTime)
// Mark as processed
processedStreams.Store(streamName, time.Now())
*streamCount++
// Mark stream as done after processing
if err := client.DoneStream(ctx, streamName); err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to mark stream done", "error", err, "stream", streamName, "consumer_id", consumerID)
}</span> else<span class="cov0" title="0"> {
slog.Info("✅ Completed processing stream", "consumer_id", consumerID, "stream_name", streamName, "processing_time", processingTime)
}</span>
}
func handleClaimedStream(ctx context.Context, client types.RedisStreamClient, streamName string, processedStreams *sync.Map, streamCount *int32) <span class="cov0" title="0">{
slog.Info("🔄 Processing claimed stream", "consumer_id", client.ID(), "stream_name", streamName)
// Simulate processing the claimed stream
time.Sleep(1 * time.Second)
processedStreams.Store(streamName, time.Now())
*streamCount++
// Mark stream as done after processing
if err := client.DoneStream(ctx, streamName); err != nil </span><span class="cov0" title="0">{
slog.Error("Failed to mark claimed stream done", "error", err, "stream", streamName, "consumer_id", client.ID())
}</span> else<span class="cov0" title="0"> {
slog.Info("✅ Completed processing claimed stream", "consumer_id", client.ID(), "stream_name", streamName)
}</span>
}
func printStatistics(ctx context.Context, consumerID string, processedStreams *sync.Map, streamCount *int32) <span class="cov0" title="0">{
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for </span><span class="cov0" title="0">{
select </span>{
case <-ctx.Done():<span class="cov0" title="0">
return</span>
case <-ticker.C:<span class="cov0" title="0">
count := *streamCount
slog.Info("📊 Statistics", "consumer_id", consumerID, "processed_streams", count)
// Show recent streams
recentCount := 0
processedStreams.Range(func(key, value interface{}) bool </span><span class="cov0" title="0">{
if processedTime, ok := value.(time.Time); ok </span><span class="cov0" title="0">{
if time.Since(processedTime) < 10*time.Second </span><span class="cov0" title="0">{
recentCount++
}</span>
}
<span class="cov0" title="0">return true</span>
})
<span class="cov0" title="0">if recentCount > 0 </span><span class="cov0" title="0">{
slog.Info("📈 Recent activity", "consumer_id", consumerID, "recent_streams", recentCount)
}</span>
}
}
}
</pre>
<pre class="file" id="file1" style="display: none">package impl
import (
"context"
"log/slog"
"os"
"github.com/handcoding-labs/redis-stream-client-go/configs"
)
func (r *RecoverableRedisStreamClient) lbsGroupName() string <span class="cov0" title="0">{
return r.serviceName + configs.GroupSuffix
}</span>
func (r *RecoverableRedisStreamClient) lbsName() string <span class="cov0" title="0">{
return r.serviceName + configs.InputSuffix
}</span>
func (r *RecoverableRedisStreamClient) isContextDone(ctx context.Context) bool <span class="cov0" title="0">{
select </span>{
case <-ctx.Done():<span class="cov0" title="0">
return true</span>
default:<span class="cov0" title="0">
return false</span>
}
}
func (r *RecoverableRedisStreamClient) isStreamProcessingDone(dataStreamName string) bool <span class="cov0" title="0">{
r.streamLocksMutex.Lock()
defer r.streamLocksMutex.Unlock()
return r.streamLocks[dataStreamName] == nil
}</span>
func (r *RecoverableRedisStreamClient) closeOutputChan() <span class="cov0" title="0">{
r.notificationBroker.Close() // stop accepting new sends
r.notificationBroker.Wait() // let run drain the messages from input
close(r.outputChan) // close output channel
}</span>
<pre class="file" id="file2" style="display: none">package impl
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"time"
"github.com/handcoding-labs/redis-stream-client-go/configs"
"github.com/handcoding-labs/redis-stream-client-go/notifs"
"github.com/go-redsync/redsync/v4"
"github.com/redis/go-redis/v9"
)
func (r *RecoverableRedisStreamClient) enableKeyspaceNotifsForExpiredEvents(ctx context.Context) error <span class="cov0" title="0">{
// subscribe to key space events for expiration only
// https://redis.io/docs/latest/develop/use/keyspace-notifications/
existingConfig := r.redisClient.ConfigGet(ctx, configs.NotifyKeyspaceEventsCmd)
configVals, err := existingConfig.Result()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">for _, v := range configVals </span><span class="cov0" title="0">{
if len(v) > 0 </span><span class="cov0" title="0">{
// some config for key space notifications already exists, so exit
if !r.forceOverrideConfig </span><span class="cov0" title="0">{
return fmt.Errorf("detected existing configuration for key space notifications and force override is disabled")
}</span> else<span class="cov0" title="0"> {
slog.Warn("overriding existing keyspace notifications config since force override is set")
}</span>
}
}
<span class="cov0" title="0">res := r.redisClient.ConfigSet(ctx, configs.NotifyKeyspaceEventsCmd, configs.KeyspacePatternForExpiredEvents)
if res.Err() != nil </span><span class="cov0" title="0">{
return res.Err()
}</span>
<span class="cov0" title="0">return nil</span>
}
func (r *RecoverableRedisStreamClient) subscribeToExpiredEvents(ctx context.Context) error <span class="cov0" title="0">{
r.pubSub = r.redisClient.PSubscribe(ctx, configs.ExpiredEventPattern)
r.kspChan = r.pubSub.Channel(
redis.WithChannelHealthCheckInterval(5*time.Second),
redis.WithChannelSendTimeout(r.kspChanTimeout),
redis.WithChannelSize(r.kspChanSize),
)
return nil
}</span>
// This method doesn't return error and just logs because we execute this
// when no consumer was around to recevie notifications and messages were pending.
// So, this method is just recovering those messages and if there is an issue in
// processing them, then erroring out will stop consumer from processing latest streams also.
func (r *RecoverableRedisStreamClient) recoverUnackedLBS(ctx context.Context) <span class="cov0" title="0">{
// nextStart is initialized to empty string to claiming can start
// when it gets populated as 0-0 as a result to auto claim,
// it means there is nothing more to claim or process
nextStart := ""
var unackedMessages []redis.XMessage
for nextStart != configs.StartIDPair </span><span class="cov0" title="0">{
xautoClaimRes := r.redisClient.XAutoClaim(ctx, &redis.XAutoClaimArgs{
Stream: r.lbsName(),
Group: r.lbsGroupName(),
MinIdle: r.lbsIdleTime,
Start: configs.StartIDPair,
Count: int64(r.lbsRecoveryCount),
Consumer: r.consumerID,
})
if xautoClaimRes.Err() != nil </span><span class="cov0" title="0">{
r.logger.Error("error while getting unacked messages", "error", xautoClaimRes.Err())
}</span>
<span class="cov0" title="0">msgs, start := xautoClaimRes.Val()
unackedMessages = append(unackedMessages, msgs...)
nextStart = start</span>
}
<span class="cov0" title="0">if len(unackedMessages) > 0 </span><span class="cov0" title="0">{
r.logger.Info("unacked messages found in LBS for consumer", "pending_count", len(unackedMessages))
}</span> else<span class="cov0" title="0"> {
r.logger.Info("no unacked messages found in LBS for consumer")
}</span>
<span class="cov0" title="0">streams := []redis.XStream{
{
Stream: r.lbsName(),
Messages: unackedMessages,
},
}
// process the message
if err := r.processLBSMessages(ctx, streams, r.rs); err != nil </span><span class="cov0" title="0">{
r.logger.Error("fatal error while processing unacked messages", "error", err)
return
}</span>
}
func (r *RecoverableRedisStreamClient) readLBSStream(ctx context.Context) <span class="cov0" title="0">{
for </span><span class="cov0" title="0">{
// check if context is done
if r.isContextDone(ctx) </span><span class="cov0" title="0">{
r.notificationBroker.Send(ctx, notifs.MakeStreamTerminatedNotif("context done"))
return
}</span>
// blocking read on LBS stream
<span class="cov0" title="0">res := r.redisClient.XReadGroup(ctx, &redis.XReadGroupArgs{
Group: r.lbsGroupName(),
Consumer: r.consumerID,
Streams: []string{r.lbsName(), configs.PendingMsgID},
Block: 0,
})
if res.Err() != nil </span><span class="cov0" title="0">{
if errors.Is(res.Err(), context.Canceled) </span><span class="cov0" title="0">{
r.notificationBroker.Send(ctx, notifs.MakeStreamTerminatedNotif(context.Canceled.Error()))
return
}</span>
<span class="cov0" title="0">r.logger.Error("error while reading from LBS", "error", res.Err())
r.notificationBroker.Send(ctx, notifs.MakeStreamTerminatedNotif(res.Err().Error()))
return</span>
}
<span class="cov0" title="0">if err := r.processLBSMessages(ctx, res.Val(), r.rs); err != nil </span><span class="cov0" title="0">{
r.logger.Error("fatal error while reading lbs", "error", err)
r.notificationBroker.Send(ctx, notifs.MakeStreamTerminatedNotif(err.Error()))
return
}</span>
}
}
func (r *RecoverableRedisStreamClient) processLBSMessages(
ctx context.Context,
streams []redis.XStream,
rs *redsync.Redsync,
) error <span class="cov0" title="0">{
for _, stream := range streams </span><span class="cov0" title="0">{
for _, message := range stream.Messages </span><span class="cov0" title="0">{
// has to be an LBS message
v, ok := message.Values[configs.LBSInput]
if !ok </span><span class="cov0" title="0">{
return fmt.Errorf("message on LBS stream must be keyed with %s", configs.LBSInput)
}</span>
// unmarshal the message
<span class="cov0" title="0">var lbsMessage notifs.LBSInputMessage
val, ok := v.(string)
if !ok </span><span class="cov0" title="0">{
return fmt.Errorf("error while converting lbs message")
}</span>
<span class="cov0" title="0">if err := json.Unmarshal([]byte(val), &lbsMessage); err != nil </span><span class="cov0" title="0">{
return fmt.Errorf("error while unmarshalling LBS message: %w", err)
}</span>
<span class="cov0" title="0">if lbsMessage.DataStreamName == "" </span><span class="cov0" title="0">{
return fmt.Errorf("no data stream specified in LBS message")
}</span>
<span class="cov0" title="0">lbsInfo, err := notifs.CreateByParts(lbsMessage.DataStreamName, message.ID)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
// create mutex
<span class="cov0" title="0">mutex := rs.NewMutex(lbsInfo.FormMutexKey(),
redsync.WithExpiry(r.hbInterval),
redsync.WithFailFast(true),
redsync.WithRetryDelay(10*time.Millisecond),
redsync.WithSetNXOnExtend(),
redsync.WithGenValueFunc(func() (string, error) </span><span class="cov0" title="0">{
return r.consumerID, nil
}</span>))
// lock only once
<span class="cov0" title="0">if err := mutex.Lock(); err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">r.streamLocksMutex.Lock()
r.streamLocks[lbsInfo.DataStreamName] = &StreamLocksInfo{
LBSInfo: lbsInfo,
Mutex: mutex,
AdditionalInfo: lbsMessage.Info,
}
r.streamLocksMutex.Unlock()
r.notificationBroker.Send(ctx, notifs.Make(notifs.StreamAdded, lbsInfo, lbsMessage.Info))
// now, keep extending the lock in a separate go routine
go func() </span><span class="cov0" title="0">{
if err := r.startExtendingKey(ctx, mutex, lbsInfo, lbsMessage.Info); err != nil </span><span class="cov0" title="0">{
r.logger.Error("Error extending key", "error", err, "stream", lbsInfo.DataStreamName)
}</span>
}()
}
}
<span class="cov0" title="0">return nil</span>
}
func (r *RecoverableRedisStreamClient) startExtendingKey(
ctx context.Context,
mutex *redsync.Mutex,
lbsInfo notifs.LBSInfo,
additionalInfo map[string]any,
) error <span class="cov0" title="0">{
extensionFailed := false
defer func() </span><span class="cov0" title="0">{
if extensionFailed </span><span class="cov0" title="0">{
// if client is still interested or is coming back from a delay (GC pause etc) then inform about disowning of stream
r.notificationBroker.Send(ctx, notifs.Make(notifs.StreamDisowned, lbsInfo, additionalInfo))
}</span>
}()
<span class="cov0" title="0">for </span><span class="cov0" title="0">{
// exit extending the key if:
// main context is canceled
if r.isContextDone(ctx) </span><span class="cov0" title="0">{
r.logger.Debug("context done, exiting", "consumer_id", r.consumerID)
return nil
}</span>
// or if DoneStream was called
<span class="cov0" title="0">if r.isStreamProcessingDone(lbsInfo.DataStreamName) </span><span class="cov0" title="0">{
r.logger.Debug("DoneStream called. Stopping key extension.")
return nil
}</span>
<span class="cov0" title="0">if ok, err := mutex.Extend(); !ok || err != nil </span><span class="cov0" title="0">{
extensionFailed = true
return fmt.Errorf("could not extend mutex, err: %s", err)
}</span>
<span class="cov0" title="0">time.Sleep(r.hbInterval / 2)</span>
}
}
func (r *RecoverableRedisStreamClient) listenKsp(ctx context.Context) <span class="cov0" title="0">{
for </span><span class="cov0" title="0">{
select </span>{
case <-ctx.Done():<span class="cov0" title="0">
r.logger.Debug("context done, exiting", "consumer_id", r.consumerID)
r.notificationBroker.Send(ctx, notifs.MakeStreamTerminatedNotif("context done"))
return</span>
case kspNotif := <-r.kspChan:<span class="cov0" title="0">
if kspNotif != nil </span><span class="cov0" title="0">{
r.logger.Debug("ksp notif received", "consumer_id", r.consumerID, "payload", kspNotif.Payload)
lbsInfo, err := notifs.CreateByKspNotification(kspNotif.Payload)
if err != nil </span><span class="cov0" title="0">{
r.logger.Warn("error parsing ksp notification", "ksp_notification", kspNotif)
continue</span>
}
// Try to get additional info from stored stream locks
<span class="cov0" title="0">var additionalInfo map[string]any
r.streamLocksMutex.RLock()
if streamLockInfo, exists := r.streamLocks[lbsInfo.DataStreamName]; exists </span><span class="cov0" title="0">{
additionalInfo = streamLockInfo.AdditionalInfo
}</span>
<span class="cov0" title="0">r.streamLocksMutex.RUnlock()
r.notificationBroker.Send(ctx, notifs.Make(notifs.StreamExpired, lbsInfo, additionalInfo))</span>
}
}
}
}
</pre>
<pre class="file" id="file3" style="display: none">package impl
import (
"fmt"
"time"
"github.com/handcoding-labs/redis-stream-client-go/notifs"
)
type RecoverableRedisOption func(*RecoverableRedisStreamClient) error
// WithLBSIdleTime sets the time after which a message is considered idle and will be recovered
func WithLBSIdleTime(idleTime time.Duration) RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
// idleTime must be greater than 2 * heartbeat interval at least
if idleTime == 0 || idleTime < (2*r.hbInterval) </span><span class="cov0" title="0">{
return fmt.Errorf("idleTime must be greater than 2 * heartbeat interval at least")
}</span>
<span class="cov0" title="0">r.lbsIdleTime = idleTime
return nil</span>
}
}
// WithLBSRecoveryCount sets the number of messages to fetch at a time during recovery
func WithLBSRecoveryCount(count int) RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
if count <= 0 </span><span class="cov0" title="0">{
return fmt.Errorf("recovery count must be greater than 0")
}</span>
<span class="cov0" title="0">r.lbsRecoveryCount = count
return nil</span>
}
}
// WithKspChanSize sets the size of the ksp channel which corresponds to number of
// pub sub notifications that we can receive from redis
func WithKspChanSize(size int) RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
if size <= 0 </span><span class="cov0" title="0">{
return fmt.Errorf("kspChanSize must be a positive number")
}</span>
<span class="cov0" title="0">r.kspChanSize = size
return nil</span>
}
}
// WithKspChanTimeout is the duration after which an outstanding pub sub message
// from redis pub sub is dropped from channel
func WithKspChanTimeout(timeout time.Duration) RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
if timeout == 0 </span><span class="cov0" title="0">{
return fmt.Errorf("timeout cannot be zero value")
}</span>
<span class="cov0" title="0">r.kspChanTimeout = timeout
return nil</span>
}
}
// WithForceConfigOverride when set overrides the redis configuration for
// key space notifications
func WithForceConfigOverride() RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
r.forceOverrideConfig = true
return nil
}</span>
}
// WithOutputChanSize lets the clients set the outputChanSize where different
// notifications are sent
func WithOutputChanSize(size int) RecoverableRedisOption <span class="cov0" title="0">{
return func(r *RecoverableRedisStreamClient) error </span><span class="cov0" title="0">{
if size <= 0 </span><span class="cov0" title="0">{
return fmt.Errorf("outputChan size must be a positive number")
}</span>
<span class="cov0" title="0">r.outputChan = make(chan notifs.RecoverableRedisNotification, size)
return nil</span>
}
}
// WithLogger allows clients to provide their own logger implementation based on slog.Logger
func WithLogger(logger *slog.Logger) RecoverableRedisOption {
return func(r *RecoverableRedisStreamClient) error {
r.logger = logger
return nil
}
}
</pre>
<pre class="file" id="file4" style="display: none">package impl
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"strings"
"sync"
"time"
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v9"
"github.com/redis/go-redis/v9"
"github.com/handcoding-labs/redis-stream-client-go/configs"
"github.com/handcoding-labs/redis-stream-client-go/notifs"
"github.com/handcoding-labs/redis-stream-client-go/types"
)
// StreamLocksInfo holds information needed to operation with data streams and their management for synchronization
type StreamLocksInfo struct {
LBSInfo notifs.LBSInfo
Mutex *redsync.Mutex
AdditionalInfo map[string]any
}
// RecoverableRedisStreamClient is an implementation of the RedisStreamClient interface
type RecoverableRedisStreamClient struct {
// underlying redis client used to interact with redis
redisClient redis.UniversalClient
// consumerID is the unique identifier for the consumer
consumerID string
// kspChan is the channel to read keyspace notifications
kspChan <-chan *redis.Message
// lbsCtxCancelFunc is used to control when to kill go routines spawned as part of lbs
lbsCtxCancelFunc context.CancelFunc
// hbInterval is the interval at which the client sends heartbeats
hbInterval time.Duration
// streamLocks is a map of stream name to LBSInfo for locking
streamLocks map[string]*StreamLocksInfo
// streamLocksMutex protects streamLocks map from concurrent access
streamLocksMutex sync.RWMutex
// serviceName is the name of the service
serviceName string
// redis pub sub subscription
pubSub *redis.PubSub
// outputChan is the channel exposed to clients on which we relay all messages
outputChan chan notifs.RecoverableRedisNotification
// rs is a shared redsync instance used for distributed locks
rs *redsync.Redsync
// lbsIdleTime is the time after which a message is considered idle
lbsIdleTime time.Duration
// lbsRecoveryCount is the number of times a message is recovered
lbsRecoveryCount int
// kspChanSize is the size of kspChan corresponding to redis pub sub channel size
kspChanSize int
// outputChanSize is the size of the outputChan to which clients listen to
outputChanSize int
// kspChanTimeout is the duration after which a pub sub message from redis is dropped
kspChanTimeout time.Duration
// logger for plain json logging
logger *slog.Logger
// forceOverrideConfig indicates if the library should override existing keyspace notifications config
forceOverrideConfig bool
// NotificationBroker handles all messaging to clients
notificationBroker *notifs.NotificationBroker
}
// NewRedisStreamClient creates a new RedisStreamClient
//
// This function creates a new RedisStreamClient with the given redis client and stream name
// Stream is the name of the stream to read from where actual data is transmitted
func NewRedisStreamClient(redisClient redis.UniversalClient, serviceName string,
opts ...RecoverableRedisOption) (types.RedisStreamClient, error) <span class="cov0" title="0">{
// obtain consumer name via kubernetes downward api
podName := os.Getenv(configs.PodName)
podIP := os.Getenv(configs.PodIP)
if podName == "" && podIP == "" </span><span class="cov0" title="0">{
return nil, fmt.Errorf("podName or podIP not found in env")
}</span>
<span class="cov0" title="0">var consumerID string
if len(podName) > 0 </span><span class="cov0" title="0">{
consumerID = configs.RedisConsumerPrefix + podName
}</span> else<span class="cov0" title="0"> {
consumerID = configs.RedisConsumerPrefix + podIP
}</span>
<span class="cov0" title="0">pool := goredis.NewPool(redisClient)
rs := redsync.New(pool)
r := &RecoverableRedisStreamClient{
redisClient: redisClient,
consumerID: consumerID,
kspChan: make(chan *redis.Message, 500),
hbInterval: configs.DefaultHBInterval,
streamLocks: make(map[string]*StreamLocksInfo),
serviceName: serviceName,
outputChan: make(chan notifs.RecoverableRedisNotification, configs.DefaultOutputChanSize),
rs: rs,
lbsIdleTime: configs.DefaultLBSIdleTime,
lbsRecoveryCount: configs.DefaultLBSRecoveryCount,
kspChanSize: configs.DefaultKspChanSize,
kspChanTimeout: configs.DefaultKspChanTimeout,
logger: slog.Default(),
}
for _, opt := range opts </span><span class="cov0" title="0">{
if err := opt(r); err != nil </span><span class="cov0" title="0">{
panic(fmt.Sprintf("invalid option: %v", err))</span>
}
}
// init the notification broker
<span class="cov0" title="0">r.notificationBroker = notifs.NewNotificationBroker(r.outputChan, configs.DefaultOutputChanSize)
return r, nil</span>
}
// ID returns the consumer name that uniquely identifies the consumer
func (r *RecoverableRedisStreamClient) ID() string <span class="cov0" title="0">{
return r.consumerID
}</span>
// Init initializes the RedisStreamClient
//
// This function initializes the RedisStreamClient by enabling keyspace notifications for expired events,
// subscribing to expired events, and starting a blocking read on the LBS stream
// Returns a channel to read messages from the LBS stream. The client should read from this channel and
// process the messages.
func (r *RecoverableRedisStreamClient) Init(ctx context.Context) (<-chan notifs.RecoverableRedisNotification, error) <span class="cov0" title="0">{
keyspaceErr := r.enableKeyspaceNotifsForExpiredEvents(ctx)
if keyspaceErr != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("error while enabling keyspace notifications for expired events: %w", keyspaceErr)
}</span>
<span class="cov0" title="0">expiredErr := r.subscribeToExpiredEvents(ctx)
if expiredErr != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("error while subscribing to expired events: %w", expiredErr)
}</span>
<span class="cov0" title="0">newCtx, cancelFunc := context.WithCancel(ctx)
r.lbsCtxCancelFunc = cancelFunc
// create group
res := r.redisClient.XGroupCreateMkStream(ctx, r.lbsName(), r.lbsGroupName(), configs.StartFromNow)
if res.Err() != nil && !strings.Contains(res.Err().Error(), "BUSYGROUP") </span><span class="cov0" title="0">{
return nil, res.Err()
}</span>
// recovery of unacked LBS messages
<span class="cov0" title="0">r.recoverUnackedLBS(newCtx)
// start blocking read on LBS stream
go r.readLBSStream(newCtx)
// listen to ksp chan
go r.listenKsp(newCtx)
return r.outputChan, nil</span>
}
// Claim claims pending messages from a stream
func (r *RecoverableRedisStreamClient) Claim(ctx context.Context, lbsInfo notifs.LBSInfo) error <span class="cov0" title="0">{
r.logger.Info("claiming stream", "consumer_id", r.consumerID, "mutex_key", lbsInfo,
"timestamp", time.Now().Format(time.RFC3339))
// Claim the stream
res := r.redisClient.XClaim(ctx, &redis.XClaimArgs{
Stream: r.lbsName(),
Group: r.lbsGroupName(),
Consumer: r.consumerID,
MinIdle: r.hbInterval, // one heartbeat interval must have elapsed
Messages: []string{lbsInfo.IDInLBS},
})
if res.Err() != nil </span><span class="cov0" title="0">{
r.logger.Error("error claiming stream", "error", res.Err(), "consumer_id", r.consumerID)
return res.Err()
}</span>
<span class="cov0" title="0">claimed, err := res.Result()
if err != nil </span><span class="cov0" title="0">{
r.logger.Error("error getting claimed stream", "error", err, "consumer_id", r.consumerID,
"mutex_key", lbsInfo.FormMutexKey())
return err
}</span>
<span class="cov0" title="0">if len(claimed) == 0 </span><span class="cov0" title="0">{
return fmt.Errorf("already claimed")
}</span>
<span class="cov0" title="0">mutex := r.rs.NewMutex(lbsInfo.FormMutexKey(),
redsync.WithExpiry(r.hbInterval),
redsync.WithFailFast(true),
redsync.WithRetryDelay(10*time.Millisecond),
redsync.WithSetNXOnExtend(),
redsync.WithGenValueFunc(func() (string, error) </span><span class="cov0" title="0">{
return r.consumerID, nil
}</span>))
// lock once
<span class="cov0" title="0">if err := mutex.Lock(); err != nil </span><span class="cov0" title="0">{
return err
}</span>