This repository has been archived by the owner on Dec 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
222 lines (191 loc) Β· 5.26 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"net/url"
"os"
"os/signal"
"strings"
"time"
logger "github.com/blendle/go-logger"
"github.com/blendle/pg2kafka/eventqueue"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/lib/pq"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var (
topicNamespace string
version string
)
// Producer is the minimal required interface pg2kafka requires to produce
// events to a kafka topic.
type Producer interface {
Close()
Flush(int) int
Produce(*kafka.Message, chan kafka.Event) error
}
func main() {
conf := &logger.Config{
App: "pg2kafka",
Tier: "stream-processor",
Version: version,
Production: os.Getenv("ENV") == "production",
Environment: os.Getenv("ENV"),
}
logger.Init(conf)
conninfo := os.Getenv("DATABASE_URL")
topicNamespace = parseTopicNamespace(os.Getenv("TOPIC_NAMESPACE"), parseDatabaseName(conninfo))
eq, err := eventqueue.New(conninfo)
if err != nil {
logger.L.Fatal("Error opening db connection", zap.Error(err))
}
defer func() {
if cerr := eq.Close(); cerr != nil {
logger.L.Fatal("Error closing db connection", zap.Error(cerr))
}
}()
if os.Getenv("PERFORM_MIGRATIONS") == "true" {
if cerr := eq.ConfigureOutboundEventQueueAndTriggers("./sql"); cerr != nil {
logger.L.Fatal("Error configuring outbound_event_queue and triggers", zap.Error(cerr))
}
} else {
logger.L.Info("Not performing database migrations due to missing `PERFORM_MIGRATIONS`.")
}
producer := setupProducer()
defer producer.Close()
defer producer.Flush(1000)
reportProblem := func(ev pq.ListenerEventType, err error) {
if err != nil {
logger.L.Error("Error handling postgres notify", zap.Error(err))
}
}
listener := pq.NewListener(conninfo, 10*time.Second, time.Minute, reportProblem)
if err := listener.Listen("outbound_event_queue"); err != nil {
logger.L.Error("Error listening to pg", zap.Error(err))
}
defer func() {
if cerr := listener.Close(); cerr != nil {
logger.L.Error("Error closing listener", zap.Error(cerr))
}
}()
// Process any events left in the queue
processQueue(producer, eq)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
logger.L.Info("pg2kafka is now listening to notifications")
waitForNotification(listener, producer, eq, signals)
}
// ProcessEvents queries the database for unprocessed events and produces them
// to kafka.
func ProcessEvents(p Producer, eq *eventqueue.Queue) {
events, err := eq.FetchUnprocessedRecords()
if err != nil {
logger.L.Error("Error listening to pg", zap.Error(err))
}
produceMessages(p, events, eq)
}
func processQueue(p Producer, eq *eventqueue.Queue) {
pageCount, err := eq.UnprocessedEventPagesCount()
if err != nil {
logger.L.Fatal("Error selecting count", zap.Error(err))
}
for i := 0; i <= pageCount; i++ {
ProcessEvents(p, eq)
}
}
func waitForNotification(
l *pq.Listener,
p Producer,
eq *eventqueue.Queue,
signals chan os.Signal,
) {
for {
select {
case <-l.Notify:
processQueue(p, eq)
case <-time.After(90 * time.Second):
go func() {
err := l.Ping()
if err != nil {
logger.L.Fatal("Error pinging listener", zap.Error(err))
}
}()
case <-signals:
return
}
}
}
func produceMessages(p Producer, events []*eventqueue.Event, eq *eventqueue.Queue) {
deliveryChan := make(chan kafka.Event)
for _, event := range events {
msg, err := json.Marshal(event)
if err != nil {
logger.L.Fatal("Error parsing event", zap.Error(err))
}
topic := topicName(event.TableName)
message := &kafka.Message{
TopicPartition: kafka.TopicPartition{
Topic: &topic,
Partition: kafka.PartitionAny, // nolint: gotype
},
Value: msg,
Key: event.ExternalID,
Timestamp: event.CreatedAt,
}
if os.Getenv("DRY_RUN") != "" {
logger.L.Info("Would produce message", zap.Any("message", message))
} else {
err = p.Produce(message, deliveryChan)
if err != nil {
logger.L.Fatal("Failed to produce", zap.Error(err))
}
e := <-deliveryChan
result := e.(*kafka.Message)
if result.TopicPartition.Error != nil {
logger.L.Fatal("Delivery failed", zap.Error(result.TopicPartition.Error))
}
}
err = eq.MarkEventAsProcessed(event.ID)
if err != nil {
logger.L.Fatal("Error marking record as processed", zap.Error(err))
}
}
}
func setupProducer() Producer {
broker := os.Getenv("KAFKA_BROKER")
if broker == "" {
panic("missing KAFKA_BROKER environment")
}
hostname, err := os.Hostname()
if err != nil {
hostname = os.Getenv("HOSTNAME")
}
p, err := kafka.NewProducer(&kafka.ConfigMap{
"client.id": hostname,
"bootstrap.servers": broker,
"partitioner": "murmur2",
"compression.codec": "snappy",
})
if err != nil {
panic(errors.Wrap(err, "failed to setup producer"))
}
return p
}
func topicName(tableName string) string {
return fmt.Sprintf("pg2kafka.%v.%v", topicNamespace, tableName)
}
func parseDatabaseName(conninfo string) string {
dbURL, err := url.Parse(conninfo)
if err != nil {
logger.L.Fatal("Error parsing db connection string", zap.Error(err))
}
return strings.TrimPrefix(dbURL.Path, "/")
}
func parseTopicNamespace(topicNamespace string, databaseName string) string {
s := databaseName
if topicNamespace != "" {
s = topicNamespace + "." + s
}
return s
}