-
Notifications
You must be signed in to change notification settings - Fork 5
/
seawatcher.go
529 lines (393 loc) · 13.8 KB
/
seawatcher.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package seawa
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/url"
"sync"
"time"
"github.com/benleb/gloomberg/internal"
"github.com/benleb/gloomberg/internal/gbl"
"github.com/benleb/gloomberg/internal/nemo/gloomberg"
"github.com/benleb/gloomberg/internal/nemo/osmodels"
"github.com/benleb/gloomberg/internal/seawa/models"
"github.com/benleb/gloomberg/internal/style"
"github.com/benleb/gloomberg/internal/utils/hooks"
"github.com/charmbracelet/log"
"github.com/mitchellh/mapstructure"
"github.com/nshafer/phx"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/redis/rueidis"
"github.com/spf13/viper"
"go.uber.org/zap"
)
type SeaWatcher struct {
// channel for events received from the opensea stream
receivedEvents chan map[string]interface{}
// phoenix channels client
phoenixSocket *phx.Socket
// subscribed phoenix channels
channels map[string]*phx.Channel
// subscribed slugs/events
// subscriptions map[osmodels.EventType]map[string]func()
subscriptions map[string]map[osmodels.EventType]func()
// redis client
rdb rueidis.Client
gb *gloomberg.Gloomberg
mu *sync.Mutex
}
var (
availableEventTypes = []osmodels.EventType{osmodels.ItemListed, osmodels.ItemReceivedBid, osmodels.ItemMetadataUpdated} // , osmodels.CollectionOffer} //, osmodels.ItemMetadataUpdated} // ItemMetadataUpdated, ItemCancelled
eventsReceivedTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "gloomberg_oswatcher_events_received_total",
Help: "The total number of received events from the OpenSea api/stream",
})
)
// func NewSeaWatcher(apiToken string, rdb rueidis.Client) *SeaWatcher {.
func NewSeaWatcher(apiToken string, gb *gloomberg.Gloomberg) *SeaWatcher {
if apiToken == "" {
log.Info("no OpenSea api token provided, skipping OpenSea stream api")
return nil
}
endpointURL := fmt.Sprint(osmodels.StreamAPIEndpoint, "?token=", apiToken)
endpoint, err := url.Parse(endpointURL)
if err != nil {
log.Info(err)
return nil
}
sw := &SeaWatcher{
receivedEvents: make(chan map[string]interface{}, 1024),
subscriptions: make(map[string]map[osmodels.EventType]func()),
channels: make(map[string]*phx.Channel),
gb: gb,
rdb: gb.Rdb,
mu: &sync.Mutex{},
}
// create phoenix socket
sw.phoenixSocket = phx.NewSocket(endpoint)
sw.phoenixSocket.Logger = phx.NewCustomLogger(phx.LoggerLevel(phx.LogWarning), zap.NewStdLog(gbl.Log.Desugar()))
// exponential backoff for reconnects
sw.phoenixSocket.ReconnectAfterFunc = func(attempt int) time.Duration {
// max waitTime is 2^7 = 128sec
waitTime := time.Second * time.Duration(math.Pow(2.0, float64(int(math.Min(float64(attempt), 7)))))
sw.Prf("❌ reconnecting to OpenSea failed (#%d) 😩 trying again in %dsec..", attempt, int(waitTime.Seconds()))
return waitTime
}
// error function
sw.phoenixSocket.OnError(func(err error) { gbl.Log.Errorf("❌ seawa socket error: %+v", err) })
// called on successful connection to the socket/OpenSea
sw.phoenixSocket.OnOpen(func() {
sw.Pr("✅ connected to the OpenSea stream")
})
// called on disconnect/connection breaks to the socket/OpenSea
sw.phoenixSocket.OnClose(func() {
sw.Pr("❕ connection to OpenSea closed, trying to reconnect...")
err := sw.phoenixSocket.Reconnect()
if err != nil {
sw.Prf("❌ reconnecting to OpenSea stream failed: %s", err)
}
})
// initial connection to the socket/OpenSea
if sw.phoenixSocket != nil {
sw.Pr("connecting to OpenSea...")
if err := sw.phoenixSocket.Connect(); err != nil {
socketError := errors.New("OpenSea stream socket connection failed: " + err.Error())
sw.Prf("❌ socket error: %s", socketError.Error())
return nil
}
}
// start worker for managing subscriptions
go sw.WorkerMgmtChannel()
return sw
}
// Pr prints messages from seawatcher to the terminal.
func (sw *SeaWatcher) Pr(message string) {
sw.gb.PrWithKeywordAndIcon("🌊", style.OpenSea("seawa"), message)
}
// Prf formats and prints messages from seawatcher to the terminal.
func (sw *SeaWatcher) Prf(format string, a ...interface{}) {
sw.Pr(fmt.Sprintf(format, a...))
}
func (sw *SeaWatcher) EventChannel() chan map[string]interface{} {
return sw.receivedEvents
}
func (sw *SeaWatcher) ActiveSubscriptions() map[string]map[osmodels.EventType]func() {
return sw.subscriptions
}
// eventHandler handles incoming stream api events and forwards them as map.
func (sw *SeaWatcher) eventHandler(response any) {
eventsReceivedTotal.Inc()
rawEvent, ok := response.(map[string]interface{})
if !ok {
log.Errorf("⚓️❌ error in type assertion of received event: %+v", response)
return
}
itemEventType, ok := rawEvent["event_type"].(string)
if !ok {
log.Warnf("⚓️ 🤷♀️ unknown event type: %s", rawEvent["event_type"])
return
}
// decode event
var metadata *mapstructure.Metadata
// decoder config
decoderConfig := &mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
hooks.StringToAddressHookFunc(),
hooks.StringToHashHookFunc(),
hooks.StringToBigIntHookFunc(),
models.StringToNftIDHookFunc(),
mapstructure.OrComposeDecodeHookFunc(
hooks.StringToUnixTimeHookFunc(),
mapstructure.StringToTimeHookFunc(time.RFC3339),
),
),
Metadata: metadata,
}
switch osmodels.EventType(itemEventType) {
// item listed
case osmodels.ItemListed:
var event *models.ItemListed
decoderConfig.Result = &event
decoder, _ := mapstructure.NewDecoder(decoderConfig)
err := decoder.Decode(rawEvent)
if err != nil {
log.Info("⚓️❌ decoding incoming %s event failed: %s", style.Bold(itemEventType), err)
return
}
// push to eventHub for further processing
sw.gb.In.ItemListed <- event
case osmodels.ItemReceivedBid:
var event *models.ItemReceivedBid
decoderConfig.Result = &event
decoder, _ := mapstructure.NewDecoder(decoderConfig)
err := decoder.Decode(rawEvent)
if err != nil {
log.Info("⚓️❌ decoding incoming %s event failed: %s", style.Bold(itemEventType), err)
return
}
// push to eventHub for further processing
sw.gb.In.ItemReceivedBid <- event
case osmodels.CollectionOffer:
var event *models.CollectionOffer
decoderConfig.Result = &event
decoder, _ := mapstructure.NewDecoder(decoderConfig)
err := decoder.Decode(rawEvent)
if err != nil {
log.Infof("⚓️❌ decoding incoming %s event failed: %s", style.Bold(itemEventType), err)
return
}
// push to eventHub for further processing
sw.gb.In.CollectionOffer <- event
}
}
func (sw *SeaWatcher) DecodeItemReceivedBidEvent(itemEvent map[string]interface{}) (osmodels.ItemReceivedBidEvent, error) {
var collectionOfferEvent osmodels.ItemReceivedBidEvent
decodeHooks := mapstructure.ComposeDecodeHookFunc(
hooks.StringToAddressHookFunc(),
)
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: decodeHooks,
Result: &collectionOfferEvent,
})
err := decoder.Decode(itemEvent)
if err != nil {
sw.Prf("⚓️❌ decoding incoming OpenSea stream api ItemReceivedBidEvent failed: %s", err)
return osmodels.ItemReceivedBidEvent{}, err
}
return collectionOfferEvent, err
}
func (sw *SeaWatcher) DecodeCollectionOfferEvent(itemEvent map[string]interface{}) (osmodels.CollectionOfferEvent, error) {
var collectionOfferEvent osmodels.CollectionOfferEvent
decodeHooks := mapstructure.ComposeDecodeHookFunc(
hooks.StringToAddressHookFunc(),
)
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: decodeHooks,
Result: &collectionOfferEvent,
})
err := decoder.Decode(itemEvent)
if err != nil {
sw.Prf("⚓️❌ decoding incoming OpenSea stream api collection offer event failed: %s", err)
return osmodels.CollectionOfferEvent{}, err
}
return collectionOfferEvent, err
}
func (sw *SeaWatcher) SubscribeForSlug(slug string) bool {
sw.mu.Lock()
alreadySubscribed := sw.subscriptions[slug]
if alreadySubscribed != nil {
sw.mu.Unlock()
log.Debugf("⚓️ ☕️ already subscribed to OpenSea events for %s", slug)
return false
}
sw.subscriptions[slug] = make(map[osmodels.EventType]func())
for _, eventType := range availableEventTypes {
sw.subscriptions[slug][eventType] = sw.on(eventType, slug, sw.eventHandler)
}
sw.mu.Unlock()
if collection := sw.gb.CollectionDB.GetCollectionForSlug(slug); collection != nil {
log.Debugf("⏮️ resetting stats for %s", slug)
collection.ResetStats()
}
return true
}
func (sw *SeaWatcher) UnubscribeForSlug(slug string) bool {
sw.mu.Lock()
slugSubscriptions := sw.subscriptions[slug]
sw.mu.Unlock()
if slugSubscriptions != nil {
// unsubscribe
for _, unsubscribe := range slugSubscriptions {
unsubscribe()
}
// remove slug
sw.mu.Lock()
sw.subscriptions[slug] = nil
sw.mu.Unlock()
return true
}
log.Debugf("unsubscribed %s from opense events", slug)
return false
}
func (sw *SeaWatcher) IsSubscribed(slug string) bool {
sw.mu.Lock()
alreadySubscribed, ok := sw.subscriptions[slug]
sw.mu.Unlock()
if ok && alreadySubscribed != nil {
return true
}
return false
}
func (sw *SeaWatcher) createChannel(topic string) *phx.Channel {
channel := sw.phoenixSocket.Channel(topic, nil)
join, err := channel.Join()
if err != nil {
sw.Prf("⚓️❌ failed to join channel: %s", err)
return nil
}
join.Receive("ok", func(_ any) {
log.Debugf("👋 joined channel: %s", channel.Topic())
})
join.Receive("error", func(response any) {
log.Warn("failed to joined channel:", channel.Topic(), response)
})
sw.channels[topic] = channel
return channel
}
func (sw *SeaWatcher) getChannel(topic string) *phx.Channel {
channel, ok := sw.channels[topic]
if !ok {
channel = sw.createChannel(topic)
}
return channel
}
func (sw *SeaWatcher) on(eventType osmodels.EventType, collectionSlug string, eventHandler func(response any)) func() {
topic := fmt.Sprintf("collection:%s", collectionSlug)
log.Debugf("Fetching channel %s", topic)
channel := sw.getChannel(topic)
log.Debugf("Subscribing to %s events on %s", eventType, topic)
channel.On(string(eventType), eventHandler)
channel.OnClose(func(payload any) {
sw.Prf("⚠️ Channel %s closed: %s", topic, payload)
})
log.Debugf("␚ 🔔 subscribed to %s for %s", string(eventType), collectionSlug)
return func() {
sw.Prf("Unsubscribing from %s events on %s", eventType, topic)
leave, err := channel.Leave()
if err != nil {
sw.Prf("channel.Leave err: %s", err)
}
leave.Receive("ok", func(_ any) {
delete(sw.channels, collectionSlug)
sw.Prf("Successfully left channel %s listening for %s", topic, eventType)
})
}
}
func (sw *SeaWatcher) WorkerMgmtChannel() {
log.Debugf("subscribing to mgmt channel %s", internal.TopicSeaWatcherMgmt)
mgmtChannel := sw.gb.SubscribeSeawatcherMgmt()
for {
mgmtEvent := <-mgmtChannel
sw.handleMgmtEvent(mgmtEvent)
}
}
// SubscribeToPubsubMgmt starts the seawatcher by subscribing to the mgmt channel and listening for new slugs to subscribe to.
func (sw *SeaWatcher) SubscribeToPubsubMgmt() {
sw.Prf("subscribing to mgmt channel %s", style.AlmostWhiteStyle.Render(internal.TopicSeaWatcherMgmt))
err := sw.rdb.Receive(context.Background(), sw.rdb.B().Subscribe().Channel(internal.TopicSeaWatcherMgmt).Build(), func(msg rueidis.PubSubMessage) {
log.Debugf("⚓️ received msg on channel %s: %s", msg.Channel, msg.Message)
var mgmtEvent *models.MgmtEvent
if err := json.Unmarshal([]byte(msg.Message), &mgmtEvent); err != nil {
log.Errorf("⚓️❌ error json.Unmarshal: %+v", err)
return
}
sw.handleMgmtEvent(mgmtEvent)
})
if err != nil {
log.Errorf("❌ error subscribing to redis channels %s: %s", internal.TopicSeaWatcherMgmt, err.Error())
return
}
}
func (sw *SeaWatcher) handleMgmtEvent(mgmtEvent *models.MgmtEvent) {
switch mgmtEvent.Action {
case models.SendSlugs:
// SendSlugs can be ignored on server side for now
return
case models.Subscribe, models.Unsubscribe:
sw.Prf("received %s for %s collections/slugs...", style.AlmostWhiteStyle.Render(mgmtEvent.Action.String()), style.AlmostWhiteStyle.Render(fmt.Sprint(len(mgmtEvent.Slugs))))
if len(mgmtEvent.Slugs) == 0 {
log.Error("⚓️❌ incoming collection slugs msg is empty")
return
}
if viper.GetString("api_keys.opensea") == "" {
log.Error("⚓️❌ OpenSea api key is not set, can't subscribe to listings")
return
}
var action func(slug string) bool
switch mgmtEvent.Action {
case models.Subscribe:
action = sw.SubscribeForSlug
case models.Unsubscribe:
action = sw.UnubscribeForSlug
}
newEventSubscriptions := 0
for _, slug := range mgmtEvent.Slugs {
if slug == "ens" {
sw.Pr("⚓️ ␚ skipping ens for now")
continue
}
if action(slug) {
newEventSubscriptions++
time.Sleep(337 * time.Millisecond)
}
}
sw.Prf(
"successfully subscribed to %s new collections/slugs | total subscribed collections: %s",
style.AlmostWhiteStyle.Render(fmt.Sprint(newEventSubscriptions)),
style.AlmostWhiteStyle.Render(fmt.Sprint(len(sw.ActiveSubscriptions()))),
)
default:
sw.Prf("⚓️ 👀 received unknown mgmt event: %s", mgmtEvent.Action.String())
return
}
}
func (sw *SeaWatcher) PublishSendSlugs() {
// build "SendSlugs" event
sendSlugsEvent := &models.MgmtEvent{
Action: models.SendSlugs,
}
// marshal event
jsonMgmtEvent, err := json.Marshal(sendSlugsEvent)
if err != nil {
log.Error("⚓️❌ marshal failed for SendSlugs action: %s | %v", err, sendSlugsEvent)
return
}
if sw.rdb.Do(context.Background(), sw.rdb.B().Publish().Channel(internal.TopicSeaWatcherMgmt).Message(string(jsonMgmtEvent)).Build()).Error() != nil {
log.Errorf("⚓️❌ error publishing %s to redis: %s", sendSlugsEvent.Action.String(), err.Error())
} else {
sw.Prf("📣 published %s event to %s", style.AlmostWhiteStyle.Render(sendSlugsEvent.Action.String()), style.AlmostWhiteStyle.Render(internal.TopicSeaWatcherMgmt))
}
}