peerresponsesender.go 6.3 KB
Newer Older
1 2 3 4 5 6
package peerresponsemanager

import (
	"context"
	"sync"

7
	"github.com/ipfs/go-graphsync"
8 9
	"github.com/ipfs/go-graphsync/peermanager"

10
	cidlink "github.com/ipld/go-ipld-prime/linking/cid"
11 12 13 14 15 16

	"github.com/ipfs/go-graphsync/ipldbridge"

	logging "github.com/ipfs/go-log"
	"github.com/ipld/go-ipld-prime"

17
	blocks "github.com/ipfs/go-block-format"
18
	"github.com/ipfs/go-graphsync/linktracker"
19 20
	gsmsg "github.com/ipfs/go-graphsync/message"
	"github.com/ipfs/go-graphsync/responsemanager/responsebuilder"
21
	"github.com/libp2p/go-libp2p-core/peer"
22 23
)

24 25 26 27 28
const (
	// max block size is the maximum size for batching blocks in a single payload
	maxBlockSize = 512 * 1024
)

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
var log = logging.Logger("graphsync")

// PeerMessageHandler is an interface that can send a response for a given peer across
// the network.
type PeerMessageHandler interface {
	SendResponse(peer.ID, []gsmsg.GraphSyncResponse, []blocks.Block) <-chan struct{}
}

type peerResponseSender struct {
	p            peer.ID
	ctx          context.Context
	cancel       context.CancelFunc
	peerHandler  PeerMessageHandler
	ipldBridge   ipldbridge.IPLDBridge
	outgoingWork chan struct{}

45 46 47 48
	linkTrackerLk      sync.RWMutex
	linkTracker        *linktracker.LinkTracker
	responseBuildersLk sync.RWMutex
	responseBuilders   []*responsebuilder.ResponseBuilder
49 50 51 52 53 54 55
}

// PeerResponseSender handles batching, deduping, and sending responses for
// a given peer across multiple requests.
type PeerResponseSender interface {
	peermanager.PeerProcess
	SendResponse(
56
		requestID graphsync.RequestID,
57 58 59
		link ipld.Link,
		data []byte,
	)
60
	SendExtensionData(graphsync.RequestID, graphsync.ExtensionData)
61 62
	FinishRequest(requestID graphsync.RequestID)
	FinishWithError(requestID graphsync.RequestID, status graphsync.ResponseStatusCode)
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
}

// NewResponseSender generates a new PeerResponseSender for the given context, peer ID,
// using the given peer message handler and bridge to IPLD.
func NewResponseSender(ctx context.Context, p peer.ID, peerHandler PeerMessageHandler, ipldBridge ipldbridge.IPLDBridge) PeerResponseSender {
	ctx, cancel := context.WithCancel(ctx)
	return &peerResponseSender{
		p:            p,
		ctx:          ctx,
		cancel:       cancel,
		peerHandler:  peerHandler,
		ipldBridge:   ipldBridge,
		outgoingWork: make(chan struct{}, 1),
		linkTracker:  linktracker.New(),
	}
}

// Startup initiates message sending for a peer
func (prm *peerResponseSender) Startup() {
	go prm.run()
}

// Shutdown stops sending messages for a peer
func (prm *peerResponseSender) Shutdown() {
	prm.cancel()
}

90 91 92 93 94 95 96 97
func (prm *peerResponseSender) SendExtensionData(requestID graphsync.RequestID, extension graphsync.ExtensionData) {
	if prm.buildResponse(0, func(responseBuilder *responsebuilder.ResponseBuilder) {
		responseBuilder.AddExtensionData(requestID, extension)
	}) {
		prm.signalWork()
	}
}

98 99 100 101
// SendResponse sends a given link for a given
// requestID across the wire, as well as its corresponding
// block if the block is present and has not already been sent
func (prm *peerResponseSender) SendResponse(
102
	requestID graphsync.RequestID,
103 104 105 106 107
	link ipld.Link,
	data []byte,
) {
	hasBlock := data != nil
	prm.linkTrackerLk.Lock()
108
	sendBlock := hasBlock && prm.linkTracker.BlockRefCount(link) == 0
109 110 111 112
	blkSize := len(data)
	if !sendBlock {
		blkSize = 0
	}
113 114 115
	prm.linkTracker.RecordLinkTraversal(requestID, link, hasBlock)
	prm.linkTrackerLk.Unlock()

116
	if prm.buildResponse(blkSize, func(responseBuilder *responsebuilder.ResponseBuilder) {
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
		if sendBlock {
			cidLink := link.(cidlink.Link)
			block, err := blocks.NewBlockWithCid(data, cidLink.Cid)
			if err != nil {
				log.Errorf("Data did not match cid when sending link for %s", cidLink.String())
			}
			responseBuilder.AddBlock(block)
		}
		responseBuilder.AddLink(requestID, link, hasBlock)
	}) {
		prm.signalWork()
	}
}

// FinishRequest marks the given requestID as having sent all responses
132
func (prm *peerResponseSender) FinishRequest(requestID graphsync.RequestID) {
133 134 135
	prm.linkTrackerLk.Lock()
	isComplete := prm.linkTracker.FinishRequest(requestID)
	prm.linkTrackerLk.Unlock()
136
	var status graphsync.ResponseStatusCode
137
	if isComplete {
138
		status = graphsync.RequestCompletedFull
139
	} else {
140
		status = graphsync.RequestCompletedPartial
141 142 143 144 145
	}
	prm.finish(requestID, status)
}

// FinishWithError marks the given requestID as having terminated with an error
146
func (prm *peerResponseSender) FinishWithError(requestID graphsync.RequestID, status graphsync.ResponseStatusCode) {
147 148 149 150 151 152
	prm.linkTrackerLk.Lock()
	prm.linkTracker.FinishRequest(requestID)
	prm.linkTrackerLk.Unlock()

	prm.finish(requestID, status)
}
153

154
func (prm *peerResponseSender) finish(requestID graphsync.RequestID, status graphsync.ResponseStatusCode) {
155
	if prm.buildResponse(0, func(responseBuilder *responsebuilder.ResponseBuilder) {
156
		responseBuilder.AddCompletedRequest(requestID, status)
157 158 159 160
	}) {
		prm.signalWork()
	}
}
161 162 163 164 165 166 167 168 169 170 171 172 173 174
func (prm *peerResponseSender) buildResponse(blkSize int, buildResponseFn func(*responsebuilder.ResponseBuilder)) bool {
	prm.responseBuildersLk.Lock()
	defer prm.responseBuildersLk.Unlock()
	if shouldBeginNewResponse(prm.responseBuilders, blkSize) {
		prm.responseBuilders = append(prm.responseBuilders, responsebuilder.New())
	}
	responseBuilder := prm.responseBuilders[len(prm.responseBuilders)-1]
	buildResponseFn(responseBuilder)
	return !responseBuilder.Empty()
}

func shouldBeginNewResponse(responseBuilders []*responsebuilder.ResponseBuilder, blkSize int) bool {
	if len(responseBuilders) == 0 {
		return true
175
	}
176 177 178 179
	if blkSize == 0 {
		return false
	}
	return responseBuilders[len(responseBuilders)-1].BlockSize()+blkSize > maxBlockSize
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
}

func (prm *peerResponseSender) signalWork() {
	select {
	case prm.outgoingWork <- struct{}{}:
	default:
	}
}

func (prm *peerResponseSender) run() {
	for {
		select {
		case <-prm.ctx.Done():
			return
		case <-prm.outgoingWork:
195
			prm.sendResponseMessages()
196 197 198 199
		}
	}
}

200 201 202 203 204
func (prm *peerResponseSender) sendResponseMessages() {
	prm.responseBuildersLk.Lock()
	builders := prm.responseBuilders
	prm.responseBuilders = nil
	prm.responseBuildersLk.Unlock()
205

206 207 208 209 210 211 212 213
	for _, builder := range builders {
		if builder.Empty() {
			continue
		}
		responses, blks, err := builder.Build(prm.ipldBridge)
		if err != nil {
			log.Errorf("Unable to assemble GraphSync response: %s", err.Error())
		}
214

215
		done := prm.peerHandler.SendResponse(prm.p, responses, blks)
216

217 218 219 220 221
		// wait for message to be processed
		select {
		case <-done:
		case <-prm.ctx.Done():
		}
222
	}
223

224
}