-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
122 lines (103 loc) · 2.32 KB
/
writer.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
package repli
import (
"context"
"time"
"github.com/redis/go-redis/v9"
log "github.com/sirupsen/logrus"
)
type WriteCommand struct {
Command string
Key string
TTL time.Duration
Bytes []byte
}
type Writer struct {
writeBatchSize int
writeBatchLatency int
C chan *WriteCommand
writer RedisWriter
}
func NewWriter(config *CommonConfig, writeBatchSize, writeBatchLatency int) *Writer {
return &Writer{
writeBatchSize: writeBatchSize,
writeBatchLatency: writeBatchLatency,
C: make(chan *WriteCommand),
writer: config.Writer(),
}
}
func (w *Writer) Close() {
close(w.C)
w.writer.Close()
}
func (w *Writer) Delete(key string) {
w.C <- &WriteCommand{
Command: "DELETE",
Key: key,
}
}
func (w *Writer) Expire(key string, ttl time.Duration) {
w.C <- &WriteCommand{
Command: "EXPIRE",
Key: key,
TTL: ttl,
}
}
func (w *Writer) Restore(key string, ttl time.Duration, value []byte) {
w.C <- &WriteCommand{
Command: "RESTORE",
Key: key,
TTL: ttl,
Bytes: value,
}
}
func (w *Writer) Run(l *log.Entry, metrics *Metrics) {
ctx := context.Background()
var commands []*WriteCommand
for {
select {
case cmd := <-w.C:
commands = append(commands, cmd)
if len(commands) < w.writeBatchSize {
continue
}
case <-time.After(time.Millisecond * time.Duration(w.writeBatchLatency)):
l.Debug("write batch timeout")
}
if len(commands) > 0 {
results, err := w.writer.Pipelined(ctx, func(batch redis.Pipeliner) error {
for _, cmd := range commands {
metrics.Replicated()
switch cmd.Command {
case "DELETE":
batch.Del(ctx, cmd.Key)
case "EXPIRE":
batch.Expire(ctx, cmd.Key, cmd.TTL)
case "RESTORE":
batch.RestoreReplace(ctx, cmd.Key, cmd.TTL, string(cmd.Bytes))
}
}
return nil
})
if err != nil {
l.WithFields(log.Fields{
"error": err,
}).Warn("failed to write full batch")
}
for j, result := range results {
if result.Err() == nil {
continue
}
l.WithFields(log.Fields{
"key": commands[j].Key,
"command": commands[j].Command,
"error": result.Err(),
}).Error("failed to replicate key")
}
commands = nil
}
if len(commands) == 0 {
cmd := <-w.C
commands = append(commands, cmd)
}
}
}