-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
149 lines (126 loc) · 2.57 KB
/
redis.go
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
package main
import (
"context"
"fmt"
"strconv"
"strings"
"time"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
)
type RequestData struct {
Origin string
VideoID string
ChatID int64
UserID int64
MessageID int
Type int
}
func (d RequestData) ToRedis() (string, string) {
return fmt.Sprintf("%d", d.UserID), fmt.Sprintf("%s:%s:%d:%d:%d", d.Origin, d.VideoID, d.ChatID, d.MessageID, d.Type)
}
const (
originPt = 0
videoIDPt = iota
chatIDPt = iota
messageIDPt = iota
typePt = iota
)
func NewData(key, value string) (*RequestData, error) {
vals := strings.Split(value, ":")
origin := vals[originPt]
videoID := vals[videoIDPt]
userID, err := strconv.ParseInt(key, 10, 64)
if err != nil {
return nil, err
}
chatID, err := strconv.ParseInt(vals[chatIDPt], 10, 64)
if err != nil {
return nil, err
}
messageID, err := strconv.Atoi(vals[messageIDPt])
if err != nil {
return nil, err
}
typ, err := strconv.Atoi(vals[typePt])
if err != nil {
return nil, err
}
return &RequestData{
UserID: userID,
VideoID: videoID,
ChatID: chatID,
MessageID: messageID,
Type: typ,
Origin: origin,
}, nil
}
var (
mehCtx = context.Background()
rdb *redis.Client = redis.NewClient(&redis.Options{
Addr: mustGetEnv("REDIS"),
})
)
func WaitForRedis() {
for {
if err := rdb.Scan(mehCtx, 0, "", 0).Err(); err == nil {
return
}
time.Sleep(time.Second)
}
}
func AddReq(req *RequestData) error {
key, value := req.ToRedis()
return rdb.SAdd(mehCtx, key, value).Err()
}
func DelReq(req *RequestData) error {
key, value := req.ToRedis()
return rdb.SRem(mehCtx, key, value).Err()
}
func ListReqs() <-chan *RequestData {
resC := make(chan *RequestData, 42)
go func() {
var cursor uint64
for {
var keys []string
var err error
keys, cursor, err = rdb.Scan(mehCtx, cursor, "*", 0).Result()
if err != nil {
L.Error(
"Failed to scan redis",
zap.Error(err),
)
close(resC)
return
}
for _, key := range keys {
vals, err := rdb.SMembers(mehCtx, key).Result()
if err != nil {
L.Error(
"Failed to get redis members",
zap.Error(err),
zap.String("key", key),
)
continue
}
for _, val := range vals {
if data, err := NewData(key, val); err != nil {
L.Error(
"Failed to parse redis value",
zap.Error(err),
zap.String("key", key),
zap.String("value", val),
)
} else {
resC <- data
}
}
}
if cursor == 0 {
close(resC)
return
}
}
}()
return resC
}