-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.go
195 lines (160 loc) · 5.22 KB
/
events.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
package events
import (
"encoding/json"
"os"
"os/signal"
"runtime/debug"
log "github.com/Sirupsen/logrus"
"github.com/nats-io/go-nats-streaming"
"github.com/spf13/viper"
"github.com/Bnei-Baruch/archive-backend/common"
"github.com/Bnei-Baruch/archive-backend/es"
"github.com/Bnei-Baruch/archive-backend/utils"
)
var indexer *es.Indexer
var indexerQueue WorkQueue
func shutDown(signalChan chan os.Signal, sc stan.Conn, indexerQueue WorkQueue, cleanupDone chan bool) {
for _ = range signalChan {
log.Info("Shutting down...")
log.Info("Closing connection to nats")
// Do not unsubscribe a durable on exit, except if asked to.
sc.Close()
log.Info("Closing indexer queue")
indexerQueue.Close()
cleanupDone <- true
}
}
func RunListener() {
log.SetLevel(log.InfoLevel)
var err error
log.Info("Initialize data stores")
common.Init()
defer common.Shutdown()
log.Info("Initialize connection to nats")
natsURL := viper.GetString("nats.url")
natsClientID := viper.GetString("nats.client-id")
natsClusterID := viper.GetString("nats.cluster-id")
natsSubject := viper.GetString("nats.subject")
sc, err := stan.Connect(natsClusterID, natsClientID, stan.NatsURL(natsURL))
utils.Must(err)
defer sc.Close()
log.Info("Subscribing to nats subject")
var startOpt stan.SubscriptionOption
if viper.GetBool("nats.durable") == true {
startOpt = stan.DurableName(viper.GetString("nats.durable-name"))
} else {
startOpt = stan.DeliverAllAvailable()
}
_, err = sc.Subscribe(natsSubject, msgHandler, startOpt, stan.SetManualAckMode())
utils.Must(err)
log.Info("Initialize search engine indexer")
esc, err := common.ESC.GetClient()
if err != nil {
log.Fatalf("Elastic is not available in RunListener(): %+v", err)
}
if viper.GetBool("server.fake-indexer") {
indexer, err = es.MakeFakeIndexer(common.DB, esc)
utils.Must(err)
} else {
err, date := es.ProdIndexDate(esc)
utils.Must(err)
indexer, err = es.MakeProdIndexer(date, common.DB, esc)
utils.Must(err)
}
log.Info("Initialize indexer queue")
indexerQueue = new(IndexerQueue)
indexerQueue.Init()
// wait for kill
signalChan := make(chan os.Signal, 1)
cleanupDone := make(chan bool)
signal.Notify(signalChan, os.Interrupt)
go func() { shutDown(signalChan, sc, indexerQueue, cleanupDone) }()
log.Info("Press Ctrl+C to terminate")
<-cleanupDone
}
// Data struct for unmarshaling data from nats
type Data struct {
ID string `json:"id"`
Type string `json:"type"`
ReplicationLocation string `json:"rloc"`
Payload map[string]interface{} `json:"payload"`
}
type MessageHandler func(d Data)
var messageHandlers = map[string]MessageHandler{
E_COLLECTION_CREATE: CollectionCreate,
E_COLLECTION_DELETE: CollectionDelete,
E_COLLECTION_UPDATE: CollectionUpdate,
E_COLLECTION_PUBLISHED_CHANGE: CollectionPublishedChange,
E_COLLECTION_CONTENT_UNITS_CHANGE: CollectionContentUnitsChange,
E_CONTENT_UNIT_CREATE: ContentUnitCreate,
E_CONTENT_UNIT_DELETE: ContentUnitDelete,
E_CONTENT_UNIT_UPDATE: ContentUnitUpdate,
E_CONTENT_UNIT_PUBLISHED_CHANGE: ContentUnitPublishedChange,
E_CONTENT_UNIT_DERIVATIVES_CHANGE: ContentUnitDerivativesChange,
E_CONTENT_UNIT_SOURCES_CHANGE: ContentUnitSourcesChange,
E_CONTENT_UNIT_TAGS_CHANGE: ContentUnitTagsChange,
E_CONTENT_UNIT_PERSONS_CHANGE: ContentUnitPersonsChange,
E_CONTENT_UNIT_PUBLISHERS_CHANGE: ContentUnitPublishersChange,
E_FILE_PUBLISHED: FilePublished,
E_FILE_REPLACE: FileReplace,
E_FILE_INSERT: FileInsert,
E_FILE_UPDATE: FileUpdate,
E_FILE_REMOVE: FileUpdate,
E_SOURCE_CREATE: SourceCreate,
E_SOURCE_UPDATE: SourceUpdate,
E_TAG_CREATE: TagCreate,
E_TAG_UPDATE: TagUpdate,
E_PERSON_CREATE: PersonCreate,
E_PERSON_DELETE: PersonDelete,
E_PERSON_UPDATE: PersonUpdate,
E_PUBLISHER_CREATE: PublisherCreate,
E_PUBLISHER_UPDATE: PublisherUpdate,
E_BLOG_POST_CREATE: BlogPostCreate,
E_BLOG_POST_UPDATE: BlogPostUpdate,
E_BLOG_POST_DELETE: BlogPostDelete,
E_TWEET_CREATE: TweetCreate,
E_TWEET_UPDATE: TweetUpdate,
E_TWEET_DELETE: TweetDelete,
}
// msgHandler checks message type and calls "eventHandler"
func msgHandler(msg *stan.Msg) {
// don't panic !
defer func() {
if rval := recover(); rval != nil {
log.Errorf("msgHandler panic: %v while handling %v", rval, msg)
debug.PrintStack()
}
}()
var d Data
err := json.Unmarshal(msg.Data, &d)
if err != nil {
log.Errorf("json.Unmarshal error: %s\n", err)
}
handler, ok := messageHandlers[d.Type]
if !ok {
log.Errorf("Unknown event type: %v", d)
// Acknowledge the message so we won't stuck on it
msg.Ack()
}
if d.ReplicationLocation != "" {
log.Infof("Replication location: %s", d.ReplicationLocation)
var synced bool
err := common.DB.
QueryRow("SELECT pg_last_xlog_replay_location() >= $1", d.ReplicationLocation).
Scan(&synced)
if err != nil {
log.Errorf("Check replica is synced: %+v", err)
return
}
if !synced {
log.Infof("Replica not synced: %s", d.ReplicationLocation)
// sleep maybe ?
//time.Sleep(500 * time.Millisecond)
return
}
}
// Acknowledge the message
msg.Ack()
log.Infof("Handling %+v", d)
handler(d)
}