forked from kyleconroy/pgoutput
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsub.go
205 lines (166 loc) · 4.72 KB
/
sub.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
package pgoutput
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/jackc/pgx"
)
type Subscription struct {
Name string
Publication string
WaitTimeout time.Duration
StatusTimeout time.Duration
conn *pgx.ReplicationConn
maxWal uint64
walRetain uint64
walFlushed uint64
failOnHandler bool
// Mutex is used to prevent reading and writing to a connection at the same time
sync.Mutex
}
type Handler func(Message, uint64) error
func NewSubscription(conn *pgx.ReplicationConn, name, publication string, walRetain uint64, failOnHandler bool) *Subscription {
return &Subscription{
Name: name,
Publication: publication,
WaitTimeout: 1 * time.Second,
StatusTimeout: 10 * time.Second,
conn: conn,
walRetain: walRetain,
failOnHandler: failOnHandler,
}
}
func pluginArgs(version, publication string) string {
return fmt.Sprintf(`"proto_version" '%s', "publication_names" '%s'`, version, publication)
}
// CreateSlot creates a replication slot if it doesn't exist
func (s *Subscription) CreateSlot() (err error) {
// If creating the replication slot fails with code 42710, this means
// the replication slot already exists.
if err = s.conn.CreateReplicationSlot(s.Name, "pgoutput"); err != nil {
pgerr, ok := err.(pgx.PgError)
if !ok || pgerr.Code != "42710" {
return
}
err = nil
}
return
}
func (s *Subscription) sendStatus(walWrite, walFlush uint64) error {
if walFlush > walWrite {
return fmt.Errorf("walWrite should be >= walFlush")
}
s.Lock()
defer s.Unlock()
k, err := pgx.NewStandbyStatus(walFlush, walFlush, walWrite)
if err != nil {
return fmt.Errorf("error creating status: %s", err)
}
if err = s.conn.SendStandbyStatus(k); err != nil {
return err
}
return nil
}
// Flush sends the status message to server indicating that we've fully applied all of the events until maxWal.
// This allows PostgreSQL to purge it's WAL logs
func (s *Subscription) Flush() error {
wp := atomic.LoadUint64(&s.maxWal)
err := s.sendStatus(wp, wp)
if err == nil {
atomic.StoreUint64(&s.walFlushed, wp)
}
return err
}
// Start replication and block until error or ctx is canceled
func (s *Subscription) Start(ctx context.Context, startLSN uint64, h Handler) (err error) {
err = s.conn.StartReplication(s.Name, startLSN, -1, pluginArgs("1", s.Publication))
if err != nil {
return fmt.Errorf("failed to start replication: %s", err)
}
s.maxWal = startLSN
sendStatus := func() error {
walPos := atomic.LoadUint64(&s.maxWal)
walLastFlushed := atomic.LoadUint64(&s.walFlushed)
// Confirm only walRetain bytes in past
// If walRetain is zero - will confirm current walPos as flushed
walFlush := walPos - s.walRetain
if walLastFlushed > walFlush {
// If there was a manual flush - report it's position until we're past it
walFlush = walLastFlushed
} else if walFlush < 0 {
// If we have less than walRetain bytes - just report zero
walFlush = 0
}
return s.sendStatus(walPos, walFlush)
}
go func() {
tick := time.NewTicker(s.StatusTimeout)
defer tick.Stop()
for {
select {
case <-tick.C:
if err = sendStatus(); err != nil {
return
}
case <-ctx.Done():
return
}
}
}()
for {
select {
case <-ctx.Done():
// Send final status and exit
if err = sendStatus(); err != nil {
return fmt.Errorf("Unable to send final status: %s", err)
}
return
default:
var message *pgx.ReplicationMessage
wctx, cancel := context.WithTimeout(ctx, s.WaitTimeout)
s.Lock()
message, err = s.conn.WaitForReplicationMessage(wctx)
s.Unlock()
cancel()
if err == context.DeadlineExceeded {
continue
} else if err == context.Canceled {
return
} else if err != nil {
return fmt.Errorf("replication failed: %s", err)
}
if message == nil {
return fmt.Errorf("replication failed: nil message received, should not happen")
}
if message.WalMessage != nil {
var logmsg Message
walStart := message.WalMessage.WalStart
// Skip stuff that's in the past
if walStart > 0 && walStart <= startLSN {
continue
}
if walStart > atomic.LoadUint64(&s.maxWal) {
atomic.StoreUint64(&s.maxWal, walStart)
}
logmsg, err = Parse(message.WalMessage.WalData)
if err != nil {
return fmt.Errorf("invalid pgoutput message: %s", err)
}
// Ignore the error from handler for now
if err = h(logmsg, walStart); err != nil && s.failOnHandler {
return
}
} else if message.ServerHeartbeat != nil {
if message.ServerHeartbeat.ReplyRequested == 1 {
if err = sendStatus(); err != nil {
return
}
}
} else {
return fmt.Errorf("No WalMessage/ServerHeartbeat defined in packet, should not happen")
}
}
}
}