This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 215
/
tailer.go
288 lines (254 loc) · 7.49 KB
/
tailer.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 postgres
import (
"encoding/csv"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/compose/transporter/client"
"github.com/compose/transporter/commitlog"
"github.com/compose/transporter/log"
"github.com/compose/transporter/message"
"github.com/compose/transporter/message/data"
"github.com/compose/transporter/message/ops"
)
var (
_ client.Reader = &Tailer{}
)
// Tailer implements the behavior defined by client.Tailer for interfacing with the MongoDB oplog.
type Tailer struct {
reader client.Reader
replicationSlot string
}
func newTailer(replicationSlot string) client.Reader {
return &Tailer{newReader(), replicationSlot}
}
// Tail does the things
func (t *Tailer) Read(resumeMap map[string]client.MessageSet, filterFn client.NsFilterFunc) client.MessageChanFunc {
return func(s client.Session, done chan struct{}) (chan client.MessageSet, error) {
readFunc := t.reader.Read(resumeMap, filterFn)
msgChan, err := readFunc(s, done)
if err != nil {
return nil, err
}
session := s.(*Session)
out := make(chan client.MessageSet)
go func() {
defer close(out)
// read until reader done
for msg := range msgChan {
out <- msg
}
// start tailing
log.With("db", session.db).With("logical_decoding_slot", t.replicationSlot).Infoln("Listening for changes...")
for {
select {
case <-done:
log.With("db", session.db).Infoln("tailing stopping...")
return
case <-time.After(time.Second):
msgSlice, err := t.pluckFromLogicalDecoding(s.(*Session), filterFn)
if err != nil {
log.With("db", session.db).Errorf("error plucking from logical decoding %v", err)
continue
}
for _, msg := range msgSlice {
out <- msg
}
}
}
}()
return out, nil
}
}
// Use Postgres logical decoding to retrieve the latest changes
func (t *Tailer) pluckFromLogicalDecoding(s *Session, filterFn client.NsFilterFunc) ([]client.MessageSet, error) {
var result []client.MessageSet
dataMatcher := regexp.MustCompile(`(?s)^table ([^\.]+)\.([^:]+): (INSERT|DELETE|UPDATE): (.+)$`) // 1 - schema, 2 - table, 3 - action, 4 - remaining
changesResult, err := s.pqSession.Query(fmt.Sprintf("SELECT * FROM pg_logical_slot_get_changes('%v', NULL, NULL);", t.replicationSlot))
if err != nil {
return result, err
}
for changesResult.Next() {
var (
location string
xid string
d string
)
err = changesResult.Scan(&location, &xid, &d)
if err != nil {
return result, err
}
// Ensure we are getting a data change row
dataMatches := dataMatcher.FindStringSubmatch(d)
if len(dataMatches) == 0 {
continue
}
// Skippable because no primary key on record
// Make sure we are getting changes on valid tables
schemaAndTable := fmt.Sprintf("%v.%v", dataMatches[1], dataMatches[2])
if !filterFn(schemaAndTable) {
continue
}
if dataMatches[4] == "(no-tuple-data)" {
log.With("op", dataMatches[3]).With("schema", schemaAndTable).Infoln("no tuple data")
continue
}
// normalize the action
var action ops.Op
switch dataMatches[3] {
case "INSERT":
action = ops.Insert
case "DELETE":
action = ops.Delete
case "UPDATE":
action = ops.Update
default:
return result, fmt.Errorf("Error processing action from string: %v", d)
}
log.With("op", action).With("table", schemaAndTable).Debugln("received")
docMap := parseLogicalDecodingData(dataMatches[4])
result = append(result, client.MessageSet{
Msg: message.From(action, schemaAndTable, docMap),
Mode: commitlog.Sync,
})
}
return result, err
}
func parseLogicalDecodingData(d string) data.Data {
data := make(data.Data)
var (
label string
labelFinished bool
valueType string
valueTypeFinished bool
openBracketInValueType bool
skippedColon bool
value string // will type switch later
valueEndCharacter string
deferredSingleQuote bool
valueFinished bool
)
valueTypeFinished = false
labelFinished = false
skippedColon = false
deferredSingleQuote = false
openBracketInValueType = false
valueFinished = false
for _, character := range d {
if !labelFinished {
if string(character) == "[" {
labelFinished = true
continue
}
label = fmt.Sprintf("%v%v", label, string(character))
continue
}
if !valueTypeFinished {
if openBracketInValueType && string(character) == "]" { // if a bracket is open, close it
openBracketInValueType = false
} else if string(character) == "]" { // if a bracket is not open, finish valueType
valueTypeFinished = true
continue
} else if string(character) == "[" {
openBracketInValueType = true
}
valueType = fmt.Sprintf("%v%v", valueType, string(character))
continue
}
if !skippedColon && string(character) == ":" {
skippedColon = true
continue
}
if len(valueEndCharacter) == 0 {
if string(character) == "'" {
valueEndCharacter = "'"
continue
}
valueEndCharacter = " "
}
// ending with '
if deferredSingleQuote && string(character) == " " { // we hit an unescaped single quote
valueFinished = true
} else if deferredSingleQuote && string(character) == "'" { // we hit an escaped single quote ''
deferredSingleQuote = false
} else if string(character) == "'" && !deferredSingleQuote { // we hit a first single quote
deferredSingleQuote = true
continue
}
// ending with space
if valueEndCharacter == " " && string(character) == valueEndCharacter {
valueFinished = true
}
// continue parsing
if !valueFinished {
value = fmt.Sprintf("%v%v", value, string(character))
continue
}
// Set and reset
data[label] = casifyValue(value, valueType)
label = ""
labelFinished = false
valueType = ""
valueTypeFinished = false
skippedColon = false
deferredSingleQuote = false
value = ""
valueEndCharacter = ""
valueFinished = false
}
if len(label) > 0 { // ensure we process any line ending abruptly
data[label] = casifyValue(value, valueType)
}
return data
}
func casifyValue(value string, valueType string) interface{} {
findArray := regexp.MustCompile("[[]]$")
switch {
case value == "null":
return nil
case valueType == "integer" || valueType == "smallint" || valueType == "bigint":
i, _ := strconv.Atoi(value)
return i
case valueType == "double precision" || valueType == "numeric" || valueType == "money":
if valueType == "money" { // remove the dollar sign for money
value = value[1:]
}
f, _ := strconv.ParseFloat(value, 64)
return f
case valueType == "boolean":
return value == "true"
case valueType == "jsonb[]" || valueType == "json":
var m map[string]interface{}
json.Unmarshal([]byte(value), &m)
return m
case len(findArray.FindAllString(valueType, 1)) > 0:
var result []interface{}
arrayValueType := findArray.ReplaceAllString(valueType, "")
r := csv.NewReader(strings.NewReader(value[1 : len(value)-1]))
arrayValues, err := r.ReadAll()
if err != nil {
return value
}
for _, arrayValue := range arrayValues[0] {
result = append(result, casifyValue(arrayValue, arrayValueType))
}
return result
case valueType == "timestamp without time zone":
// parse time like 2015-08-21 16:09:02.988058
t, err := time.Parse("2006-01-02 15:04:05.9", value)
if err != nil {
fmt.Printf("\nTime (%v) parse error: %v\n\n", value, err)
}
return t
case valueType == "date":
t, err := time.Parse("2006-01-02", value)
if err != nil {
fmt.Printf("\nTime (%v) parse error: %v\n\n", value, err)
}
return t
}
return value
}