peermessagemanager.go 1.38 KB
Newer Older
1 2 3 4 5
package peermanager

import (
	"context"

Hannah Howard's avatar
Hannah Howard committed
6
	"github.com/libp2p/go-libp2p-core/peer"
7

8
	gsmsg "github.com/ipfs/go-graphsync/message"
9
	"github.com/ipfs/go-graphsync/notifications"
10 11 12 13 14
)

// PeerQueue is a process that sends messages to a peer
type PeerQueue interface {
	PeerProcess
15
	AllocateAndBuildMessage(blkSize uint64, buildMessageFn func(*gsmsg.Builder), notifees []notifications.Notifee)
16 17 18 19 20 21 22 23 24 25 26 27 28
}

// PeerQueueFactory provides a function that will create a PeerQueue.
type PeerQueueFactory func(ctx context.Context, p peer.ID) PeerQueue

// PeerMessageManager manages message queues for peers
type PeerMessageManager struct {
	*PeerManager
}

// NewMessageManager generates a new manger for sending messages
func NewMessageManager(ctx context.Context, createPeerQueue PeerQueueFactory) *PeerMessageManager {
	return &PeerMessageManager{
29
		PeerManager: New(ctx, func(ctx context.Context, p peer.ID) PeerHandler {
30 31 32 33 34
			return createPeerQueue(ctx, p)
		}),
	}
}

35
// BuildMessage allows you to modify the next message that is sent for the given peer
36 37
// If blkSize > 0, message building may block until enough memory has been freed from the queues to allocate the message.
func (pmm *PeerMessageManager) AllocateAndBuildMessage(p peer.ID, blkSize uint64, buildMessageFn func(*gsmsg.Builder), notifees []notifications.Notifee) {
38
	pq := pmm.GetProcess(p).(PeerQueue)
39
	pq.AllocateAndBuildMessage(blkSize, buildMessageFn, notifees)
40
}