forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
indexsubscriber.go
420 lines (355 loc) · 10.7 KB
/
indexsubscriber.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
// Copyright (c) 2021-2023 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package indexers
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/decred/dcrd/database/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/internal/blockchain/progresslog"
)
// IndexNtfnType represents an index notification type.
type IndexNtfnType int
const (
// ConnectNtfn indicates the index notification signals a block
// connected to the main chain.
ConnectNtfn IndexNtfnType = iota
// DisconnectNtfn indicates the index notification signals a block
// disconnected from the main chain.
DisconnectNtfn
)
var (
// bufferSize represents the index notification buffer size.
bufferSize = 128
// noPrereqs indicates no index prerequisites.
noPrereqs = "none"
// syncUpdateInterval is the time between periodically checking indexes
// and notifying their synchronization subscribers if synced.
syncUpdateInterval = time.Millisecond * 500
)
// IndexNtfn represents an index notification detailing a block connection
// or disconnection.
type IndexNtfn struct {
NtfnType IndexNtfnType
Block *dcrutil.Block
Parent *dcrutil.Block
IsTreasuryEnabled bool
Done chan bool
}
// IndexSubscription represents a subscription for index updates.
type IndexSubscription struct {
id string
idx Indexer
subscriber *IndexSubscriber
mtx sync.Mutex
// prerequisite defines the notification processing hierarchy for this
// subscription. It is expected that the subscriber associated with the
// prerequisite provided processes notifications before they are
// delivered by this subscription to its subscriber. An empty string
// indicates the subscription has no prerequisite.
prerequisite string
// dependent defines the index subscription that requires the subscriber
// associated with this subscription to have processed incoming
// notifications before it does. A nil dependency indicates the subscription
// has no dependencies.
dependent *IndexSubscription
}
// newIndexSubscription initializes a new index subscription.
func newIndexSubscription(subber *IndexSubscriber, indexer Indexer, prereq string) *IndexSubscription {
return &IndexSubscription{
id: indexer.Name(),
idx: indexer,
prerequisite: prereq,
subscriber: subber,
}
}
// stop prevents any future index updates from being delivered and
// unsubscribes the associated subscription.
//
// This must be called with the index subscriber mutex held for writes.
func (s *IndexSubscription) stop() error {
// If the subscription has a prerequisite, find it and remove the
// subscription as a dependency.
if s.prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriber.subscriptions[s.prerequisite]
s.mtx.Unlock()
if !ok {
return fmt.Errorf("no subscription found with id %s", s.prerequisite)
}
prereq.mtx.Lock()
prereq.dependent = nil
prereq.mtx.Unlock()
return nil
}
// If the subscription has a dependent, stop it as well.
if s.dependent != nil {
err := s.dependent.stop()
if err != nil {
return err
}
}
// If the subscription is independent, remove it from the
// index subscriber's subscriptions.
delete(s.subscriber.subscriptions, s.id)
return nil
}
// IndexSubscriber subscribes clients for index updates.
type IndexSubscriber struct {
subscribers atomic.Uint32
c chan IndexNtfn
subscriptions map[string]*IndexSubscription
mtx sync.Mutex
ctx context.Context
cancel context.CancelFunc
quit chan struct{}
}
// NewIndexSubscriber creates a new index subscriber. It also starts the
// handler for incoming index update subscriptions.
func NewIndexSubscriber(sCtx context.Context) *IndexSubscriber {
ctx, cancel := context.WithCancel(sCtx)
s := &IndexSubscriber{
c: make(chan IndexNtfn, bufferSize),
subscriptions: make(map[string]*IndexSubscription),
ctx: ctx,
cancel: cancel,
quit: make(chan struct{}),
}
return s
}
// Subscribe subscribes an index for updates. The returned index subscription
// has functions to retrieve a channel that produces a stream of index updates
// and to stop the stream when the caller no longer wishes to receive updates.
func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexSubscription, error) {
sub := newIndexSubscription(s, index, prerequisite)
// If the subscription has a prequisite, find it and set the subscription
// as a dependency.
if prerequisite != noPrereqs {
s.mtx.Lock()
prereq, ok := s.subscriptions[prerequisite]
s.mtx.Unlock()
if !ok {
return nil, fmt.Errorf("no subscription found with id %s", prerequisite)
}
prereq.mtx.Lock()
defer prereq.mtx.Unlock()
if prereq.dependent != nil {
return nil, fmt.Errorf("%s already has a dependent set: %s",
prereq.id, prereq.dependent.id)
}
prereq.dependent = sub
s.subscribers.Add(1)
return sub, nil
}
// If the subscription does not have a prerequisite, add it to the index
// subscriber's subscriptions.
s.mtx.Lock()
s.subscriptions[sub.id] = sub
s.mtx.Unlock()
s.subscribers.Add(1)
return sub, nil
}
// Notify relays an index notification to subscribed indexes for processing.
func (s *IndexSubscriber) Notify(ntfn *IndexNtfn) {
subscribers := s.subscribers.Load()
// Only relay notifications when there are subscribed indexes
// to be notified.
if subscribers > 0 {
select {
case <-s.quit:
case s.c <- *ntfn:
}
}
}
// findLowestIndexTipHeight determines the lowest index tip height among
// subscribed indexes and their dependencies.
func (s *IndexSubscriber) findLowestIndexTipHeight(queryer ChainQueryer) (int64, int64, error) {
// Find the lowest tip height to catch up among subscribed indexes.
bestHeight, _ := queryer.Best()
lowestHeight := bestHeight
for _, sub := range s.subscriptions {
tipHeight, tipHash, err := sub.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
// Ensure the index tip is on the main chain.
if !queryer.MainChainHasBlock(tipHash) {
return 0, bestHeight, fmt.Errorf("%s: index tip (%s) is not on the "+
"main chain", sub.idx.Name(), tipHash)
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
// Update the lowest tip height if a dependent has a lower tip height.
dependent := sub.dependent
for dependent != nil {
tipHeight, _, err := sub.dependent.idx.Tip()
if err != nil {
return 0, bestHeight, err
}
if tipHeight < lowestHeight {
lowestHeight = tipHeight
}
dependent = dependent.dependent
}
}
return lowestHeight, bestHeight, nil
}
// CatchUp syncs all subscribed indexes to the main chain by connecting blocks
// from after the lowest index tip to the current main chain tip.
//
// This should be called after all indexes have subscribed for updates.
func (s *IndexSubscriber) CatchUp(ctx context.Context, _ database.DB, queryer ChainQueryer) error {
lowestHeight, bestHeight, err := s.findLowestIndexTipHeight(queryer)
if err != nil {
return err
}
// Nothing to do if all indexes are synced.
if bestHeight == lowestHeight {
return nil
}
// Create a progress logger for the indexing process below.
progressLogger := progresslog.NewBlockProgressLogger("Indexed", log)
// tip and need to be caught up, so log the details and loop through
// each block that needs to be indexed.
log.Infof("Catching up from height %d to %d", lowestHeight,
bestHeight)
var cachedParent *dcrutil.Block
for height := lowestHeight + 1; height <= bestHeight; height++ {
if interruptRequested(ctx) {
return indexerError(ErrInterruptRequested, interruptMsg)
}
hash, err := queryer.BlockHashByHeight(height)
if err != nil {
return err
}
// Ensure the next tip hash is on the main chain.
if !queryer.MainChainHasBlock(hash) {
msg := fmt.Sprintf("the next block being synced to (%s) "+
"at height %d is not on the main chain", hash, height)
return indexerError(ErrBlockNotOnMainChain, msg)
}
var parent *dcrutil.Block
if cachedParent == nil && height > 0 {
parentHash, err := queryer.BlockHashByHeight(height - 1)
if err != nil {
return err
}
parent, err = queryer.BlockByHash(parentHash)
if err != nil {
return err
}
} else {
parent = cachedParent
}
child, err := queryer.BlockByHash(hash)
if err != nil {
return err
}
// Construct and send the index notification.
isTreasuryEnabled, err := queryer.IsTreasuryAgendaActive(parent.Hash())
if err != nil {
return err
}
ntfn := &IndexNtfn{
NtfnType: ConnectNtfn,
Block: child,
Parent: parent,
IsTreasuryEnabled: isTreasuryEnabled,
}
// Relay the index update to subscribed indexes.
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, ntfn)
if err != nil {
s.cancel()
return err
}
}
cachedParent = child
progressLogger.LogBlockHeight(child.MsgBlock())
}
log.Infof("Caught up to height %d", bestHeight)
return nil
}
// handleSyncSubscribers updates index sync subscribers when a subscribed
// indexer is fully synced.
//
// This should be run as a goroutine.
func (s *IndexSubscriber) handleSyncSubscribers(ctx context.Context) {
ticker := time.NewTicker(syncUpdateInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.mtx.Lock()
for _, sub := range s.subscriptions {
err := maybeNotifySubscribers(ctx, sub.idx)
if err != nil {
log.Errorf("unable to notify sync subscribers: %v", err)
s.cancel()
}
}
s.mtx.Unlock()
}
}
}
// handleIndexUpdates relays updates to subscribed indexers.
func (s *IndexSubscriber) handleIndexUpdates(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case ntfn := <-s.c:
// Relay the index update to subscribed indexes.
s.mtx.Lock()
for _, sub := range s.subscriptions {
err := updateIndex(ctx, sub.idx, &ntfn)
if err != nil {
log.Error(err)
s.cancel()
break
}
}
s.mtx.Unlock()
if ntfn.Done != nil {
close(ntfn.Done)
}
}
}
}
// Run relays index notifications to subscribed indexes.
//
// This should be run as a goroutine.
func (s *IndexSubscriber) Run(ctx context.Context) {
var wg sync.WaitGroup
wg.Add(2)
go func() {
s.handleIndexUpdates(ctx)
wg.Done()
}()
go func() {
s.handleSyncSubscribers(ctx)
wg.Done()
}()
// Stop all the subscriptions and shutdown the subscriber when the context
// is cancelled.
<-ctx.Done()
close(s.quit)
s.mtx.Lock()
for _, sub := range s.subscriptions {
err := sub.stop()
if err != nil {
log.Errorf("unable to stop index subscription: %v", err)
}
}
s.mtx.Unlock()
s.cancel()
wg.Wait()
log.Tracef("Index subscriber stopped")
}