-
Notifications
You must be signed in to change notification settings - Fork 39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New heads subscription #1861
Merged
Merged
New heads subscription #1861
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
package subscription | ||
|
||
import ( | ||
"math/big" | ||
"sync" | ||
"sync/atomic" | ||
|
||
gethcommon "github.com/ethereum/go-ethereum/common" | ||
"github.com/ethereum/go-ethereum/core/types" | ||
|
||
gethlog "github.com/ethereum/go-ethereum/log" | ||
"github.com/ten-protocol/go-ten/go/common" | ||
"github.com/ten-protocol/go-ten/go/common/host" | ||
"github.com/ten-protocol/go-ten/go/common/log" | ||
"github.com/ten-protocol/go-ten/lib/gethfork/rpc" | ||
) | ||
|
||
// NewHeadsService multiplexes new batch header messages from an input channel into multiple subscribers | ||
// also handles unsubscribe | ||
// Note: this is a service which must be Started and Stopped | ||
type NewHeadsService struct { | ||
inputCh chan *common.BatchHeader | ||
convertToEthHeader bool | ||
notifiersMutex *sync.RWMutex | ||
newHeadNotifiers map[rpc.ID]*rpc.Notifier | ||
onMessage func(*common.BatchHeader) error | ||
stopped *atomic.Bool | ||
logger gethlog.Logger | ||
} | ||
|
||
func NewNewHeadsService(inputCh chan *common.BatchHeader, convertToEthHeader bool, logger gethlog.Logger, onMessage func(*common.BatchHeader) error) *NewHeadsService { | ||
return &NewHeadsService{ | ||
inputCh: inputCh, | ||
convertToEthHeader: convertToEthHeader, | ||
onMessage: onMessage, | ||
logger: logger, | ||
stopped: &atomic.Bool{}, | ||
newHeadNotifiers: make(map[rpc.ID]*rpc.Notifier), | ||
notifiersMutex: &sync.RWMutex{}, | ||
} | ||
} | ||
|
||
func (nhs *NewHeadsService) Start() error { | ||
go ForwardFromChannels([]chan *common.BatchHeader{nhs.inputCh}, nhs.stopped, func(head *common.BatchHeader) error { | ||
nhs.notifiersMutex.RLock() | ||
defer nhs.notifiersMutex.RUnlock() | ||
|
||
if nhs.onMessage != nil { | ||
err := nhs.onMessage(head) | ||
if err != nil { | ||
nhs.logger.Info("failed invoking onMessage callback.", log.ErrKey, err) | ||
} | ||
} | ||
|
||
var msg any = head | ||
if nhs.convertToEthHeader { | ||
msg = convertBatchHeader(head) | ||
} | ||
|
||
// for each new head, notify all registered subscriptions | ||
for id, notifier := range nhs.newHeadNotifiers { | ||
if nhs.stopped.Load() { | ||
return nil | ||
} | ||
err := notifier.Notify(id, msg) | ||
if err != nil { | ||
// on error, remove the notification | ||
nhs.logger.Info("failed to notify newHead subscription", log.ErrKey, err, log.SubIDKey, id) | ||
nhs.notifiersMutex.Lock() | ||
delete(nhs.newHeadNotifiers, id) | ||
nhs.notifiersMutex.Unlock() | ||
} | ||
} | ||
return nil | ||
}) | ||
return nil | ||
} | ||
|
||
func (nhs *NewHeadsService) RegisterNotifier(notifier *rpc.Notifier, subscription *rpc.Subscription) { | ||
nhs.notifiersMutex.Lock() | ||
defer nhs.notifiersMutex.Unlock() | ||
nhs.newHeadNotifiers[subscription.ID] = notifier | ||
|
||
go HandleUnsubscribe(subscription, nil, func() { | ||
nhs.notifiersMutex.Lock() | ||
defer nhs.notifiersMutex.Unlock() | ||
delete(nhs.newHeadNotifiers, subscription.ID) | ||
}) | ||
} | ||
|
||
func (nhs *NewHeadsService) Stop() error { | ||
nhs.stopped.Store(true) | ||
return nil | ||
} | ||
|
||
func (nhs *NewHeadsService) HealthStatus() host.HealthStatus { | ||
return &host.BasicErrHealthStatus{} | ||
} | ||
|
||
func convertBatchHeader(head *common.BatchHeader) *types.Header { | ||
return &types.Header{ | ||
ParentHash: head.ParentHash, | ||
UncleHash: gethcommon.Hash{}, | ||
Root: head.Root, | ||
TxHash: head.TxHash, | ||
ReceiptHash: head.ReceiptHash, | ||
Bloom: types.Bloom{}, | ||
Difficulty: big.NewInt(0), | ||
Number: head.Number, | ||
GasLimit: head.GasLimit, | ||
GasUsed: head.GasUsed, | ||
Time: head.Time, | ||
Extra: make([]byte, 0), | ||
BaseFee: head.BaseFee, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package subscription | ||
|
||
import ( | ||
"reflect" | ||
"sync/atomic" | ||
"time" | ||
|
||
"github.com/ten-protocol/go-ten/lib/gethfork/rpc" | ||
) | ||
|
||
// ForwardFromChannels - reads messages from the input channels, and calls the `onMessage` callback. | ||
// Exits when the unsubscribed flag is true. | ||
// Must be called as a go routine! | ||
func ForwardFromChannels[R any](inputChannels []chan R, unsubscribed *atomic.Bool, onMessage func(R) error) { | ||
inputCases := make([]reflect.SelectCase, len(inputChannels)+1) | ||
|
||
// create a ticker to handle cleanup, check the "unsubscribed" flag and exit the goroutine | ||
inputCases[0] = reflect.SelectCase{ | ||
Dir: reflect.SelectRecv, | ||
Chan: reflect.ValueOf(time.NewTicker(2 * time.Second).C), | ||
} | ||
|
||
// create a select "case" for each input channel | ||
for i, ch := range inputChannels { | ||
inputCases[i+1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ch)} | ||
} | ||
|
||
unclosedInputChannels := len(inputCases) | ||
for unclosedInputChannels > 0 { | ||
chosen, value, ok := reflect.Select(inputCases) | ||
if !ok { | ||
// The chosen channel has been closed, so zero out the channel to disable the case | ||
inputCases[chosen].Chan = reflect.ValueOf(nil) | ||
unclosedInputChannels-- | ||
continue | ||
} | ||
|
||
if unsubscribed.Load() { | ||
return | ||
} | ||
|
||
switch v := value.Interface().(type) { | ||
case time.Time: | ||
// exit the loop to avoid a goroutine leak | ||
if unsubscribed.Load() { | ||
return | ||
} | ||
case R: | ||
err := onMessage(v) | ||
if err != nil { | ||
// todo - log | ||
return | ||
} | ||
default: | ||
// ignore unexpected element | ||
continue | ||
} | ||
} | ||
} | ||
|
||
// HandleUnsubscribe - when the client calls "unsubscribe" or the subscription times out, it calls `onSub` | ||
// Must be called as a go routine! | ||
func HandleUnsubscribe(connectionSub *rpc.Subscription, unsubscribed *atomic.Bool, onUnsub func()) { | ||
<-connectionSub.Err() | ||
if unsubscribed != nil { | ||
unsubscribed.Store(true) | ||
} | ||
onUnsub() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Worth a comment on this to say it should only be called once.