/
watcher.go
572 lines (495 loc) · 17.8 KB
/
watcher.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright 2018-2020 Celer Network
//
// This is a wrapper on top of Go-Ethereum's client API (ethclient)
// for fetching log events via filtered query requests. It handles
// reliable restarts of the application by persisting into the KVStore
// the index of the last log event acknowledged by the application.
// This guarantees that the application does not miss log events that
// occur while the application is not running.
package watcher
import (
"container/list"
"context"
"errors"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/celer-network/goutils/log"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
)
const (
notBlockIndex = ^int64(0) // 0xFFFFFFFF not-a-block-index value
)
var (
ErrWatchServiceClosed = errors.New("Watch service closed")
ErrWatcherTimeout = errors.New("Watcher timeout")
)
// LogEventID tracks the position of a watch event in the event log.
type LogEventID struct {
BlockNumber uint64 // Number of the block containing the event
Index int64 // Index of the event within the block
}
// WatchService holds the active watchers and their connections
// to the Ethereum client and the KVStore persistence layer that
// provides resumability of the watcher after a restart.
type WatchService struct {
client WatchClient // Ethereum client interface
dal WatchDAL // Data access layer
polling uint64 // Polling interval (msec)
maxBlockDelta uint64 // Maximum number of blocks per query, 0 means unlimited
quit chan bool // Terminate the watch service
mu sync.RWMutex // Guards the fields that follow it.
blkNum uint64 // Current on-chain block number
watches map[string]*Watch // Map of registered watches
}
// Watch provides an iterator over a stream of event logs that match
// an Ethereum filtering query. It updates the KVStore to persist the
// position in the stream of the last event log that the application
// has acknowledged receiving.
// To handle chain reorganization (ephemeral forking), watch only
// requests from on-chain event logs that are older than a specified
// number of on-chain blocks.
type Watch struct {
name string // Unique name of registered watch
service *WatchService // Service owning this watch
ackWait bool // Is it waiting for an ACK from the app?
lastAck bool // One last ACK is allowed after close
ackID LogEventID // ID of log event pending an ACK
lastID *LogEventID // ID of log event for resuming (or nil)
blkDelay uint64 // Log event delay in number of blocks
fwdDelay uint64 // Block delay when fast forward
checkInterval uint64 // Check event every checkInterval * service.polling
fromBlock uint64 // Start a fetch from this block number
query ethereum.FilterQuery // On-chain event log query
mu sync.Mutex // Guards log queue and "closed" flag
logQueue *list.List // Queue of buffered log events
logQueueCond *sync.Cond // Condvar for waiting on the queue
closed bool // Is the watch closed?
}
// WatchClient is an interface for the subset of functions of the Go-Ethereum
// client API that the watch service uses.
type WatchClient interface {
HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error)
}
// WatchDAL is an interface for the watch-specific API of the KVStore
// data access layer.
type WatchDAL interface {
InsertMonitor(event string, blockNum uint64, blockIdx int64, restart bool) error
GetMonitorBlock(event string) (uint64, int64, bool, error)
UpdateMonitorBlock(event string, blockNum uint64, blockIdx int64) error
UpsertMonitorBlock(event string, blockNum uint64, blockIdx int64, restart bool) error
}
// Create a watch service.
// polling: interval (in seconds) to periodically query eth logs
// maxBlockDelta: maximum number of blocks for each eth log query, 0 means unlimited
func NewWatchService(client WatchClient, dal WatchDAL, polling, maxBlockDelta uint64) *WatchService {
// Note: the incoming polling interval is in seconds. Purely for
// unit testing purposes, the internal "polling" variable is in
// milliseconds to allow tests to set faster polling intervals.
return makeWatchService(client, dal, polling*1000, maxBlockDelta)
}
// Helper (for testing) to create a watch service with msec polling interval.
func makeWatchService(client WatchClient, dal WatchDAL, polling, maxBlockDelta uint64) *WatchService {
if client == nil || dal == nil || polling == 0 {
return nil
}
ws := &WatchService{
client: client,
dal: dal,
polling: polling,
maxBlockDelta: maxBlockDelta,
quit: make(chan bool),
watches: make(map[string]*Watch),
}
// Synchronously initialize the current head block number.
ws.updateBlockNumber()
// Start the common on-chain block number watcher.
go ws.watchBlkNum()
return ws
}
// Internal goroutine within the watch service that tracks the on-chain
// block number.
func (ws *WatchService) watchBlkNum() {
ticker := time.NewTicker(time.Duration(ws.polling) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ws.quit:
log.Debugln("watchBlkNum: quit")
return
case <-ticker.C:
ws.updateBlockNumber()
}
}
}
// Fetch the on-chain block number and update the local value if needed.
func (ws *WatchService) updateBlockNumber() {
head, err := ws.client.HeaderByNumber(context.Background(), nil)
if err != nil {
log.Traceln("cannot fetch on-chain block number:", err)
return
}
blkNum := head.Number.Uint64()
var topBlkNum uint64
ws.mu.Lock()
if blkNum > ws.blkNum {
ws.blkNum = blkNum
}
topBlkNum = ws.blkNum
ws.mu.Unlock()
log.Tracef("top block #: %d, on-chain #: %d", topBlkNum, blkNum)
}
// Return the most recent on-chain block number.
func (ws *WatchService) GetBlockNumber() uint64 {
ws.mu.RLock()
defer ws.mu.RUnlock()
return ws.blkNum
}
// Return the most recent on-chain block number in big.Int format.
func (ws *WatchService) GetCurrentBlockNumber() *big.Int {
return new(big.Int).SetUint64(ws.GetBlockNumber())
}
// Close the watch service.
func (ws *WatchService) Close() {
ws.mu.Lock()
defer ws.mu.Unlock()
if ws.watches != nil {
close(ws.quit)
for _, w := range ws.watches {
w.inner_close()
}
ws.watches = nil
}
}
// Register a named watch.
func (ws *WatchService) register(name string, watch *Watch) error {
ws.mu.Lock()
defer ws.mu.Unlock()
if ws.watches == nil {
return ErrWatchServiceClosed
}
if _, exist := ws.watches[name]; exist {
return fmt.Errorf("watch name '%s' already in use", name)
}
ws.watches[name] = watch
return nil
}
// Unregister a named watch
func (ws *WatchService) unregister(name string) {
ws.mu.Lock()
defer ws.mu.Unlock()
if ws.watches != nil {
delete(ws.watches, name)
}
}
// MakeFilterQuery constructs an Ethereum FilterQuery structure from these
// event and contract parameters: address, raw ABI string, event name, and
// the optional start block number.
func (ws *WatchService) MakeFilterQuery(
addr common.Address, rawABI string, eventName string, startBlock *big.Int) (ethereum.FilterQuery, error) {
var q ethereum.FilterQuery
parsedABI, err := abi.JSON(strings.NewReader((rawABI)))
if err != nil {
return q, err
}
ev, exist := parsedABI.Events[eventName]
if !exist {
return q, fmt.Errorf("unknown event name: %s", eventName)
}
q.FromBlock = startBlock
q.Addresses = []common.Address{addr}
q.Topics = [][]common.Hash{{ev.ID}}
return q, nil
}
// Create a watch for the given Ethereum log filtering query.
// The block delay is the number of blocks mined used as a time delay
// for fetching event logs, mitigating the effects of chain reorg.
// The block interval controls the polling frequency of fetch logs
// from on-chain, but measured in block numbers (as a delta).
// If "reset" is enabled, the watcher ignores the previously stored
// position in the subscription which resets the stream to its start.
func (ws *WatchService) NewWatch(
name string, query ethereum.FilterQuery, blkDelay, fwdDelay, checkInterval uint64, reset bool) (*Watch, error) {
if name == "" {
return nil, fmt.Errorf("watch name not specified")
}
if ws.maxBlockDelta > 0 && ws.maxBlockDelta <= fwdDelay {
return nil, fmt.Errorf("maxBlockDelta %d should larger than fwdDelay %d", ws.maxBlockDelta, fwdDelay)
}
w := &Watch{
name: name,
service: ws,
blkDelay: blkDelay,
fwdDelay: fwdDelay,
checkInterval: checkInterval,
query: query,
logQueue: list.New(),
}
w.logQueueCond = sync.NewCond(&w.mu) // condvar uses "mu"
// Register the named watch.
if err := ws.register(name, w); err != nil {
return nil, err
}
go w.watchLogEvents(reset)
return w, nil
}
// Internal goroutine that periodically fetches and enqueues the log events
// requested by the watch query.
func (w *Watch) watchLogEvents(reset bool) {
// Set the ID of the last log event acknowledged by the app (if any).
// It is used to resume the watch from where the application left off.
w.setWatchLastID(reset)
log.Debugf("watchLogEvents: start %s from %d", w.name, w.fromBlock)
// The polling interval is computed in relation to block polling.
polling := w.checkInterval * w.service.polling
ticker := time.NewTicker(time.Duration(polling) * time.Millisecond)
defer ticker.Stop()
for !w.isClosed() {
w.fetchLogEvents()
select {
case <-w.service.quit:
log.Debugln("watchLogEvents: quit:", w.name)
return
case <-ticker.C:
continue
}
}
log.Debugln("watchLogEvents: closed:", w.name)
}
// Set the ID of the last log event acknowledged by the app (if any).
// This is used to resume the watcher from where it left off when the
// application was terminated. If "reset" is enabled, ignore the value
// in the store and reset it to the one provided by the query.
//
// Note: The design of an ack'ed ID keeps open a small window between
// the first time a watch is started (from a user-specified block number)
// and the first log it gives to the app and gets its ACK. During that
// time window, a server crash/restart will not have any persisted ID
// and would appear to watch as brand-new, even though that watch was
// previously started. To handle this state (a watch previously started
// from a block number but never had the chance to give a log to the app)
// it is encoded into the persisted ID using the special "notBlockIndex"
// value for the block "Index": ID = {BlockNumber, notBlockIndex}.
// With that in place, a restarted watch will resume from that previous
// block number again, giving persistence to that special time window.
func (w *Watch) setWatchLastID(reset bool) {
w.lastID = nil
w.fromBlock = 0
blockNum, blockIdx, found, err := w.service.dal.GetMonitorBlock(w.name)
if err == nil && found && !reset {
if blockIdx != notBlockIndex {
// This is a real ACK ID from the app.
w.lastID = &LogEventID{
BlockNumber: blockNum,
Index: blockIdx,
}
}
// Ignore the query's "FromBlock" and start from this block.
w.fromBlock = blockNum
return
}
// No previously persisted resume pointer (or "reset", or some DB error).
// Remember this starting block number to resume from in case of a crash.
if w.query.FromBlock != nil {
w.fromBlock = w.query.FromBlock.Uint64()
}
if err != nil {
log.Warnln("resume pointer overwritten:", w.name, err)
err = w.service.dal.UpsertMonitorBlock(w.name,
w.fromBlock, notBlockIndex, false)
} else if found {
err = w.service.dal.UpdateMonitorBlock(w.name,
w.fromBlock, notBlockIndex)
} else {
err = w.service.dal.InsertMonitor(w.name,
w.fromBlock, notBlockIndex, false)
}
if err != nil {
log.Warnln("cannot persist resume pointer:", w.name, err)
}
}
// Fetch a batch of log events from on-chain and enqueue them.
// This function is called periodically in a ticker polling loop.
func (w *Watch) fetchLogEvents() {
// Do nothing if the on-chain block number has not moved forward
// beyond the desired block delay (to protect from on-chain reorg).
blkNum := w.service.GetBlockNumber()
if w.fromBlock+w.blkDelay > blkNum {
log.Tracef("skip log fetching: %s: want %d, delay %d, blk %d", w.name, w.fromBlock, w.blkDelay, blkNum)
return
}
// Fetch server-side filtered log events in the target range of
// block numbers. The block delay limit is used to avoid fetching
// recently mined blocks that may still be undone by a chain reorg.
// https://infura.io/docs/ethereum/json-rpc/eth-getLogs up to 10s
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
toBlock := blkNum - w.blkDelay
if w.service.maxBlockDelta > 0 && toBlock-w.fromBlock > w.service.maxBlockDelta {
toBlock = w.fromBlock + w.service.maxBlockDelta
}
w.query.FromBlock = new(big.Int).SetUint64(w.fromBlock)
w.query.ToBlock = new(big.Int).SetUint64(toBlock)
log.Tracef("fetch logs: %s: [%d-%d]", w.name, w.fromBlock, toBlock)
logs, err := w.service.client.FilterLogs(ctx, w.query)
if err != nil {
log.Warnf("cannot fetch logs: %s: [%d-%d]: %s", w.name, w.fromBlock, toBlock, err)
return
}
// Enqueue log events. In the first fetch after an application resume,
// lastID is used to skip log events previously handled within a block.
// This is needed because log fetching is at the block granularity, but
// processing is at the log event finer granularity. After that initial
// resuming block is refetched and partially de-duped, the lastID is no
// longer needed.
maxBlock := uint64(0)
count := 0
for i := range logs {
log := &logs[i]
if log.BlockNumber > maxBlock {
maxBlock = log.BlockNumber
}
if w.lastID == nil {
w.enqueue(log)
count++
} else if greaterThanLastID(log, w.lastID) {
w.enqueue(log)
count++
if log.BlockNumber > w.lastID.BlockNumber {
w.lastID = nil
}
}
}
// Update the next block number to start fetching.
if maxBlock >= w.fromBlock {
w.fromBlock = maxBlock + 1
log.Tracef("added %d logs to queue: %s: next from %d", count, w.name, w.fromBlock)
} else {
// we didn't find any event between fromBlock and toBlock, so we can fast forward.
fromBlock := toBlock
if fromBlock+w.fwdDelay+w.blkDelay >= blkNum {
// add additional block delay to mitigate consistency issues from query nodes
fromBlock = fromBlock - w.fwdDelay
}
if fromBlock > w.fromBlock {
w.fromBlock = fromBlock
}
// when there is no event in queue and the Watch is not waiting for Ack(), we
// assert that at this moment, no event is being processed or going to be processed.
if w.logQueue.Len() == 0 {
w.mu.Lock()
if !w.ackWait {
if err := w.service.dal.UpdateMonitorBlock(w.name, w.fromBlock, notBlockIndex); err != nil {
log.Warnln("cannot persist resume pointer:", w.name, err)
}
}
w.mu.Unlock()
}
log.Tracef("fast forward %s fromBlock to %d", w.name, w.fromBlock)
}
}
// Return true if the log event ID is strictly greater than the last ID.
func greaterThanLastID(log *types.Log, lastID *LogEventID) bool {
if log.BlockNumber > lastID.BlockNumber {
return true
} else if log.BlockNumber < lastID.BlockNumber {
return false
} else if int64(log.Index) > lastID.Index {
return true
}
return false
}
// Enqueue an event log.
func (w *Watch) enqueue(log *types.Log) {
w.mu.Lock()
defer w.mu.Unlock()
oldLen := w.logQueue.Len()
w.logQueue.PushBack(log)
if oldLen == 0 {
w.logQueueCond.Signal()
}
}
// Dequeue and return the first event log in the queue, or block waiting
// for one to arrive or the watcher to be closed.
func (w *Watch) dequeue() (*types.Log, error) {
w.mu.Lock()
defer w.mu.Unlock()
for !w.closed && w.logQueue.Len() == 0 && !w.ackWait {
w.logQueueCond.Wait()
}
if w.closed {
return nil, fmt.Errorf("watch name '%s' closed", w.name)
}
if w.ackWait {
return nil, fmt.Errorf("last event log received not yet ACKed")
}
elem := w.logQueue.Front()
w.logQueue.Remove(elem)
nextLog := elem.Value.(*types.Log)
w.ackID.BlockNumber = nextLog.BlockNumber
w.ackID.Index = int64(nextLog.Index)
w.ackWait = true
return nextLog, nil
}
// Fetch the next log event. The function will block until either an
// event log is available, or the watcher is closed.
func (w *Watch) Next() (types.Log, error) {
var empty types.Log
if w.isClosed() {
return empty, fmt.Errorf("watch name '%s' already closed", w.name)
}
if w.ackWait {
return empty, fmt.Errorf("last event log received not yet ACKed")
}
nextLog, err := w.dequeue()
if err != nil {
return empty, err
}
return *nextLog, nil
}
// The app ACKs the complete processing of the last received event log.
// Be lenient in one case: after the watch is closed, allow at most one
// more ACK to be done. This allows event processing that was completed
// by the application when an asynchronous Close() took place (between
// the Next() and the Ack() calls) to be persisted into storage instead
// of having it be re-done after the application is restarted.
func (w *Watch) Ack() error {
if w.isClosed() {
if w.lastAck {
return fmt.Errorf("watch name '%s' already closed", w.name)
}
w.lastAck = true
}
if !w.ackWait {
return fmt.Errorf("last event log received already ACKed")
}
if err := w.service.dal.UpdateMonitorBlock(w.name, w.ackID.BlockNumber, w.ackID.Index); err != nil {
return err
}
w.ackWait = false
return nil
}
func (w *Watch) isClosed() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.closed
}
func (w *Watch) inner_close() {
w.mu.Lock()
defer w.mu.Unlock()
if !w.closed {
w.closed = true
w.logQueueCond.Broadcast()
}
}
// Close a watch subscription.
func (w *Watch) Close() {
w.service.unregister(w.name) // remove from watch service
w.inner_close()
}