forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
347 lines (293 loc) · 9.6 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
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
package processor
import (
"fmt"
"strconv"
"time"
"github.com/dafanshu/benthos/v3/internal/bloblang/field"
"github.com/dafanshu/benthos/v3/internal/docs"
bredis "github.com/dafanshu/benthos/v3/internal/impl/redis"
"github.com/dafanshu/benthos/v3/internal/interop"
"github.com/dafanshu/benthos/v3/internal/tracing"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/types"
"github.com/go-redis/redis/v7"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeRedis] = TypeSpec{
constructor: NewRedis,
Categories: []Category{
CategoryIntegration,
},
Summary: `
Performs actions against Redis that aren't possible using a
` + "[`cache`](/docs/components/processors/cache)" + ` processor. Actions are
performed for each message of a batch, where the contents are replaced with the
result.`,
Description: `
## Operators
### ` + "`keys`" + `
Returns an array of strings containing all the keys that match the pattern specified by the ` + "`key` field" + `.
### ` + "`scard`" + `
Returns the cardinality of a set, or ` + "`0`" + ` if the key does not exist.
### ` + "`sadd`" + `
Adds a new member to a set. Returns ` + "`1`" + ` if the member was added.
### ` + "`incrby`" + `
Increments the number stored at ` + "`key`" + ` by the message content. If the
key does not exist, it is set to ` + "`0`" + ` before performing the operation.
Returns the value of ` + "`key`" + ` after the increment.`,
FieldSpecs: bredis.ConfigDocs().Add(
docs.FieldCommon("operator", "The [operator](#operators) to apply.").HasOptions("scard", "sadd", "incrby", "keys"),
docs.FieldCommon("key", "A key to use for the target operator.").IsInterpolated(),
docs.FieldAdvanced("retries", "The maximum number of retries before abandoning a request."),
docs.FieldAdvanced("retry_period", "The time to wait before consecutive retry attempts."),
PartsFieldSpec,
),
Examples: []docs.AnnotatedExample{
{
Title: "Querying Cardinality",
Summary: `
If given payloads containing a metadata field ` + "`set_key`" + ` it's possible
to query and store the cardinality of the set for each message using a
` + "[`branch` processor](/docs/components/processors/branch)" + ` in order to
augment rather than replace the message contents:`,
Config: `
pipeline:
processors:
- branch:
processors:
- redis:
url: TODO
operator: scard
key: ${! meta("set_key") }
result_map: 'root.cardinality = this'
`,
},
{
Title: "Running Total",
Summary: `
If we have JSON data containing number of friends visited during covid 19:
` + "```json" + `
{"name":"ash","month":"feb","year":2019,"friends_visited":10}
{"name":"ash","month":"apr","year":2019,"friends_visited":-2}
{"name":"bob","month":"feb","year":2019,"friends_visited":3}
{"name":"bob","month":"apr","year":2019,"friends_visited":1}
` + "```" + `
We can add a field that contains the running total number of friends visited:
` + "```json" + `
{"name":"ash","month":"feb","year":2019,"friends_visited":10,"total":10}
{"name":"ash","month":"apr","year":2019,"friends_visited":-2,"total":8}
{"name":"bob","month":"feb","year":2019,"friends_visited":3,"total":3}
{"name":"bob","month":"apr","year":2019,"friends_visited":1,"total":4}
` + "```" + `
Using the ` + "`incrby`" + ` operator:
`,
Config: `
pipeline:
processors:
- branch:
request_map: |
root = this.friends_visited
meta name = this.name
processors:
- redis:
url: TODO
operator: incrby
key: ${! meta("name") }
result_map: 'root.total = this'
`,
},
},
}
}
//------------------------------------------------------------------------------
// RedisConfig contains configuration fields for the Redis processor.
type RedisConfig struct {
bredis.Config `json:",inline" yaml:",inline"`
Parts []int `json:"parts" yaml:"parts"`
Operator string `json:"operator" yaml:"operator"`
Key string `json:"key" yaml:"key"`
Retries int `json:"retries" yaml:"retries"`
RetryPeriod string `json:"retry_period" yaml:"retry_period"`
}
// NewRedisConfig returns a RedisConfig with default values.
func NewRedisConfig() RedisConfig {
return RedisConfig{
Config: bredis.NewConfig(),
Parts: []int{},
Operator: "scard",
Key: "",
Retries: 3,
RetryPeriod: "500ms",
}
}
//------------------------------------------------------------------------------
// Redis is a processor that performs redis operations
type Redis struct {
parts []int
conf Config
log log.Modular
stats metrics.Type
key *field.Expression
operator redisOperator
client redis.UniversalClient
retryPeriod time.Duration
mCount metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
mRedisRetry metrics.StatCounter
}
// NewRedis returns a Redis processor.
func NewRedis(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
var retryPeriod time.Duration
if tout := conf.Redis.RetryPeriod; len(tout) > 0 {
var err error
if retryPeriod, err = time.ParseDuration(tout); err != nil {
return nil, fmt.Errorf("failed to parse retry period string: %v", err)
}
}
client, err := conf.Redis.Config.Client()
if err != nil {
return nil, err
}
key, err := interop.NewBloblangField(mgr, conf.Redis.Key)
if err != nil {
return nil, fmt.Errorf("failed to parse key expression: %v", err)
}
r := &Redis{
parts: conf.Redis.Parts,
conf: conf,
log: log,
stats: stats,
key: key,
retryPeriod: retryPeriod,
client: client,
mCount: stats.GetCounter("count"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
mRedisRetry: stats.GetCounter("redis.retry"),
}
if r.operator, err = getRedisOperator(conf.Redis.Operator); err != nil {
return nil, err
}
return r, nil
}
//------------------------------------------------------------------------------
type redisOperator func(r *Redis, key string, part types.Part) error
func newRedisKeysOperator() redisOperator {
return func(r *Redis, key string, part types.Part) error {
res, err := r.client.Keys(key).Result()
for i := 0; i <= r.conf.Redis.Retries && err != nil; i++ {
r.log.Errorf("Keys command failed: %v\n", err)
<-time.After(r.retryPeriod)
r.mRedisRetry.Incr(1)
res, err = r.client.Keys(key).Result()
}
if err != nil {
return err
}
iRes := make([]interface{}, 0, len(res))
for _, v := range res {
iRes = append(iRes, v)
}
return part.SetJSON(iRes)
}
}
func newRedisSCardOperator() redisOperator {
return func(r *Redis, key string, part types.Part) error {
res, err := r.client.SCard(key).Result()
for i := 0; i <= r.conf.Redis.Retries && err != nil; i++ {
r.log.Errorf("SCard command failed: %v\n", err)
<-time.After(r.retryPeriod)
r.mRedisRetry.Incr(1)
res, err = r.client.SCard(key).Result()
}
if err != nil {
return err
}
part.Set(strconv.AppendInt(nil, res, 10))
return nil
}
}
func newRedisSAddOperator() redisOperator {
return func(r *Redis, key string, part types.Part) error {
res, err := r.client.SAdd(key, part.Get()).Result()
for i := 0; i <= r.conf.Redis.Retries && err != nil; i++ {
r.log.Errorf("SAdd command failed: %v\n", err)
<-time.After(r.retryPeriod)
r.mRedisRetry.Incr(1)
res, err = r.client.SAdd(key, part.Get()).Result()
}
if err != nil {
return err
}
part.Set(strconv.AppendInt(nil, res, 10))
return nil
}
}
func newRedisIncrByOperator() redisOperator {
return func(r *Redis, key string, part types.Part) error {
valueInt, err := strconv.Atoi(string(part.Get()))
if err != nil {
return err
}
res, err := r.client.IncrBy(key, int64(valueInt)).Result()
for i := 0; i <= r.conf.Redis.Retries && err != nil; i++ {
r.log.Errorf("incrby command failed: %v\n", err)
<-time.After(r.retryPeriod)
r.mRedisRetry.Incr(1)
res, err = r.client.IncrBy(key, int64(valueInt)).Result()
}
if err != nil {
return err
}
part.Set(strconv.AppendInt(nil, res, 10))
return nil
}
}
func getRedisOperator(opStr string) (redisOperator, error) {
switch opStr {
case "keys":
return newRedisKeysOperator(), nil
case "sadd":
return newRedisSAddOperator(), nil
case "scard":
return newRedisSCardOperator(), nil
case "incrby":
return newRedisIncrByOperator(), nil
}
return nil, fmt.Errorf("operator not recognised: %v", opStr)
}
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (r *Redis) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
r.mCount.Incr(1)
newMsg := msg.Copy()
proc := func(index int, span *tracing.Span, part types.Part) error {
key := r.key.String(index, newMsg)
if err := r.operator(r, key, part); err != nil {
r.mErr.Incr(1)
r.log.Debugf("Operator failed for key '%s': %v\n", key, err)
return err
}
return nil
}
IteratePartsWithSpanV2(TypeRedis, r.parts, newMsg, proc)
r.mBatchSent.Incr(1)
r.mSent.Incr(int64(newMsg.Len()))
return []types.Message{newMsg}, nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (r *Redis) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (r *Redis) WaitForClose(timeout time.Duration) error {
r.client.Close()
return nil
}
//------------------------------------------------------------------------------