-
-
Notifications
You must be signed in to change notification settings - Fork 577
/
postgresql.go
288 lines (256 loc) · 8.02 KB
/
postgresql.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
package consuming
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/centrifugal/centrifugo/v5/internal/tools"
"github.com/centrifugal/centrifuge"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/sync/errgroup"
)
const (
defaultNumPartitions = 1
defaultPartitionSelectLimit = 100
)
func NewPostgresConsumer(name string, logger Logger, dispatcher Dispatcher, config PostgresConfig) (*PostgresConsumer, error) {
if config.DSN == "" {
return nil, errors.New("dsn is required")
}
if config.OutboxTableName == "" {
return nil, errors.New("outbox_table_name is required")
}
if config.NumPartitions == 0 {
config.NumPartitions = defaultNumPartitions
}
if config.PartitionSelectLimit == 0 {
config.PartitionSelectLimit = defaultPartitionSelectLimit
}
if time.Duration(config.PartitionPollInterval) == 0 {
config.PartitionPollInterval = tools.Duration(300 * time.Millisecond)
}
pool, err := pgxpool.New(context.Background(), config.DSN)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = pool.Ping(ctx)
if err != nil {
return nil, err
}
return &PostgresConsumer{
name: name,
pool: pool,
logger: logger,
dispatcher: dispatcher,
config: config,
lockPrefix: "centrifugo_partition_lock_" + name,
}, nil
}
type PostgresConfig struct {
DSN string `mapstructure:"dsn" json:"dsn"`
OutboxTableName string `mapstructure:"outbox_table_name" json:"outbox_table_name"`
NumPartitions int `mapstructure:"num_partitions" json:"num_partitions"`
PartitionSelectLimit int `mapstructure:"partition_select_limit" json:"partition_select_limit"`
PartitionPollInterval tools.Duration `mapstructure:"partition_poll_interval" json:"partition_poll_interval"`
PartitionNotificationChannel string `mapstructure:"partition_notification_channel" json:"partition_notification_channel"`
}
type PostgresConsumer struct {
name string
pool *pgxpool.Pool
logger Logger
config PostgresConfig
dispatcher Dispatcher
lockPrefix string
}
type PostgresEvent struct {
ID int64
Method string
Payload []byte
Partition int64
}
func (c *PostgresConsumer) listenForNotifications(ctx context.Context, triggerChannels []chan struct{}) error {
conn, err := c.pool.Acquire(ctx)
if err != nil {
return fmt.Errorf("error acquiring connection: %w", err)
}
defer conn.Release()
_, err = conn.Exec(ctx, "LISTEN "+c.config.PartitionNotificationChannel)
if err != nil {
return fmt.Errorf("error executing LISTEN command: %w", err)
}
for {
notification, err := conn.Conn().WaitForNotification(ctx)
if err != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
return fmt.Errorf("error waiting postgresql notifications: %w", err)
}
}
partition, err := strconv.Atoi(notification.Payload)
if err != nil {
c.logger.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error converting postgresql notification", map[string]any{"error": err.Error()}))
continue
}
if partition > len(triggerChannels)-1 {
c.logger.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "outbox partition is larger than configured number", map[string]any{"partition": partition}))
continue
}
select {
case triggerChannels[partition] <- struct{}{}:
default:
}
}
}
func (c *PostgresConsumer) processOnce(ctx context.Context, partition int) (int, error) {
tx, err := c.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
return 0, fmt.Errorf("error starting transaction: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
// Acquire an advisory lock for partition. This allows us to process all the rows
// from partition in order.
lockName := c.lockPrefix + strconv.Itoa(partition)
_, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtext($1))", lockName)
if err != nil {
return 0, fmt.Errorf("unable to acquire advisory lock: %w", err)
}
sql := `
SELECT
id, method, payload, partition
FROM %s
WHERE partition=$1
ORDER BY id ASC
LIMIT $2`
rows, err := tx.Query(ctx, fmt.Sprintf(sql, c.config.OutboxTableName), partition, c.config.PartitionSelectLimit)
if err != nil {
return 0, fmt.Errorf("error selecting outbox events: %w", err)
}
defer rows.Close()
var events []PostgresEvent
numProcessedRows := 0
for rows.Next() {
var event PostgresEvent
err := rows.Scan(&event.ID, &event.Method, &event.Payload, &event.Partition)
if err != nil {
return 0, fmt.Errorf("error scanning event: %w", err)
}
events = append(events, event)
}
err = rows.Err()
if err != nil {
return 0, fmt.Errorf("rows error: %w", err)
}
idsToDelete := make([]int64, 0, len(events))
var dispatchErr error
var mu sync.Mutex
for _, event := range events {
dispatchErr = c.dispatcher.Dispatch(context.Background(), event.Method, event.Payload)
if dispatchErr != nil {
// Stop here, all processed events will be removed, and we will start from this one.
c.logger.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error processing consumed event", map[string]any{"error": err.Error(), "method": event.Method}))
break
} else {
numProcessedRows++
mu.Lock()
idsToDelete = append(idsToDelete, event.ID)
mu.Unlock()
}
}
// Delete processed events.
if len(idsToDelete) > 0 {
_, err = tx.Exec(ctx, fmt.Sprintf("DELETE FROM %s WHERE id = ANY($1)", c.config.OutboxTableName), idsToDelete)
if err != nil {
return 0, fmt.Errorf("error deleting outbox events: %w", err)
}
}
err = tx.Commit(ctx)
if err != nil {
return 0, fmt.Errorf("error commiting transaction: %w", err)
}
return numProcessedRows, dispatchErr
}
func (c *PostgresConsumer) Run(ctx context.Context) error {
defer c.pool.Close()
eg, ctx := errgroup.WithContext(ctx)
// Process outbox faster using LISTEN/NOTIFY.
partitionTriggerChannels := make([]chan struct{}, c.config.NumPartitions)
for i := 0; i < c.config.NumPartitions; i++ {
partitionTriggerChannels[i] = make(chan struct{}, 1)
}
if c.config.PartitionNotificationChannel != "" {
eg.Go(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
err := c.listenForNotifications(ctx, partitionTriggerChannels)
if err != nil {
if errors.Is(err, context.Canceled) {
return ctx.Err()
}
c.logger.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error listening outbox notifications", map[string]any{"error": err.Error()}))
select {
case <-time.After(time.Second):
case <-ctx.Done():
return ctx.Err()
}
}
}
})
}
pollInterval := time.Duration(c.config.PartitionPollInterval)
for i := 0; i < c.config.NumPartitions; i++ {
i := i
eg.Go(func() error {
var backoffDuration time.Duration = 0
retries := 0
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
numRows, err := c.processOnce(ctx, i)
if err != nil {
if errors.Is(err, context.Canceled) {
return err
}
retries++
backoffDuration = getNextBackoffDuration(backoffDuration, retries)
c.logger.Log(centrifuge.NewLogEntry(centrifuge.LogLevelError, "error processing postgresql outbox", map[string]any{"error": err.Error(), "partition": i}))
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoffDuration):
continue
}
}
retries = 0
backoffDuration = 0
if numRows < c.config.PartitionSelectLimit {
// Sleep until poll interval or notification for events in partition.
// If worker processed rows equal to the limit then we don't want to sleep
// here as there could be more events in the table potentially.
// If worker processed less than a limit events - then it means table
// is empty now or some events
select {
case <-time.After(pollInterval):
case <-partitionTriggerChannels[i]:
case <-ctx.Done():
return ctx.Err()
}
}
}
})
}
return eg.Wait()
}