-
Notifications
You must be signed in to change notification settings - Fork 5
/
seawatcher.go
523 lines (394 loc) Β· 14.7 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
package seawa
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"sync"
"time"
"github.com/benleb/gloomberg/internal"
"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"
)
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()
// redis client
rdb rueidis.Client
gb *gloomberg.Gloomberg
mu *sync.Mutex
}
var (
// topX = map[string]*models.Bid{}.
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 {
var socket *phx.Socket
if apiToken != "" {
endpointURL := fmt.Sprint(osmodels.StreamAPIEndpoint, "?token=", apiToken)
endpoint, err := url.Parse(endpointURL)
if err != nil {
log.Info(err)
return nil
}
// create phoenix socket
socket = phx.NewSocket(endpoint)
socket.Logger = phx.NewSimpleLogger(phx.LoggerLevel(phx.LogError))
socket.ReconnectAfterFunc = func(attempt int) time.Duration {
log.Warnf("βοΈβ opensea stream socket retry after %v..", time.Duration(attempt)*2*time.Second)
return time.Duration(attempt) * 2 * time.Second
}
// error function
onError := func(err error) { log.Info(err) }
socket.OnError(onError)
socket.OnClose(func() {
log.Info("βοΈβ opensea stream socket closed, reconnecting...")
err := socket.Reconnect()
if err != nil {
onError(errors.New("opensea stream socket reconnecting failed: " + err.Error()))
}
})
}
client := &SeaWatcher{
receivedEvents: make(chan map[string]interface{}, 1024),
subscriptions: make(map[osmodels.EventType]map[string]func(), 0),
phoenixSocket: socket,
channels: make(map[string]*phx.Channel),
gb: gb,
// rdb: rdb,
rdb: gb.Rdb,
mu: &sync.Mutex{},
}
// create subscriptions map/registry
for _, event := range AvailableEventTypes {
client.subscriptions[event] = make(map[string]func(), 0)
}
if client.phoenixSocket != nil {
if err := client.connect(); err != nil {
socketError := errors.New("opensea stream socket connection failed: " + err.Error())
log.Error("βοΈβ " + socketError.Error())
return nil
}
}
return client
}
func (sw *SeaWatcher) EventChannel() chan map[string]interface{} {
return sw.receivedEvents
}
func (sw *SeaWatcher) ActiveSubscriptions() map[osmodels.EventType]map[string]func() {
return sw.subscriptions
}
func (sw *SeaWatcher) connect() error {
return sw.phoenixSocket.Connect()
}
// 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.Info("βοΈβ 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 {
log.Info("βοΈβ decoding incoming opensea stream api ItemReceivedBidEvent failed:", 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 {
log.Info("βοΈβ decoding incoming opensea stream api collection offer event failed:", err)
return osmodels.CollectionOfferEvent{}, err
}
return collectionOfferEvent, err
}
// func printItemReceivedOfferEvent(itemOfferEvent osmodels.ItemReceivedOfferEvent) {
// priceWeiRaw, _, err := big.ParseFloat(itemOfferEvent.Payload.BasePrice, 10, 64, big.ToNearestEven)
// if err != nil {
// log.Infof("βοΈβ werror parsing price: %+v | %s", itemOfferEvent.Payload.BasePrice, err.Error())
// return
// }
// priceWei, _ := priceWeiRaw.Int(nil)
// // nftID is a identification string in the format <chain>/<contract>/<tokenID>
// nftID := strings.Split(itemOfferEvent.Payload.Item.NftID, "/")
// if len(nftID) != 3 {
// log.Infof("βοΈ π€·ββοΈ error parsing nftID: %s", itemOfferEvent.Payload.Item.NftID)
// return
// }
// eventType := osmodels.TxType[itemOfferEvent.StreamEvent]
// collectionPrimaryStyle := lipgloss.NewStyle().Foreground(style.GenerateColorWithSeed(common.HexToAddress(nftID[1]).Hash().Big().Int64())).Bold(true)
// collectionSecondaryStyle := lipgloss.NewStyle().Foreground(style.GenerateColorWithSeed(common.HexToAddress(nftID[1]).Big().Int64() ^ 2)).Bold(true)
// // get tokenID
// tID, _, _ := big.ParseFloat(nftID[2], 10, 64, big.ToNearestEven)
// tokenID, _ := tID.Int(nil)
// fmtTokenID := style.ShortenedTokenIDStyled(tokenID, collectionPrimaryStyle, collectionSecondaryStyle)
// // for erc1155 tokens itemOfferEvent.Payload.Item.Metadata.Name is the item name
// collectionName := strings.Split(itemOfferEvent.Payload.Item.Metadata.Name, " #")[0]
// fmtToken := style.BoldStyle.Render(fmt.Sprintf("%s %s", collectionPrimaryStyle.Render(collectionName), fmtTokenID))
// fmt.Println(itemOfferEvent.StreamEvent)
// log.Infof("βοΈ %s | %sΞ %s ", eventType.Icon(), style.BoldStyle.Render(fmt.Sprintf("%5.3f", price.NewPrice(priceWei).Ether())), style.TerminalLink(itemOfferEvent.Payload.Item.Permalink, fmtToken))
// }
func (sw *SeaWatcher) SubscribeForSlug(eventType osmodels.EventType, slug string) bool {
sw.mu.Lock()
alreadySubscribed := sw.subscriptions[eventType][slug]
if alreadySubscribed != nil {
sw.mu.Unlock()
log.Debugf("βοΈ βοΈ already subscribed to %s for %s", eventType, slug)
return false
}
sw.subscriptions[eventType][slug] = sw.on(eventType, slug, sw.eventHandler)
sw.mu.Unlock()
return true
}
func (sw *SeaWatcher) UnubscribeForSlug(eventType osmodels.EventType, slug string) bool {
sw.mu.Lock()
unsubscribe := sw.subscriptions[eventType][slug]
sw.mu.Unlock()
if unsubscribe != nil {
// unsubscribe
unsubscribe()
// remove slug
sw.mu.Lock()
sw.subscriptions[eventType][slug] = nil
sw.mu.Unlock()
return true
}
log.Debugf("βοΈ not subscribed to %s for %s (anymore)", eventType, slug)
return false
}
func (sw *SeaWatcher) createChannel(topic string) *phx.Channel {
channel := sw.phoenixSocket.Channel(topic, nil)
join, err := channel.Join()
if err != nil {
log.Info(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)
log.Debugf("β π subscribed to %s for %s", string(eventType), collectionSlug)
return func() {
log.Infof("Unsubscribing from %s events on %s", eventType, topic)
leave, err := channel.Leave()
if err != nil {
log.Info("channel.Leave err:", err)
}
leave.Receive("ok", func(_ any) {
delete(sw.channels, collectionSlug)
log.Infof("Successfully left channel %s listening for %s", topic, eventType)
})
}
}
// Run starts the seawatcher by subscribing to the mgmt channel and listening for new slugs to subscribe to.
func (sw *SeaWatcher) Run() {
// subscribe to mgmt channel
log.Infof("βοΈ β subscribing to mgmt channel %s", 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
}
switch mgmtEvent.Action {
case models.SendSlugs:
// SendSlugs can be ignored on server side for now
return
case models.Subscribe, models.Unsubscribe:
log.Infof("βοΈ β received %s for %s collections/slugs on %s, subscribing...", style.BoldStyle.Render(mgmtEvent.Action.String()), style.BoldStyle.Render(fmt.Sprint(len(mgmtEvent.Slugs))), internal.TopicSeaWatcherMgmt)
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(event osmodels.EventType, slug string) bool
switch mgmtEvent.Action {
case models.Subscribe:
action = sw.SubscribeForSlug
case models.Unsubscribe:
action = sw.UnubscribeForSlug
}
// transform to string
var events []string
for _, event := range AvailableEventTypes {
events = append(events, string(event))
}
// subscribe to which events?
if len(mgmtEvent.Events) == 0 {
// subscribe to all available events if none are specified
log.Infof("βοΈ β no events specified, subscribing to all available events (%+v)", strings.Join(events, ", "))
mgmtEvent.Events = AvailableEventTypes
}
newSubscriptions := make(map[string][]osmodels.EventType, 0)
newEventSubscriptions := 0
for _, slug := range mgmtEvent.Slugs {
if slug == "ens" {
log.Info("βοΈ β skipping ens for now")
continue
}
for _, event := range mgmtEvent.Events {
if action(event, slug) {
newEventSubscriptions++
if _, ok := newSubscriptions[slug]; !ok {
newSubscriptions[slug] = make([]osmodels.EventType, 0)
}
newSubscriptions[slug] = append(newSubscriptions[slug], event)
time.Sleep(257 * time.Millisecond)
}
}
}
log.Infof(
"βοΈ β successfully subscribed to %s new collections/slugs (%d events in total) | total subscriptions: %s",
style.BoldStyle.Render(fmt.Sprint(len(newSubscriptions))),
newEventSubscriptions,
style.BoldStyle.Render(fmt.Sprint(len(sw.ActiveSubscriptions()[osmodels.ItemListed]))),
)
default:
log.Infof("βοΈ π received unknown mgmt event: %s", mgmtEvent.Action.String())
return
}
})
if err != nil {
log.Errorf("β error subscribing to redis channels %s: %s", internal.TopicSeaWatcherMgmt, err.Error())
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 {
log.Infof("βοΈ π£ published %s event to %s", style.Bold(sendSlugsEvent.Action.String()), style.Bold(internal.TopicSeaWatcherMgmt))
}
}