-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgostream.go
304 lines (273 loc) · 8.5 KB
/
gostream.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
package gostream
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"github.com/segmentio/ksuid"
"github.com/sethvargo/go-retry"
"go.uber.org/zap"
"strconv"
"strings"
"sync"
"text/template"
"time"
)
var schemaTemplate *template.Template
const schemaRawTemplate = `
CREATE TABLE IF NOT EXISTS "{{ .OutboxTableName }}" (
idempotency_key TEXT PRIMARY KEY NOT NULL,
stream TEXT NOT NULL,
payload BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL
)
CREATE INDEX IF NOT EXISTS "{{ .OutboxTableName }}_idx_redis_outbox" ON "{{ .OutboxTableName }}" USING BTREE ("created_at");
`
func init() {
schemaTemplate = template.Must(template.New("schema").Parse(schemaRawTemplate))
}
func getSchema(cfg *redisStreamConfig) string {
b := bytes.NewBuffer([]byte{})
if err := schemaTemplate.Execute(b, map[string]string{"OutboxTableName": cfg.outboxTableName}); err != nil {
panic("error executing schemaTemplate: " + err.Error())
}
return b.String()
}
type redisStreamConfig struct {
outboxTableName string
useOutboxTable bool
sqlDriverName string
}
func WithUseOutboxTable(useOutboxTable bool) RedisStreamOption {
return func(cfg *redisStreamConfig) error {
cfg.useOutboxTable = useOutboxTable
return nil
}
}
func WithOutboxTableName(outboxTableName string) RedisStreamOption {
return func(cfg *redisStreamConfig) error {
if len(outboxTableName) == 0 {
return errors.New("outboxTableName is empty")
}
cfg.outboxTableName = outboxTableName
return nil
}
}
func WithSQLDriverName(driverName string) RedisStreamOption {
return func(cfg *redisStreamConfig) error {
if len(driverName) == 0 {
return errors.New("driverName is empty")
}
cfg.sqlDriverName = driverName
return nil
}
}
type RedisStreamOption func(cfg *redisStreamConfig) error
type RedisStream struct {
db *sql.DB
cfg *redisStreamConfig
ctx context.Context
log *zap.Logger
redisClient *redis.Client
emptyOutbox chan struct{}
schemaCreateOnce sync.Once
clientID string
}
type OutboxTable struct {
IdempotencyKey string `json:"idempotency_key"`
Stream string `db:"stream" json:"stream_name"`
Payload []byte `db:"payload" json:"payload"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
type Message struct {
ID string `json:"uuid"`
IdempotencyKey string `json:"idempotency_key"`
Stream string `db:"stream" json:"stream_name"`
Payload []byte `db:"payload" json:"payload"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
func (r *RedisStream) triggerEmptyOutbox() {
r.emptyOutbox <- struct{}{}
}
func (r *RedisStream) PublishMessage(ctx context.Context, tx *sql.Tx, streamName string, payload []byte) (string, error) {
createdAt := time.Now()
idempotencyKey, err := ksuid.NewRandom()
if err != nil {
return "", err
}
_, err = tx.ExecContext(ctx, fmt.Sprintf("INSERT INTO %s (idempotency_key, stream, payload, created_at) VALUES ($1, $2, $3, $4);", r.cfg.outboxTableName), idempotencyKey.String(), streamName, payload, createdAt)
if err == nil {
go func() {
time.Sleep(time.Millisecond * 50)
r.triggerEmptyOutbox()
}()
}
return idempotencyKey.String(), err
}
func (r *RedisStream) emptyOutboxRun(ctx context.Context) {
for {
var breakLoop bool
backoff, err := retry.NewFibonacci(500 * time.Millisecond)
if err != nil {
r.log.Error("Backoff error", zap.Error(err))
}
backoff = retry.WithCappedDuration(time.Second*5, backoff)
err = retry.Do(ctx, backoff, func(ctx context.Context) error {
// TODO: get message
tx, err := r.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
entry := &OutboxTable{}
err = tx.QueryRowContext(ctx, fmt.Sprintf("DELETE FROM %s WHERE idempotency_key = (SELECT idempotency_key FROM %s ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING idempotency_key, stream, payload, created_at", r.cfg.outboxTableName, r.cfg.outboxTableName)).
Scan(&entry.IdempotencyKey, &entry.Stream, &entry.Payload, &entry.CreatedAt)
if err != nil {
if err == sql.ErrNoRows {
breakLoop = true
return nil
}
r.log.Error("Error getting the row", zap.Error(err))
return err
}
// s.log.Info("Found a message, sending to Redis now", zap.Reflect("entry", entry))
err = r.redisClient.XAdd(ctx, &redis.XAddArgs{Stream: entry.Stream, Values: map[string]interface{}{
"idempotency_key": entry.IdempotencyKey,
"payload": base64.StdEncoding.EncodeToString(entry.Payload),
"created_at": entry.CreatedAt.Unix(),
}}).Err()
if err != nil {
return err
}
return tx.Commit()
})
if err != nil {
r.log.Error("emptyOutboxRun error", zap.Error(err))
breakLoop = true
}
if breakLoop {
break
}
}
}
func (r *RedisStream) emptyOutboxLoop() {
duration := time.Second * 2
ticker := time.NewTimer(duration)
for {
select {
case <-ticker.C:
ctx, cancel := context.WithTimeout(r.ctx, duration*10)
r.emptyOutboxRun(ctx)
cancel()
ticker.Reset(duration)
case <-r.emptyOutbox:
ctx, cancel := context.WithTimeout(r.ctx, duration*10)
r.emptyOutboxRun(ctx)
cancel()
ticker.Reset(duration)
case <-r.ctx.Done():
r.log.Info("Stopping RedisStream.emptyOutbox ticker")
return
}
}
}
func (r *RedisStream) init() {
if r.cfg.useOutboxTable {
go r.emptyOutboxLoop()
}
}
func (r *RedisStream) ensureGroupCreated(ctx context.Context, stream, group string) error {
_, err := r.redisClient.XGroupCreateMkStream(ctx, stream, group, "0").Result()
if err != nil && strings.Contains(err.Error(), "already exists") {
return nil
}
return err
}
// TODO: non blocking
func (r *RedisStream) Subscribe(ctx context.Context, group string, stream string, f func(msg *Message) error) error {
if err := r.ensureGroupCreated(ctx, stream, group); err != nil {
return err
}
for {
streamResult, err := r.redisClient.XReadGroup(ctx, &redis.XReadGroupArgs{Consumer: r.clientID, Group: group, Streams: []string{stream, ">"}, Count: 1, Block: time.Second * 5}).Result()
if err != nil {
if err == redis.Nil {
continue
}
r.log.Error("Cannot read streamResult group. Sleeping 3 seconds...", zap.String("streamResult", stream), zap.String("group", group), zap.Error(err))
time.Sleep(time.Second * 3)
continue
}
msg := streamResult[0].Messages[0]
streamName := streamResult[0].Stream
payload, _ := base64.StdEncoding.DecodeString(msg.Values["payload"].(string))
ts, _ := strconv.ParseInt(msg.Values["created_at"].(string), 10, 64)
backoff, _ := retry.NewConstant(time.Second)
err = retry.Do(ctx, retry.WithMaxDuration(time.Second*10, backoff), func(ctx context.Context) error {
if err := f(&Message{
ID: msg.ID,
IdempotencyKey: msg.Values["idempotency_key"].(string),
Stream: streamName,
Payload: payload,
CreatedAt: time.Unix(ts, 0),
}); err != nil {
return retry.RetryableError(err)
}
return nil
})
if err == nil {
backoff, _ := retry.NewConstant(time.Second)
if err := retry.Do(ctx, retry.WithMaxDuration(time.Second*10, backoff), func(ctx context.Context) error {
return retry.RetryableError(r.redisClient.XAck(ctx, streamName, group, msg.ID).Err())
}); err != nil {
r.log.Error("Could not ack the redis message",
zap.String("stream", streamName),
zap.String("group", group),
zap.String("msg.ID", msg.ID),
)
}
r.log.Info("Message processed successfuly", zap.String("stream", streamName),
zap.String("group", group),
zap.String("msg.ID", msg.ID))
} else {
r.log.Error("Could not process message after several retries",
zap.String("stream", streamName),
zap.String("group", group),
zap.String("msg.ID", msg.ID),
)
}
}
}
func NewRedisStream(ctx context.Context, clientID string, redisHostPort string, db *sql.DB, log *zap.Logger, options ...RedisStreamOption) (*RedisStream, error) {
if db == nil {
return nil, errors.New("db is nil")
}
// default config
cfg := &redisStreamConfig{
useOutboxTable: true,
outboxTableName: "redis_outbox",
sqlDriverName: "postgres",
}
for _, option := range options {
if err := option(cfg); err != nil {
return nil, err
}
}
r := &RedisStream{
ctx: ctx,
clientID: clientID,
db: db,
cfg: cfg,
log: log.Named("RedisStream"),
redisClient: redis.NewClient(&redis.Options{
Addr: redisHostPort,
}),
emptyOutbox: make(chan struct{}),
schemaCreateOnce: sync.Once{},
}
r.init()
return r, nil
}