/
writer.go
221 lines (188 loc) · 6.42 KB
/
writer.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
package warpy_sync
import (
"context"
"errors"
"strings"
"github.com/cenkalti/backoff"
"github.com/go-resty/resty/v2"
"github.com/warp-contracts/syncer/src/utils/config"
"github.com/warp-contracts/syncer/src/utils/monitoring"
"github.com/warp-contracts/syncer/src/utils/sequencer"
"github.com/warp-contracts/syncer/src/utils/task"
"github.com/warp-contracts/syncer/src/utils/warpy"
)
type Writer struct {
*task.Task
monitor monitoring.Monitor
input <-chan *[]InteractionPayload
sequencerClient *sequencer.Client
httpClient *resty.Client
}
func NewWriter(config *config.Config) (self *Writer) {
self = new(Writer)
self.httpClient = resty.New().
SetTimeout(config.WarpySyncer.WriterHttpRequestTimeout)
self.Task = task.NewTask(config, "writer").
WithSubtaskFunc(self.run).
WithWorkerPool(config.Evolver.DownloaderNumWorkers, config.Evolver.DownloaderWorkerQueueSize)
return
}
func (self *Writer) WithMonitor(monitor monitoring.Monitor) *Writer {
self.monitor = monitor
return self
}
func (self *Writer) WithSequencerClient(sequencerClient *sequencer.Client) *Writer {
self.sequencerClient = sequencerClient
return self
}
func (self *Writer) WithInputChannel(v chan *[]InteractionPayload) *Writer {
self.input = v
return self
}
func (self *Writer) run() (err error) {
for interactionPayload := range self.input {
self.Log.Debug("Writer initialized")
err = self.writeInteraction(interactionPayload)
}
return
}
func (self *Writer) writeInteraction(payloads *[]InteractionPayload) (err error) {
chunkSize := self.Config.WarpySyncer.WriterInteractionChunkSize
if len(*payloads) == 0 {
self.Log.Debug("Interaction Payload slice is empty")
return
}
payloadChunk := make([]InteractionPayload, 0, chunkSize)
for _, payload := range *payloads {
if payload.Points == 0 {
self.Log.WithField("from_address", payload.FromAddress).Debug("Skipping from address, points 0")
continue
}
payloadChunk = append(payloadChunk, payload)
if len(payloadChunk) >= chunkSize {
err = self.sendInteractionChunk(&payloadChunk)
if err != nil {
self.Log.
WithField("chunk_size", len(payloadChunk)).
WithError(err).Error("Failed to send interaction chunk")
return err
}
payloadChunk = make([]InteractionPayload, 0, chunkSize)
}
}
if len(payloadChunk) > 0 {
err = self.sendInteractionChunk(&payloadChunk)
if err != nil {
self.Log.WithError(err).Error("Failed to send interaction chunk")
return err
}
}
return
}
func (self *Writer) sendInteractionChunk(interactions *[]InteractionPayload) (err error) {
self.Log.WithField("chunk_size", len(*interactions)).
Info("Attempting to send a chunk of interaction payload")
addressToRoles, err := self.walletAddressToDiscordRoles(interactions)
if err != nil {
self.Log.WithError(err).Error("Failed to get roles")
return err
}
if addressToRoles == nil || len(*addressToRoles) == 0 {
self.Log.WithField("chunk_size", len(*interactions)).
Debug("Skipping writing interactions, none of the addresses registered in warpy")
return
}
members := make([]Member, 0, len(*interactions))
for _, p := range *interactions {
roles, ok := (*addressToRoles)[p.FromAddress]
if ok {
members = append(members, Member{Id: p.FromAddress, Roles: roles, Points: p.Points})
} else {
self.Log.WithField("from_address", p.FromAddress).Debug("Skipping address, not registered in warpy")
}
}
if len(members) == 1 {
self.Log.WithField("from_address", (members)[0].Id).
WithField("points", (members)[0].Points).
Debug("Writing interaction to Warpy...")
} else {
self.Log.WithField("chunk_size", len(members)).
WithField("points_default", 0).
Debug("Writing interaction to Warpy...")
}
input := Input{
Function: "addPointsForAddress",
Points: 0,
AdminId: self.Config.WarpySyncer.SyncerInteractionAdminId,
Members: members,
}
interactionId, err := warpy.WriteInteractionToWarpy(
self.Ctx, self.Config.WarpySyncer, input, self.Log, self.sequencerClient)
if err != nil {
return err
}
self.Log.WithField("interactionId", interactionId).Info("Interaction sent to Warpy")
self.monitor.GetReport().WarpySyncer.State.WriterInteractionsToWarpy.Inc()
return
}
// Returns a map of wallet address to a list of discord roles.
// If wallet not registered in warpy the map will not contain the key.
// If wallet found but no roles the map will point to an empty collection.
func (self *Writer) walletAddressToDiscordRoles(payloads *[]InteractionPayload) (walletToRoles *map[string][]string, err error) {
addresses := make([]string, 0, len(*payloads))
for _, p := range *payloads {
addresses = append(addresses, p.FromAddress)
}
err = task.NewRetry().
WithContext(self.Ctx).
// Retries infinitely until success
WithMaxElapsedTime(0).
WithMaxInterval(self.Config.WarpySyncer.WriterBackoffInterval).
WithAcceptableDuration(self.Config.WarpySyncer.WriterBackoffInterval * 2).
WithOnError(func(err error, isDurationAcceptable bool) error {
if errors.Is(err, context.Canceled) && self.IsStopping.Load() {
return backoff.Permanent(err)
}
self.monitor.GetReport().WarpySyncer.Errors.WriterFailures.Inc()
self.Log.WithError(err).
Warn("Could not process assets sum, retrying...")
return err
}).
Run(func() error {
result, err := warpy.GetWalletToDiscordIdMap(self.httpClient, self.Config.WarpySyncer.SyncerDreUrl, &addresses, self.Log)
if err != nil {
self.Log.WithError(err).Warn("Could not retrieve sender Discord ids")
return err
}
if result.WalletToDiscordId == nil || len(result.WalletToDiscordId) == 0 {
self.Log.
WithField("addresses", strings.Join(addresses, ",")).
Debug("No discord ids found for specified address, exiting")
return nil
}
ids := make([]string, 0, len(result.WalletToDiscordId))
for _, w := range addresses {
id := result.WalletToDiscordId[w]
if len(id) > 15 {
ids = append(ids, id)
} else {
self.Log.WithField("from_address", w).
Info("Address not registered in Warpy, skipping")
}
}
walletToRoles = &map[string][]string{}
rolesPayload, err := warpy.GetSendersRoles(self.httpClient, self.Config.WarpySyncer.SyncerWarpyApiUrl, &ids, self.Log)
if err != nil {
self.Log.
WithError(err).Warn("Could not retrieve senders roles")
return err
}
for _, w := range addresses {
if id, ok := result.WalletToDiscordId[w]; ok {
(*walletToRoles)[w] = (*rolesPayload).IdToRoles[id]
}
}
return nil
})
return
}