Skip to content
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

feat!: provide context object for callback functions #579

Merged
merged 1 commit into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cmd/gouroboros/chainsync.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -256,12 +256,13 @@ func testChainSync(f *globalFlags) {
select {}
}

func chainSyncRollBackwardHandler(point common.Point, tip chainsync.Tip) error {
func chainSyncRollBackwardHandler(ctx chainsync.CallbackContext, point common.Point, tip chainsync.Tip) error {
fmt.Printf("roll backward: point = %#v, tip = %#v\n", point, tip)
return nil
}

func chainSyncRollForwardHandler(
ctx chainsync.CallbackContext,
blockType uint,
blockData interface{},
tip chainsync.Tip,
Expand Down Expand Up @@ -312,7 +313,7 @@ func chainSyncRollForwardHandler(
return nil
}

func blockFetchBlockHandler(blockData ledger.Block) error {
func blockFetchBlockHandler(ctx blockfetch.CallbackContext, blockData ledger.Block) error {
switch block := blockData.(type) {
case *ledger.ByronEpochBoundaryBlock:
fmt.Printf("era = Byron (EBB), epoch = %d, slot = %d, id = %s\n", block.Header.ConsensusData.Epoch, block.SlotNumber(), block.Hash())
Expand Down
4 changes: 3 additions & 1 deletion cmd/tx-submission/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -145,6 +145,7 @@ func main() {
}

func handleRequestTxIds(
ctx txsubmission.CallbackContext,
blocking bool,
ack uint16,
req uint16,
Expand All @@ -167,6 +168,7 @@ func handleRequestTxIds(
}

func handleRequestTxs(
ctx txsubmission.CallbackContext,
txIds []txsubmission.TxId,
) ([]txsubmission.TxBody, error) {
ret := []txsubmission.TxBody{
Expand Down
25 changes: 8 additions & 17 deletions connection.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -31,6 +31,7 @@ import (
"sync"
"time"

"github.com/blinklabs-io/gouroboros/connection"
"github.com/blinklabs-io/gouroboros/muxer"
"github.com/blinklabs-io/gouroboros/protocol"
"github.com/blinklabs-io/gouroboros/protocol/blockfetch"
Expand All @@ -49,6 +50,8 @@ const (
DefaultConnectTimeout = 30 * time.Second
)

type ConnectionId = connection.ConnectionId

// The Connection type is a wrapper around a net.Conn object that handles communication using the Ouroboros network protocol over that connection
type Connection struct {
id ConnectionId
Expand Down Expand Up @@ -90,19 +93,6 @@ type Connection struct {
txSubmissionConfig *txsubmission.Config
}

type ConnectionId struct {
LocalAddr net.Addr
RemoteAddr net.Addr
}

func (c ConnectionId) String() string {
return fmt.Sprintf(
"%s<->%s",
c.LocalAddr.String(),
c.RemoteAddr.String(),
)
}

// NewConnection returns a new Connection object with the specified options. If a connection is provided, the
// handshake will be started. An error will be returned if the handshake fails
func NewConnection(options ...ConnectionOptionFunc) (*Connection, error) {
Expand Down Expand Up @@ -289,8 +279,9 @@ func (c *Connection) setupConnection() error {
}
}()
protoOptions := protocol.ProtocolOptions{
Muxer: c.muxer,
ErrorChan: c.protoErrorChan,
ConnectionId: c.id,
Muxer: c.muxer,
ErrorChan: c.protoErrorChan,
}
if c.useNodeToNodeProto {
protoOptions.Mode = protocol.ProtocolModeNodeToNode
Expand Down Expand Up @@ -319,7 +310,7 @@ func (c *Connection) setupConnection() error {
var handshakeFullDuplex bool
handshakeConfig := handshake.NewConfig(
handshake.WithProtocolVersionMap(protoVersions),
handshake.WithFinishedFunc(func(version uint16, versionData protocol.VersionData) error {
handshake.WithFinishedFunc(func(ctx handshake.CallbackContext, version uint16, versionData protocol.VersionData) error {
c.handshakeVersion = version
c.handshakeVersionData = versionData
if c.useNodeToNodeProto {
Expand Down
33 changes: 33 additions & 0 deletions connection/id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package connection

import (
"fmt"
"net"
)

type ConnectionId struct {
LocalAddr net.Addr
RemoteAddr net.Addr
}

func (c ConnectionId) String() string {
return fmt.Sprintf(
"%s<->%s",
c.LocalAddr.String(),
c.RemoteAddr.String(),
)
}
14 changes: 11 additions & 3 deletions protocol/blockfetch/blockfetch.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -17,6 +17,7 @@ package blockfetch
import (
"time"

"github.com/blinklabs-io/gouroboros/connection"
"github.com/blinklabs-io/gouroboros/protocol"
"github.com/blinklabs-io/gouroboros/protocol/common"

Expand Down Expand Up @@ -92,9 +93,16 @@ type Config struct {
BlockTimeout time.Duration
}

// Callback context
type CallbackContext struct {
ConnectionId connection.ConnectionId
Client *Client
Server *Server
}

// Callback function types
type BlockFunc func(ledger.Block) error
type RequestRangeFunc func(common.Point, common.Point) error
type BlockFunc func(CallbackContext, ledger.Block) error
type RequestRangeFunc func(CallbackContext, common.Point, common.Point) error

func New(protoOptions protocol.ProtocolOptions, cfg *Config) *BlockFetch {
b := &BlockFetch{
Expand Down
9 changes: 7 additions & 2 deletions protocol/blockfetch/client.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,6 +28,7 @@ import (
type Client struct {
*protocol.Protocol
config *Config
callbackContext CallbackContext
blockChan chan ledger.Block
startBatchResultChan chan error
busyMutex sync.Mutex
Expand All @@ -46,6 +47,10 @@ func NewClient(protoOptions protocol.ProtocolOptions, cfg *Config) *Client {
blockChan: make(chan ledger.Block),
startBatchResultChan: make(chan error),
}
c.callbackContext = CallbackContext{
Client: c,
ConnectionId: protoOptions.ConnectionId,
}
// Update state map with timeouts
stateMap := StateMap.Copy()
if entry, ok := stateMap[StateBusy]; ok {
Expand Down Expand Up @@ -186,7 +191,7 @@ func (c *Client) handleBlock(msgGeneric protocol.Message) error {
}
// We use the callback when requesting ranges and the internal channel for a single block
if c.blockUseCallback {
if err := c.config.BlockFunc(blk); err != nil {
if err := c.config.BlockFunc(c.callbackContext, blk); err != nil {
return err
}
} else {
Expand Down
11 changes: 8 additions & 3 deletions protocol/blockfetch/server.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -23,13 +23,18 @@ import (

type Server struct {
*protocol.Protocol
config *Config
config *Config
callbackContext CallbackContext
}

func NewServer(protoOptions protocol.ProtocolOptions, cfg *Config) *Server {
s := &Server{
config: cfg,
}
s.callbackContext = CallbackContext{
Server: s,
ConnectionId: protoOptions.ConnectionId,
}
protoConfig := protocol.ProtocolConfig{
Name: ProtocolName,
ProtocolId: ProtocolId,
Expand Down Expand Up @@ -98,7 +103,7 @@ func (s *Server) handleRequestRange(msg protocol.Message) error {
)
}
msgRequestRange := msg.(*MsgRequestRange)
return s.config.RequestRangeFunc(msgRequestRange.Start, msgRequestRange.End)
return s.config.RequestRangeFunc(s.callbackContext, msgRequestRange.Start, msgRequestRange.End)
}

func (s *Server) handleClientDone() error {
Expand Down
18 changes: 13 additions & 5 deletions protocol/chainsync/chainsync.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -18,6 +18,7 @@ package chainsync
import (
"time"

"github.com/blinklabs-io/gouroboros/connection"
"github.com/blinklabs-io/gouroboros/protocol"
"github.com/blinklabs-io/gouroboros/protocol/common"
)
Expand Down Expand Up @@ -121,11 +122,18 @@ type Config struct {
PipelineLimit int
}

// Callback context
type CallbackContext struct {
ConnectionId connection.ConnectionId
Client *Client
Server *Server
}

// Callback function types
type RollBackwardFunc func(common.Point, Tip) error
type RollForwardFunc func(uint, interface{}, Tip) error
type FindIntersectFunc func([]common.Point) (common.Point, Tip, error)
type RequestNextFunc func() error
type RollBackwardFunc func(CallbackContext, common.Point, Tip) error
type RollForwardFunc func(CallbackContext, uint, interface{}, Tip) error
type FindIntersectFunc func(CallbackContext, []common.Point) (common.Point, Tip, error)
type RequestNextFunc func(CallbackContext) error

// New returns a new ChainSync object
func New(protoOptions protocol.ProtocolOptions, cfg *Config) *ChainSync {
Expand Down
13 changes: 9 additions & 4 deletions protocol/chainsync/client.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -28,6 +28,7 @@ import (
type Client struct {
*protocol.Protocol
config *Config
callbackContext CallbackContext
busyMutex sync.Mutex
intersectResultChan chan error
readyForNextBlockChan chan bool
Expand Down Expand Up @@ -63,6 +64,10 @@ func NewClient(protoOptions protocol.ProtocolOptions, cfg *Config) *Client {
firstBlockChan: make(chan common.Point),
intersectPointChan: make(chan common.Point),
}
c.callbackContext = CallbackContext{
Client: c,
ConnectionId: protoOptions.ConnectionId,
}
// Update state map with timeouts
stateMap := StateMap.Copy()
if entry, ok := stateMap[stateIntersect]; ok {
Expand Down Expand Up @@ -343,7 +348,7 @@ func (c *Client) handleRollForward(msgGeneric protocol.Message) error {
return nil
}
// Call the user callback function
callbackErr = c.config.RollForwardFunc(blockType, blockHeader, msg.Tip)
callbackErr = c.config.RollForwardFunc(c.callbackContext, blockType, blockHeader, msg.Tip)
} else {
msg := msgGeneric.(*MsgRollForwardNtC)
blk, err := ledger.NewBlockFromCbor(msg.BlockType(), msg.BlockCbor())
Expand All @@ -360,7 +365,7 @@ func (c *Client) handleRollForward(msgGeneric protocol.Message) error {
return nil
}
// Call the user callback function
callbackErr = c.config.RollForwardFunc(msg.BlockType(), blk, msg.Tip)
callbackErr = c.config.RollForwardFunc(c.callbackContext, msg.BlockType(), blk, msg.Tip)
}
if callbackErr != nil {
if callbackErr == StopSyncProcessError {
Expand Down Expand Up @@ -388,7 +393,7 @@ func (c *Client) handleRollBackward(msg protocol.Message) error {
)
}
// Call the user callback function
if callbackErr := c.config.RollBackwardFunc(msgRollBackward.Point, msgRollBackward.Tip); callbackErr != nil {
if callbackErr := c.config.RollBackwardFunc(c.callbackContext, msgRollBackward.Point, msgRollBackward.Tip); callbackErr != nil {
if callbackErr == StopSyncProcessError {
// Signal that we're cancelling the sync
c.readyForNextBlockChan <- false
Expand Down
13 changes: 9 additions & 4 deletions protocol/chainsync/server.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2023 Blink Labs Software
// Copyright 2024 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -25,7 +25,8 @@ import (
// Server implements the ChainSync server
type Server struct {
*protocol.Protocol
config *Config
config *Config
callbackContext CallbackContext
}

// NewServer returns a new ChainSync server object
Expand All @@ -41,6 +42,10 @@ func NewServer(protoOptions protocol.ProtocolOptions, cfg *Config) *Server {
s := &Server{
config: cfg,
}
s.callbackContext = CallbackContext{
Server: s,
ConnectionId: protoOptions.ConnectionId,
}
protoConfig := protocol.ProtocolConfig{
Name: ProtocolName,
ProtocolId: ProtocolId,
Expand Down Expand Up @@ -112,7 +117,7 @@ func (s *Server) handleRequestNext(msg protocol.Message) error {
"received chain-sync RequestNext message but no callback function is defined",
)
}
return s.config.RequestNextFunc()
return s.config.RequestNextFunc(s.callbackContext)
}

func (s *Server) handleFindIntersect(msg protocol.Message) error {
Expand All @@ -122,7 +127,7 @@ func (s *Server) handleFindIntersect(msg protocol.Message) error {
)
}
msgFindIntersect := msg.(*MsgFindIntersect)
point, tip, err := s.config.FindIntersectFunc(msgFindIntersect.Points)
point, tip, err := s.config.FindIntersectFunc(s.callbackContext, msgFindIntersect.Points)
if err != nil {
if err == IntersectNotFoundError {
msgResp := NewMsgIntersectNotFound(tip)
Expand Down
Loading