-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathworker.go
285 lines (236 loc) · 7.65 KB
/
worker.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
package async_sequencer
import (
"context"
"database/sql"
"sync"
"time"
"github.com/mr-tron/base58"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/pkg/errors"
"github.com/code-payments/code-server/pkg/database/query"
"github.com/code-payments/code-server/pkg/metrics"
"github.com/code-payments/code-server/pkg/pointer"
"github.com/code-payments/code-server/pkg/retry"
"github.com/code-payments/code-server/pkg/code/data/fulfillment"
"github.com/code-payments/code-server/pkg/code/data/nonce"
"github.com/code-payments/code-server/pkg/code/data/transaction"
transaction_util "github.com/code-payments/code-server/pkg/code/transaction"
)
func (p *service) worker(serviceCtx context.Context, state fulfillment.State, interval time.Duration) error {
var cursor query.Cursor
delay := interval
err := retry.Loop(
func() (err error) {
time.Sleep(delay)
nr := serviceCtx.Value(metrics.NewRelicContextKey).(*newrelic.Application)
m := nr.StartTransaction("async__sequencer_service__handle_" + state.String())
defer m.End()
tracedCtx := newrelic.NewContext(serviceCtx, m)
// todo: proper config to tune states individually
var limit uint64
switch state {
case fulfillment.StatePending:
limit = 100 // todo: we'll likely want to up this one, but also rate limit our send/getSignature RPC calls
default:
limit = 100
}
// Get a batch of records in similar state (e.g. newly created, released, reserved, etc...)
items, err := p.data.GetAllFulfillmentsByState(
tracedCtx,
state,
false, // Don't poll for fulfillments that have active scheduling disabled
query.WithLimit(limit),
query.WithCursor(cursor),
)
if err != nil {
cursor = query.EmptyCursor
return err
}
// Process the batch of fulfillments in parallel
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(record *fulfillment.Record) {
defer wg.Done()
err := p.handle(tracedCtx, record)
if err != nil {
m.NoticeError(err)
}
}(item)
}
wg.Wait()
// Update cursor to point to the next set of fulfillments
if len(items) > 0 {
cursor = query.ToCursor(items[len(items)-1].Id)
} else {
cursor = query.EmptyCursor
}
return nil
},
retry.NonRetriableErrors(context.Canceled),
)
return err
}
func (p *service) handle(ctx context.Context, record *fulfillment.Record) error {
err := p.checkPreconditions(ctx, record)
if err != nil {
// Preconditions failed or we could not get the lock, go do something else
return err
}
switch record.State {
case fulfillment.StateUnknown:
return p.handleUnknown(ctx, record)
case fulfillment.StatePending:
return p.handlePending(ctx, record)
case fulfillment.StateConfirmed:
return p.handleConfirmed(ctx, record)
case fulfillment.StateFailed:
return p.handleFailed(ctx, record)
case fulfillment.StateRevoked:
return p.handleRevoked(ctx, record)
default:
return nil
}
}
func (p *service) checkPreconditions(ctx context.Context, record *fulfillment.Record) error {
if false {
// todo: get a distributed lock on the intent from Redis
return ErrCouldNotGetIntentLock
}
return nil
}
func (p *service) handleUnknown(ctx context.Context, record *fulfillment.Record) error {
handler, ok := p.fulfillmentHandlersByType[record.FulfillmentType]
if !ok {
return errors.Errorf("no fulfillment handler for %d type", record.FulfillmentType)
}
// Sanity check the fulfillment record. There should be data for a signed
// transaction when it's not made on demand.
if !handler.SupportsOnDemandTransactions() && (record.Signature == nil || len(*record.Signature) == 0) {
return errors.New("fulfillment doesn't support on demand transaction creation")
}
isRevoked, nonceUsed, err := handler.IsRevoked(ctx, record)
if err != nil {
return err
} else if isRevoked {
return p.markFulfillmentRevoked(ctx, record, nonceUsed)
}
// Check if this fulfillment is scheduled for submission to the blockchain
isScheduled, err := p.scheduler.CanSubmitToBlockchain(ctx, record)
if err != nil {
return err
} else if !isScheduled {
return nil
}
return p.markFulfillmentPending(ctx, record)
}
func (p *service) handlePending(ctx context.Context, record *fulfillment.Record) error {
fulfillmentHandler, ok := p.fulfillmentHandlersByType[record.FulfillmentType]
if !ok {
return errors.Errorf("no fulfillment handler for %d type", record.FulfillmentType)
}
actionHandler, ok := p.actionHandlersByType[record.ActionType]
if !ok {
return errors.Errorf("no action handler for %d type", record.ActionType)
}
intentHandler, ok := p.intentHandlersByType[record.IntentType]
if !ok {
return errors.Errorf("no intent handler for %d type", record.IntentType)
}
// Check on the status of the transaction
tx, err := p.getTransaction(ctx, record)
if err != nil && err != transaction.ErrNotFound {
return err
}
if tx != nil {
if tx.HasErrors || tx.ConfirmationState == transaction.ConfirmationFailed {
recovered, err := fulfillmentHandler.OnFailure(ctx, record, tx)
if err != nil {
return err
}
if recovered {
return nil
}
err = actionHandler.OnFulfillmentStateChange(ctx, record, fulfillment.StateFailed)
if err != nil {
return err
}
err = intentHandler.OnActionUpdated(ctx, record.Intent)
if err != nil {
return err
}
// By design is the last thing so we can retry all logic
return p.markFulfillmentFailed(ctx, record)
}
if tx.ConfirmationState == transaction.ConfirmationFinalized {
err := actionHandler.OnFulfillmentStateChange(ctx, record, fulfillment.StateConfirmed)
if err != nil {
return err
}
err = intentHandler.OnActionUpdated(ctx, record.Intent)
if err != nil {
return err
}
err = fulfillmentHandler.OnSuccess(ctx, record, tx)
if err != nil {
return err
}
// By design is the last thing so we can retry all logic
return p.markFulfillmentConfirmed(ctx, record)
}
}
// We're still pending
// Create the transaction on demand if it's supported
if record.Signature == nil {
if !fulfillmentHandler.SupportsOnDemandTransactions() {
return errors.New("unexpected scheduled fulfillment without transaction data")
}
selectedNonce, err := transaction_util.SelectAvailableNonce(ctx, p.data, nonce.PurposeOnDemandTransaction)
if err != nil {
return err
}
defer func() {
selectedNonce.ReleaseIfNotReserved()
selectedNonce.Unlock()
}()
txn, err := fulfillmentHandler.MakeOnDemandTransaction(ctx, record, selectedNonce)
if err != nil {
return err
}
record.Signature = pointer.String(base58.Encode(txn.Signature()))
record.Nonce = pointer.String(selectedNonce.Account.PublicKey().ToBase58())
record.Blockhash = pointer.String(base58.Encode(selectedNonce.Blockhash[:]))
record.Data = txn.Marshal()
err = p.data.ExecuteInTx(ctx, sql.LevelDefault, func(ctx context.Context) error {
err := selectedNonce.MarkReservedWithSignature(ctx, *record.Signature)
if err != nil {
return err
}
err = p.data.UpdateFulfillment(ctx, record)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
}
// Re-broadcast the transaction (could be the first time)
if !p.conf.disableTransactionSubmission.Get(ctx) {
return p.sendToBlockchain(ctx, record)
}
return nil
}
func (p *service) handleConfirmed(ctx context.Context, record *fulfillment.Record) error {
// Nothing to do here. We're done...
return nil
}
func (p *service) handleFailed(ctx context.Context, record *fulfillment.Record) error {
// Nothing to do here. We're done...
return nil
}
func (p *service) handleRevoked(ctx context.Context, record *fulfillment.Record) error {
// Nothing to do here. We're done...
return nil
}