-
Notifications
You must be signed in to change notification settings - Fork 211
/
reporter.go
654 lines (573 loc) · 17.3 KB
/
reporter.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
package events
import (
"errors"
"fmt"
"sync"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/timesync"
"go.uber.org/zap/zapcore"
)
// reporter is the event reporter singleton.
var reporter *EventReporter
// we use a mutex to ensure thread safety
var mu sync.RWMutex
func init() {
mu = sync.RWMutex{}
}
// ReportNewTx dispatches incoming events to the reporter singleton
func ReportNewTx(tx *types.Transaction) {
Publish(NewTx{
ID: tx.ID().String(),
Origin: tx.Origin().String(),
Destination: tx.Recipient.String(),
Amount: tx.Amount,
Fee: tx.Fee,
})
ReportTxWithValidity(tx, true)
}
// ReportTxWithValidity reports a tx along with whether it was just invalidated
func ReportTxWithValidity(tx *types.Transaction, valid bool) {
mu.RLock()
defer mu.RUnlock()
txWithValidity := TransactionWithValidity{
Transaction: tx,
Valid: valid,
}
if reporter != nil {
log.With().Info("about to report tx validity updates", txWithValidity.Transaction.ID(),
log.Bool("validity", txWithValidity.Valid))
for sub := range reporter.transactionSubs {
select {
case sub <- txWithValidity:
log.With().Debug("reported tx to subs", txWithValidity.Transaction.ID(),
log.Bool("validity", txWithValidity.Valid))
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported tx validity update to subscribers", txWithValidity.Transaction.ID(),
log.Bool("validity", txWithValidity.Valid))
}
}
// ReportValidTx reports a valid transaction
func ReportValidTx(tx *types.Transaction, valid bool) {
Publish(ValidTx{ID: tx.ID().String(), Valid: valid})
}
// ReportNewActivation reports a new activation
func ReportNewActivation(activation *types.ActivationTx) {
mu.RLock()
defer mu.RUnlock()
Publish(NewAtx{
ID: activation.ShortString(),
LayerID: uint64(activation.PubLayerID.GetEpoch()),
})
if reporter != nil {
innerBytes, err := activation.InnerBytes()
if err != nil {
log.Error("error attempting to report activation: unable to encode activation")
return
}
for sub := range reporter.activationSubs {
select {
case sub <- activation:
log.With().Debug("reported activation", activation.Fields(len(innerBytes))...)
default:
log.Debug("reporter would block on subscriber")
}
}
}
}
// SubscribeToRewards subscribes a channel to rewards events
func SubscribeToRewards() chan Reward {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan Reward, reporter.bufsize)
reporter.rewardsSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromRewards unsubscribes a channel from rewards events
// do we need to close the subscriber channel here?
func UnsubscribeFromRewards(subscriptionChannel chan Reward) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.rewardsSubs[subscriptionChannel]; exists {
delete(reporter.rewardsSubs, subscriptionChannel)
}
}
}
// ReportRewardReceived reports a new reward
func ReportRewardReceived(r Reward) {
mu.RLock()
defer mu.RUnlock()
Publish(RewardReceived{
Coinbase: r.Coinbase.String(),
Amount: r.Total,
SmesherID: r.Smesher.ToBytes(),
})
if reporter != nil {
log.With().Info("about to report reward", r)
for sub := range reporter.rewardsSubs {
select {
case sub <- r:
log.With().Debug("reporter send reward to subscriber", r)
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported reward to subscribers", r)
}
}
// ReportNewBlock reports a new block
func ReportNewBlock(blk *types.Block) {
Publish(NewBlock{
ID: blk.ID().String(),
Atx: blk.ATXID.ShortString(),
Layer: uint64(blk.LayerIndex),
})
}
// ReportValidBlock reports a block's validity
func ReportValidBlock(blockID types.BlockID, valid bool) {
Publish(ValidBlock{
ID: blockID.String(),
Valid: valid,
})
}
// ReportAtxCreated reports a created activation
func ReportAtxCreated(created bool, layer uint64, id string) {
Publish(AtxCreated{Created: created, Layer: layer, ID: id})
}
// ReportValidActivation reports a valid activation
func ReportValidActivation(activation *types.ActivationTx, valid bool) {
Publish(ValidAtx{ID: activation.ShortString(), Valid: valid})
}
// ReportDoneCreatingBlock reports a created block
func ReportDoneCreatingBlock(eligible bool, layer uint64, error string) {
Publish(DoneCreatingBlock{
Eligible: eligible,
Layer: layer,
Error: error,
})
}
// ReportNewLayer reports a new layer
func ReportNewLayer(layer NewLayer) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
log.With().Info("about to report new layer", layer)
for sub := range reporter.layerSubs {
select {
case sub <- layer:
log.With().Debug("reporter new layer to subscriber", layer)
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported layer update to subscribers", layer)
}
}
// ReportError reports an error
func ReportError(err NodeError) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
log.With().Info("about to report error updates for error", log.String("error-msg", err.Msg))
for sub := range reporter.errorSubs {
select {
case sub <- err:
log.With().Debug("reported error updates to subscriber for error", log.String("error-msg", err.Msg))
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported error update to subscribers")
}
}
// ReportNodeStatusUpdate reports an update to the node status. It just
// pings the listener to notify them that there is an update; the listener
// is responsible for fetching the new status details. This is because
// status contains disparate information coming from different services,
// and the listener already knows how to gather that information so there
// is no point in duplicating that logic here.
// Note: There is some overlap with channelLayer here, as a new latest
// or verified layer should be sent over that channel as well. However,
// that happens inside the Mesh, at the source. It doesn't currently
// happen here because the status update includes only a layer ID, not
// full layer data, and the Reporter currently has no way to retrieve
// full layer data.
func ReportNodeStatusUpdate() {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
for sub := range reporter.statusSubs {
select {
case sub <- struct{}{}:
default:
log.Debug("reporter would block on subscriber")
}
}
}
}
// ReportReceipt reports creation or receipt of a new tx receipt
func ReportReceipt(r TxReceipt) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
log.With().Info("about to report receipts for", r, r.Address)
for sub := range reporter.receiptsSubs {
select {
case sub <- r:
log.With().Debug("reporter send receipt to subscriber", r, r.Address)
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported receipt to subscribers", r, r.Address)
}
}
// ReportAccountUpdate reports an account whose data has been updated
func ReportAccountUpdate(a types.Address) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
log.With().Info("about to report account update for", a)
for sub := range reporter.accountsSubs {
select {
case sub <- a:
log.With().Debug("reporter send account to subscriber", a)
default:
log.Debug("reporter would block on subscriber")
}
}
log.With().Debug("reported account update to subscribers", a)
}
}
// GetNewTxChannel returns a channel of new transactions
// func GetNewTxChannel() chan TransactionWithValidity {
// mu.RLock()
// defer mu.RUnlock()
// if reporter != nil {
// return reporter.channelTransaction
// }
// return nil
// }
// SubscribeToTxChannel subscribes a process to tx updates
func SubscribeToTxChannel() chan TransactionWithValidity {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan TransactionWithValidity, reporter.bufsize)
reporter.transactionSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromTxChannel unsubscribes a process from tx updates
func UnsubscribeFromTxChannel(subscriptionChannel chan TransactionWithValidity) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.transactionSubs[subscriptionChannel]; exists {
delete(reporter.transactionSubs, subscriptionChannel)
}
}
}
// SubscribeToActivations allows a process to subscribe to events of activations
func SubscribeToActivations() chan *types.ActivationTx {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan *types.ActivationTx, reporter.bufsize)
reporter.activationSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromActivations allows a process to unsubscribe from layer events
func UnsubscribeFromActivations(subscriptionChannel chan *types.ActivationTx) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.activationSubs[subscriptionChannel]; exists {
delete(reporter.activationSubs, subscriptionChannel)
}
}
}
// SubscribeToLayerChannel allows a process to subscribe to events of newLayers
func SubscribeToLayerChannel() chan NewLayer {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan NewLayer, reporter.bufsize)
reporter.layerSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromLayerChannel allows a process to unsubscribe from layer events
func UnsubscribeFromLayerChannel(subscriptionChannel chan NewLayer) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.layerSubs[subscriptionChannel]; exists {
delete(reporter.layerSubs, subscriptionChannel)
}
}
}
// SubscribeToErrors allows a goroutine to receive a channel for
// error notifications
func SubscribeToErrors() chan NodeError {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan NodeError, reporter.bufsize)
reporter.errorSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromErrors allows a goroutine to unsubscribe from the error channel
func UnsubscribeFromErrors(subscriberChannel chan NodeError) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.errorSubs[subscriberChannel]; exists {
delete(reporter.errorSubs, subscriberChannel)
}
}
}
// SubscribeToStatus subscribes a channel to receive status updates
func SubscribeToStatus() chan struct{} {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan struct{}, reporter.bufsize)
reporter.statusSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromStatus unsubscribes a channel from receiving status updates
func UnsubscribeFromStatus(subscriberChannel chan struct{}) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.statusSubs[subscriberChannel]; exists {
delete(reporter.statusSubs, subscriberChannel)
return
}
}
}
// SubscribeToAccounts subscribes a channel to account update events
func SubscribeToAccounts() chan types.Address {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan types.Address, reporter.bufsize)
reporter.accountsSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromAccounts unsubscribes a channel from accounts events
// do we need to close the subscriber channel here?
func UnsubscribeFromAccounts(subscriptionChannel chan types.Address) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.accountsSubs[subscriptionChannel]; exists {
delete(reporter.accountsSubs, subscriptionChannel)
}
}
}
// SubscribeToReceipts allows a process to subscribe to receipt events
func SubscribeToReceipts() chan TxReceipt {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
newChan := make(chan TxReceipt, reporter.bufsize)
reporter.receiptsSubs[newChan] = struct{}{}
return newChan
}
return nil
}
// UnsubscribeFromReceipts removes a channel from receipt event notifications
func UnsubscribeFromReceipts(subscriptionChannel chan TxReceipt) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
if _, exists := reporter.receiptsSubs[subscriptionChannel]; exists {
delete(reporter.receiptsSubs, subscriptionChannel)
}
}
}
// InitializeEventReporter initializes the event reporting interface
func InitializeEventReporter(url string) error {
// Need to buffer the channels so that slow subscribers can still receive updates
return InitializeEventReporterWithOptions(url, 30)
}
// InitializeEventReporterWithOptions initializes the event reporting interface with
// a nonzero channel buffer. This is useful for testing, where we want reporting to
// block.
func InitializeEventReporterWithOptions(url string, bufsize int) error {
mu.Lock()
defer mu.Unlock()
if reporter != nil {
return errors.New("reporter is already initialized, call CloseEventReporter before reinitializing")
}
reporter = newEventReporter(bufsize)
if url != "" {
InitializeEventPubsub(url)
}
return nil
}
// SubscribeToLayers is used to track and report automatically every time a
// new layer is reached.
func SubscribeToLayers(newLayerCh timesync.LayerTimer) {
mu.RLock()
defer mu.RUnlock()
if reporter != nil {
// This will block, so run in a goroutine
go func() {
for {
select {
case layer := <-newLayerCh:
log.With().Debug("reporter got new layer", layer)
ReportNodeStatusUpdate()
case <-reporter.stopChan:
return
}
}
}()
}
}
// The status of a layer
const (
LayerStatusTypeUnknown = iota
LayerStatusTypeApproved // approved by Hare
LayerStatusTypeConfirmed // confirmed by Tortoise
)
// NewLayer packages up a layer with its status (which a layer does not
// ordinarily contain)
type NewLayer struct {
Layer *types.Layer
Status int
}
// Field returns a log field. Implements the LoggableField interface.
func (nl NewLayer) Field() log.Field {
return log.String("layer",
fmt.Sprintf("status: %d, number: %d, numblocks: %d",
nl.Status, nl.Layer.Index(), len(nl.Layer.Blocks())))
}
// NodeError represents an internal error to be reported
type NodeError struct {
Msg string
Trace string
Level zapcore.Level
}
// TxReceipt represents a transaction receipt
type TxReceipt struct {
ID types.TransactionID
Result int
GasUsed uint64
Fee uint64
Layer types.LayerID
Index uint32
Address types.Address
}
func (t TxReceipt) String() string {
return fmt.Sprintf("ID: %v, Result: %v, Gas Used: %v, Fee: %v, Layer: %v, Index: %v",
t.ID, t.Result, t.GasUsed, t.Fee, t.Layer, t.Index)
}
// Field returns a loggable field representation of the TxReceipt
func (t TxReceipt) Field() log.Field {
return log.String("transaction-receipt", t.String())
}
// Reward represents a reward object with extra data needed by the API
type Reward struct {
Layer types.LayerID
Total uint64
LayerReward uint64
Coinbase types.Address
// TODO: We don't currently have a way to get the Layer Computed.
// See https://github.com/spacemeshos/go-spacemesh/issues/2275
//LayerComputed
Smesher types.NodeID
}
func (r Reward) String() string {
return fmt.Sprintf("Layer: %v, Total: %v, LayerReward: %v, Coinbase: %v, Smesher: %v",
r.Layer, r.Total, r.LayerReward, r.Coinbase, r.Smesher)
}
// Field returns a loggable field representation of the Reward struct
func (r Reward) Field() log.Field {
return log.String("reward", r.String())
}
// TransactionWithValidity wraps a tx with its validity info
type TransactionWithValidity struct {
Transaction *types.Transaction
Valid bool
}
// EventReporter is the struct that receives incoming events and dispatches them
type EventReporter struct {
stopChan chan struct{}
rewardsSubs map[chan Reward]struct{}
accountsSubs map[chan types.Address]struct{}
receiptsSubs map[chan TxReceipt]struct{}
statusSubs map[chan struct{}]struct{}
errorSubs map[chan NodeError]struct{}
layerSubs map[chan NewLayer]struct{}
activationSubs map[chan *types.ActivationTx]struct{}
transactionSubs map[chan TransactionWithValidity]struct{}
bufsize int
}
func newEventReporter(bufsize int) *EventReporter {
return &EventReporter{
stopChan: make(chan struct{}),
rewardsSubs: make(map[chan Reward]struct{}),
accountsSubs: make(map[chan types.Address]struct{}),
receiptsSubs: make(map[chan TxReceipt]struct{}),
statusSubs: make(map[chan struct{}]struct{}),
errorSubs: make(map[chan NodeError]struct{}),
layerSubs: make(map[chan NewLayer]struct{}),
activationSubs: make(map[chan *types.ActivationTx]struct{}),
transactionSubs: make(map[chan TransactionWithValidity]struct{}),
bufsize: bufsize,
}
}
// CloseEventReporter shuts down the event reporting service and closes open channels
func CloseEventReporter() {
mu.Lock()
defer mu.Unlock()
if reporter != nil {
close(reporter.stopChan)
for c := range reporter.rewardsSubs {
close(c)
}
for c := range reporter.accountsSubs {
close(c)
}
for c := range reporter.receiptsSubs {
close(c)
}
for c := range reporter.statusSubs {
close(c)
}
for c := range reporter.errorSubs {
close(c)
}
for c := range reporter.layerSubs {
close(c)
}
for c := range reporter.activationSubs {
close(c)
}
for c := range reporter.transactionSubs {
close(c)
}
reporter = nil
}
}