-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathstore.go
More file actions
72 lines (58 loc) · 2.1 KB
/
store.go
File metadata and controls
72 lines (58 loc) · 2.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
package alert
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const (
keyPrefixAlert = "alert" // Base prefix for all alert keys
keyFailures = "cf" // Set for consecutive failure attempt IDs
)
// AlertStore manages alert-related data persistence
type AlertStore interface {
IncrementConsecutiveFailureCount(ctx context.Context, tenantID, destinationID, attemptID string) (int, error)
ResetConsecutiveFailureCount(ctx context.Context, tenantID, destinationID string) error
}
type redisAlertStore struct {
client redis.Cmdable
deploymentID string
}
// NewRedisAlertStore creates a new Redis-backed alert store
func NewRedisAlertStore(client redis.Cmdable, deploymentID string) AlertStore {
return &redisAlertStore{
client: client,
deploymentID: deploymentID,
}
}
func (s *redisAlertStore) IncrementConsecutiveFailureCount(ctx context.Context, tenantID, destinationID, attemptID string) (int, error) {
key := s.getFailuresKey(destinationID)
// Use a transaction to ensure atomicity between SADD, SCARD, and EXPIRE operations.
// SADD is idempotent — adding the same attemptID on replay is a no-op,
// preventing double-counting when messages are redelivered.
pipe := s.client.TxPipeline()
pipe.SAdd(ctx, key, attemptID)
scardCmd := pipe.SCard(ctx, key)
pipe.Expire(ctx, key, 24*time.Hour)
_, err := pipe.Exec(ctx)
if err != nil {
return 0, fmt.Errorf("failed to execute consecutive failure count transaction: %w", err)
}
count, err := scardCmd.Result()
if err != nil {
return 0, fmt.Errorf("failed to get consecutive failure count: %w", err)
}
return int(count), nil
}
func (s *redisAlertStore) ResetConsecutiveFailureCount(ctx context.Context, tenantID, destinationID string) error {
return s.client.Del(ctx, s.getFailuresKey(destinationID)).Err()
}
func (s *redisAlertStore) deploymentPrefix() string {
if s.deploymentID == "" {
return ""
}
return fmt.Sprintf("%s:", s.deploymentID)
}
func (s *redisAlertStore) getFailuresKey(destinationID string) string {
return fmt.Sprintf("%s%s:%s:%s", s.deploymentPrefix(), keyPrefixAlert, destinationID, keyFailures)
}