/
tunnel.go
75 lines (59 loc) · 1.88 KB
/
tunnel.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
package rstreams
import (
"context"
"github.com/go-redis/redis/v8"
"github.com/pkg/errors"
"github.com/batchcorp/plumber-schemas/build/go/protos/opts"
"github.com/batchcorp/plumber-schemas/build/go/protos/records"
"github.com/batchcorp/plumber/tunnel"
"github.com/batchcorp/plumber/validate"
)
func (r *RedisStreams) Tunnel(ctx context.Context, tunnelOpts *opts.TunnelOptions, tunnelSvc tunnel.ITunnel, errorCh chan<- *records.ErrorRecord) error {
if err := validateTunnelOptions(tunnelOpts); err != nil {
return errors.Wrap(err, "unable to validate tunnel options")
}
llog := r.log.WithField("pkg", "rstreams/tunnel")
if err := tunnelSvc.Start(ctx, "Redis Streams", errorCh); err != nil {
return errors.Wrap(err, "unable to create tunnel")
}
outboundCh := tunnelSvc.Read()
for {
select {
case outbound := <-outboundCh:
for _, streamName := range tunnelOpts.RedisStreams.Args.Streams {
_, err := r.client.XAdd(ctx, &redis.XAddArgs{
Stream: streamName,
ID: tunnelOpts.RedisStreams.Args.WriteId,
Values: map[string]interface{}{
tunnelOpts.RedisStreams.Args.Key: outbound.Blob,
},
}).Result()
if err != nil {
r.log.Errorf("unable to write message to '%s': %s", streamName, err)
continue
}
r.log.Infof("Successfully wrote message to stream '%s' with key '%s' for replay '%s'",
streamName, tunnelOpts.RedisStreams.Args.Key, outbound.ReplayId)
}
case <-ctx.Done():
llog.Debug("context cancelled")
return nil
}
}
return nil
}
func validateTunnelOptions(tunnelOpts *opts.TunnelOptions) error {
if tunnelOpts == nil {
return validate.ErrEmptyTunnelOpts
}
if tunnelOpts.RedisStreams == nil {
return validate.ErrEmptyBackendGroup
}
if tunnelOpts.RedisStreams.Args == nil {
return validate.ErrEmptyBackendArgs
}
if len(tunnelOpts.RedisStreams.Args.Streams) == 0 {
return ErrMissingStream
}
return nil
}