-
Notifications
You must be signed in to change notification settings - Fork 291
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Factor message queue and friends into ./msgq
- Loading branch information
Eugene Kim
committed
Oct 8, 2019
1 parent
4e479e2
commit 39ec270
Showing
3 changed files
with
60 additions
and
32 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package msgq | ||
|
||
import ( | ||
"github.com/libp2p/go-libp2p-core/peer" | ||
"github.com/pkg/errors" | ||
|
||
"github.com/harmony-one/harmony/node" | ||
) | ||
|
||
// MessageHandler is a message handler. | ||
type MessageHandler interface { | ||
HandleMessage(content []byte, sender peer.ID) | ||
} | ||
|
||
// MessageQueue is a finite-sized message queue. It can be used as an overrun | ||
// protection mechanism. | ||
type MessageQueue struct { | ||
ch chan node.incomingMessage | ||
} | ||
|
||
// NewMessageQueue returns a new message queue of the given size, which must be | ||
// non-negative. | ||
func NewMessageQueue(size int) *MessageQueue { | ||
return &MessageQueue{ch: make(chan node.incomingMessage, size)} | ||
} | ||
|
||
// AddMessage enqueues a received message for processing. It returns without | ||
// blocking, and may return a queue overrun error. | ||
func (q *MessageQueue) AddMessage(content []byte, sender peer.ID) error { | ||
select { | ||
case q.ch <- node.incomingMessage{content, sender}: | ||
default: | ||
return ErrRxOverrun | ||
} | ||
return nil | ||
} | ||
|
||
// HandleMessages dequeues and dispatches incoming messages using the given | ||
// message handler, until the message queue is closed. This function can be | ||
// spawned as a background goroutine, potentially multiple times for a pool. | ||
func (q *MessageQueue) HandleMessages(h MessageHandler) { | ||
for msg := range q.ch { | ||
h.HandleMessage(msg.content, msg.sender) | ||
} | ||
} | ||
|
||
// ErrRxOverrun signals that a receive queue has been overrun. | ||
var ErrRxOverrun = errors.New("rx overrun") | ||
|
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