messagequeue.go 17.5 KB
Newer Older
1 2 3 4
package messagequeue

import (
	"context"
dirkmc's avatar
dirkmc committed
5
	"math"
6
	"sync"
7 8 9
	"time"

	bsmsg "github.com/ipfs/go-bitswap/message"
dirkmc's avatar
dirkmc committed
10
	pb "github.com/ipfs/go-bitswap/message/pb"
11
	bsnet "github.com/ipfs/go-bitswap/network"
12
	"github.com/ipfs/go-bitswap/wantlist"
dirkmc's avatar
dirkmc committed
13 14
	bswl "github.com/ipfs/go-bitswap/wantlist"
	cid "github.com/ipfs/go-cid"
15
	logging "github.com/ipfs/go-log"
Raúl Kripalani's avatar
Raúl Kripalani committed
16
	peer "github.com/libp2p/go-libp2p-core/peer"
17
	"github.com/libp2p/go-libp2p/p2p/protocol/ping"
Dirk McCormick's avatar
Dirk McCormick committed
18
	"go.uber.org/zap"
19 20 21
)

var log = logging.Logger("bitswap")
Dirk McCormick's avatar
Dirk McCormick committed
22
var sflog = log.Desugar()
23

24 25
const (
	defaultRebroadcastInterval = 30 * time.Second
dirkmc's avatar
dirkmc committed
26 27
	// maxRetries is the number of times to attempt to send a message before
	// giving up
28 29
	maxRetries  = 3
	sendTimeout = 30 * time.Second
dirkmc's avatar
dirkmc committed
30 31 32 33 34 35 36 37 38
	// maxMessageSize is the maximum message size in bytes
	maxMessageSize = 1024 * 1024 * 2
	// sendErrorBackoff is the time to wait before retrying to connect after
	// an error when trying to send a message
	sendErrorBackoff = 100 * time.Millisecond
	// maxPriority is the max priority as defined by the bitswap protocol
	maxPriority = math.MaxInt32
	// sendMessageDebounce is the debounce duration when calling sendMessage()
	sendMessageDebounce = time.Millisecond
39 40
	// when we reach sendMessageCutoff wants/cancels, we'll send the message immediately.
	sendMessageCutoff = 256
Steven Allen's avatar
Steven Allen committed
41 42
	// when we debounce for more than sendMessageMaxDelay, we'll send the
	// message immediately.
43
	sendMessageMaxDelay = 20 * time.Millisecond
44
)
45

46
// MessageNetwork is any network that can connect peers and generate a message
47
// sender.
48 49
type MessageNetwork interface {
	ConnectTo(context.Context, peer.ID) error
50
	NewMessageSender(context.Context, peer.ID, *bsnet.MessageSenderOpts) (bsnet.MessageSender, error)
51 52
	Latency(peer.ID) time.Duration
	Ping(context.Context, peer.ID) ping.Result
53
	Self() peer.ID
54 55
}

56
// MessageQueue implements queue of want messages to send to peers.
57
type MessageQueue struct {
dirkmc's avatar
dirkmc committed
58
	ctx              context.Context
59
	shutdown         func()
dirkmc's avatar
dirkmc committed
60 61
	p                peer.ID
	network          MessageNetwork
62
	dhTimeoutMgr     DontHaveTimeoutManager
dirkmc's avatar
dirkmc committed
63 64 65
	maxMessageSize   int
	sendErrorBackoff time.Duration

Steven Allen's avatar
Steven Allen committed
66
	outgoingWork chan time.Time
dirkmc's avatar
dirkmc committed
67 68 69 70 71 72

	// Take lock whenever any of these variables are modified
	wllock    sync.Mutex
	bcstWants recallWantlist
	peerWants recallWantlist
	cancels   *cid.Set
73
	priority  int32
dirkmc's avatar
dirkmc committed
74 75

	// Dont touch any of these variables outside of run loop
76 77 78 79
	sender                bsnet.MessageSender
	rebroadcastIntervalLk sync.RWMutex
	rebroadcastInterval   time.Duration
	rebroadcastTimer      *time.Timer
80 81 82
	// For performance reasons we just clear out the fields of the message
	// instead of creating a new one every time.
	msg bsmsg.BitSwapMessage
83 84
}

85
// recallWantlist keeps a list of pending wants and a list of sent wants
dirkmc's avatar
dirkmc committed
86 87 88
type recallWantlist struct {
	// The list of wants that have not yet been sent
	pending *bswl.Wantlist
89 90
	// The list of wants that have been sent
	sent *bswl.Wantlist
dirkmc's avatar
dirkmc committed
91 92 93 94
}

func newRecallWantList() recallWantlist {
	return recallWantlist{
95 96
		pending: bswl.New(),
		sent:    bswl.New(),
dirkmc's avatar
dirkmc committed
97 98 99
	}
}

100
// Add want to the pending list
101
func (r *recallWantlist) Add(c cid.Cid, priority int32, wtype pb.Message_Wantlist_WantType) {
dirkmc's avatar
dirkmc committed
102 103 104
	r.pending.Add(c, priority, wtype)
}

105
// Remove wants from both the pending list and the list of sent wants
dirkmc's avatar
dirkmc committed
106
func (r *recallWantlist) Remove(c cid.Cid) {
107
	r.sent.Remove(c)
dirkmc's avatar
dirkmc committed
108 109 110
	r.pending.Remove(c)
}

111
// Remove wants by type from both the pending list and the list of sent wants
dirkmc's avatar
dirkmc committed
112
func (r *recallWantlist) RemoveType(c cid.Cid, wtype pb.Message_Wantlist_WantType) {
113
	r.sent.RemoveType(c, wtype)
dirkmc's avatar
dirkmc committed
114 115 116
	r.pending.RemoveType(c, wtype)
}

117 118
// MarkSent moves the want from the pending to the sent list
func (r *recallWantlist) MarkSent(e wantlist.Entry) {
119 120 121 122
	r.pending.RemoveType(e.Cid, e.WantType)
	r.sent.Add(e.Cid, e.Priority, e.WantType)
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
type peerConn struct {
	p       peer.ID
	network MessageNetwork
}

func newPeerConnection(p peer.ID, network MessageNetwork) *peerConn {
	return &peerConn{p, network}
}

func (pc *peerConn) Ping(ctx context.Context) ping.Result {
	return pc.network.Ping(ctx, pc.p)
}

func (pc *peerConn) Latency() time.Duration {
	return pc.network.Latency(pc.p)
}

// Fires when a timeout occurs waiting for a response from a peer running an
// older version of Bitswap that doesn't support DONT_HAVE messages.
type OnDontHaveTimeout func(peer.ID, []cid.Cid)

// DontHaveTimeoutManager pings a peer to estimate latency so it can set a reasonable
// upper bound on when to consider a DONT_HAVE request as timed out (when connected to
// a peer that doesn't support DONT_HAVE messages)
type DontHaveTimeoutManager interface {
	// Start the manager (idempotent)
	Start()
	// Shutdown the manager (Shutdown is final, manager cannot be restarted)
	Shutdown()
	// AddPending adds the wants as pending a response. If the are not
	// cancelled before the timeout, the OnDontHaveTimeout method will be called.
	AddPending([]cid.Cid)
	// CancelPending removes the wants
	CancelPending([]cid.Cid)
}

// New creates a new MessageQueue.
func New(ctx context.Context, p peer.ID, network MessageNetwork, onDontHaveTimeout OnDontHaveTimeout) *MessageQueue {
	onTimeout := func(ks []cid.Cid) {
Dirk McCormick's avatar
Dirk McCormick committed
162
		log.Infow("Bitswap: timeout waiting for blocks", "cids", ks, "peer", p)
163 164
		onDontHaveTimeout(p, ks)
	}
165
	dhTimeoutMgr := newDontHaveTimeoutMgr(newPeerConnection(p, network), onTimeout)
166
	return newMessageQueue(ctx, p, network, maxMessageSize, sendErrorBackoff, dhTimeoutMgr)
dirkmc's avatar
dirkmc committed
167 168 169
}

// This constructor is used by the tests
170 171 172
func newMessageQueue(ctx context.Context, p peer.ID, network MessageNetwork,
	maxMsgSize int, sendErrorBackoff time.Duration, dhTimeoutMgr DontHaveTimeoutManager) *MessageQueue {

173
	ctx, cancel := context.WithCancel(ctx)
dirkmc's avatar
dirkmc committed
174
	mq := &MessageQueue{
175
		ctx:                 ctx,
176
		shutdown:            cancel,
177
		p:                   p,
dirkmc's avatar
dirkmc committed
178
		network:             network,
179
		dhTimeoutMgr:        dhTimeoutMgr,
dirkmc's avatar
dirkmc committed
180 181 182 183
		maxMessageSize:      maxMsgSize,
		bcstWants:           newRecallWantList(),
		peerWants:           newRecallWantList(),
		cancels:             cid.NewSet(),
Steven Allen's avatar
Steven Allen committed
184
		outgoingWork:        make(chan time.Time, 1),
185
		rebroadcastInterval: defaultRebroadcastInterval,
dirkmc's avatar
dirkmc committed
186 187
		sendErrorBackoff:    sendErrorBackoff,
		priority:            maxPriority,
188 189 190
		// For performance reasons we just clear out the fields of the message
		// after using it, instead of creating a new one every time.
		msg: bsmsg.New(false),
191
	}
dirkmc's avatar
dirkmc committed
192 193

	return mq
194 195
}

dirkmc's avatar
dirkmc committed
196 197 198
// Add want-haves that are part of a broadcast to all connected peers
func (mq *MessageQueue) AddBroadcastWantHaves(wantHaves []cid.Cid) {
	if len(wantHaves) == 0 {
199 200
		return
	}
dirkmc's avatar
dirkmc committed
201 202 203 204 205 206 207 208 209 210 211

	mq.wllock.Lock()
	defer mq.wllock.Unlock()

	for _, c := range wantHaves {
		mq.bcstWants.Add(c, mq.priority, pb.Message_Wantlist_Have)
		mq.priority--

		// We're adding a want-have for the cid, so clear any pending cancel
		// for the cid
		mq.cancels.Remove(c)
212
	}
dirkmc's avatar
dirkmc committed
213 214 215

	// Schedule a message send
	mq.signalWorkReady()
216 217
}

dirkmc's avatar
dirkmc committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
// Add want-haves and want-blocks for the peer for this message queue.
func (mq *MessageQueue) AddWants(wantBlocks []cid.Cid, wantHaves []cid.Cid) {
	if len(wantBlocks) == 0 && len(wantHaves) == 0 {
		return
	}

	mq.wllock.Lock()
	defer mq.wllock.Unlock()

	for _, c := range wantHaves {
		mq.peerWants.Add(c, mq.priority, pb.Message_Wantlist_Have)
		mq.priority--

		// We're adding a want-have for the cid, so clear any pending cancel
		// for the cid
		mq.cancels.Remove(c)
	}
	for _, c := range wantBlocks {
		mq.peerWants.Add(c, mq.priority, pb.Message_Wantlist_Block)
		mq.priority--

		// We're adding a want-block for the cid, so clear any pending cancel
		// for the cid
		mq.cancels.Remove(c)
	}

	// Schedule a message send
	mq.signalWorkReady()
}

// Add cancel messages for the given keys.
func (mq *MessageQueue) AddCancels(cancelKs []cid.Cid) {
	if len(cancelKs) == 0 {
		return
	}

254 255 256
	// Cancel any outstanding DONT_HAVE timers
	mq.dhTimeoutMgr.CancelPending(cancelKs)

dirkmc's avatar
dirkmc committed
257 258 259
	mq.wllock.Lock()
	defer mq.wllock.Unlock()

260 261
	workReady := false

262
	// Remove keys from broadcast and peer wants, and add to cancels
dirkmc's avatar
dirkmc committed
263
	for _, c := range cancelKs {
264 265 266 267 268
		// Check if a want for the key was sent
		_, wasSentBcst := mq.bcstWants.sent.Contains(c)
		_, wasSentPeer := mq.peerWants.sent.Contains(c)

		// Remove the want from tracking wantlists
dirkmc's avatar
dirkmc committed
269 270
		mq.bcstWants.Remove(c)
		mq.peerWants.Remove(c)
271 272 273 274 275 276

		// Only send a cancel if a want was sent
		if wasSentBcst || wasSentPeer {
			mq.cancels.Add(c)
			workReady = true
		}
dirkmc's avatar
dirkmc committed
277 278 279
	}

	// Schedule a message send
280 281 282
	if workReady {
		mq.signalWorkReady()
	}
283 284 285 286 287 288
}

// SetRebroadcastInterval sets a new interval on which to rebroadcast the full wantlist
func (mq *MessageQueue) SetRebroadcastInterval(delay time.Duration) {
	mq.rebroadcastIntervalLk.Lock()
	mq.rebroadcastInterval = delay
289 290 291
	if mq.rebroadcastTimer != nil {
		mq.rebroadcastTimer.Reset(delay)
	}
292
	mq.rebroadcastIntervalLk.Unlock()
293
}
294

dirkmc's avatar
dirkmc committed
295
// Startup starts the processing of messages and rebroadcasting.
296
func (mq *MessageQueue) Startup() {
297 298 299
	mq.rebroadcastIntervalLk.RLock()
	mq.rebroadcastTimer = time.NewTimer(mq.rebroadcastInterval)
	mq.rebroadcastIntervalLk.RUnlock()
300
	go mq.runQueue()
301 302
}

303
// Shutdown stops the processing of messages for a message queue.
304
func (mq *MessageQueue) Shutdown() {
305
	mq.shutdown()
306
}
307

308 309 310
func (mq *MessageQueue) onShutdown() {
	// Shut down the DONT_HAVE timeout manager
	mq.dhTimeoutMgr.Shutdown()
311 312 313 314 315

	// Reset the streamMessageSender
	if mq.sender != nil {
		_ = mq.sender.Reset()
	}
316 317
}

318
func (mq *MessageQueue) runQueue() {
319 320
	defer mq.onShutdown()

Steven Allen's avatar
Steven Allen committed
321 322 323
	// Create a timer for debouncing scheduled work.
	scheduleWork := time.NewTimer(0)
	if !scheduleWork.Stop() {
324 325
		// Need to drain the timer if Stop() returns false
		// See: https://golang.org/pkg/time/#Timer.Stop
Steven Allen's avatar
Steven Allen committed
326 327 328 329
		<-scheduleWork.C
	}

	var workScheduled time.Time
330 331
	for {
		select {
332 333
		case <-mq.rebroadcastTimer.C:
			mq.rebroadcastWantlist()
Steven Allen's avatar
Steven Allen committed
334 335 336 337 338 339 340 341
		case when := <-mq.outgoingWork:
			// If we have work scheduled, cancel the timer. If we
			// don't, record when the work was scheduled.
			// We send the time on the channel so we accurately
			// track delay.
			if workScheduled.IsZero() {
				workScheduled = when
			} else if !scheduleWork.Stop() {
342
				// Need to drain the timer if Stop() returns false
Steven Allen's avatar
Steven Allen committed
343 344 345 346 347
				<-scheduleWork.C
			}

			// If we have too many updates and/or we've waited too
			// long, send immediately.
348
			if mq.pendingWorkCount() > sendMessageCutoff ||
Steven Allen's avatar
Steven Allen committed
349 350 351 352 353 354 355 356 357 358 359
				time.Since(workScheduled) >= sendMessageMaxDelay {
				mq.sendIfReady()
				workScheduled = time.Time{}
			} else {
				// Otherwise, extend the timer.
				scheduleWork.Reset(sendMessageDebounce)
			}
		case <-scheduleWork.C:
			// We have work scheduled and haven't seen any updates
			// in sendMessageDebounce. Send immediately.
			workScheduled = time.Time{}
dirkmc's avatar
dirkmc committed
360
			mq.sendIfReady()
361
		case <-mq.ctx.Done():
362 363 364 365 366
			return
		}
	}
}

dirkmc's avatar
dirkmc committed
367
// Periodically resend the list of wants to the peer
368 369 370 371 372
func (mq *MessageQueue) rebroadcastWantlist() {
	mq.rebroadcastIntervalLk.RLock()
	mq.rebroadcastTimer.Reset(mq.rebroadcastInterval)
	mq.rebroadcastIntervalLk.RUnlock()

dirkmc's avatar
dirkmc committed
373 374 375 376 377
	// If some wants were transferred from the rebroadcast list
	if mq.transferRebroadcastWants() {
		// Send them out
		mq.sendMessage()
	}
378 379
}

dirkmc's avatar
dirkmc committed
380 381 382 383
// Transfer wants from the rebroadcast lists into the pending lists.
func (mq *MessageQueue) transferRebroadcastWants() bool {
	mq.wllock.Lock()
	defer mq.wllock.Unlock()
384

dirkmc's avatar
dirkmc committed
385
	// Check if there are any wants to rebroadcast
386
	if mq.bcstWants.sent.Len() == 0 && mq.peerWants.sent.Len() == 0 {
dirkmc's avatar
dirkmc committed
387
		return false
388
	}
dirkmc's avatar
dirkmc committed
389

390 391 392
	// Copy sent wants into pending wants lists
	mq.bcstWants.pending.Absorb(mq.bcstWants.sent)
	mq.peerWants.pending.Absorb(mq.peerWants.sent)
dirkmc's avatar
dirkmc committed
393 394

	return true
395 396
}

Steven Allen's avatar
Steven Allen committed
397
func (mq *MessageQueue) signalWorkReady() {
dirkmc's avatar
dirkmc committed
398
	select {
Steven Allen's avatar
Steven Allen committed
399
	case mq.outgoingWork <- time.Now():
dirkmc's avatar
dirkmc committed
400 401
	default:
	}
402 403
}

dirkmc's avatar
dirkmc committed
404 405 406
func (mq *MessageQueue) sendIfReady() {
	if mq.hasPendingWork() {
		mq.sendMessage()
407
	}
dirkmc's avatar
dirkmc committed
408
}
409

dirkmc's avatar
dirkmc committed
410
func (mq *MessageQueue) sendMessage() {
411
	sender, err := mq.initializeSender()
412
	if err != nil {
413 414 415
		// If we fail to initialize the sender, the networking layer will
		// emit a Disconnect event and the MessageQueue will get cleaned up
		log.Infof("Could not open message sender to peer %s: %s", mq.p, err)
416
		mq.Shutdown()
417
		return
418 419
	}

420
	// Make sure the DONT_HAVE timeout manager has started
421 422
	// Note: Start is idempotent
	mq.dhTimeoutMgr.Start()
423

dirkmc's avatar
dirkmc committed
424
	// Convert want lists to a Bitswap Message
425
	message, onSent := mq.extractOutgoingMessage(mq.sender.SupportsHave())
426 427 428 429 430

	// After processing the message, clear out its fields to save memory
	defer mq.msg.Reset(false)

	if message.Empty() {
dirkmc's avatar
dirkmc committed
431 432 433
		return
	}

434 435
	wantlist := message.Wantlist()
	mq.logOutgoingMessage(wantlist)
dirkmc's avatar
dirkmc committed
436

437 438 439 440
	if err := sender.SendMsg(mq.ctx, message); err != nil {
		// If the message couldn't be sent, the networking layer will
		// emit a Disconnect event and the MessageQueue will get cleaned up
		log.Infof("Could not send message to peer %s: %s", mq.p, err)
441
		mq.Shutdown()
442 443
		return
	}
dirkmc's avatar
dirkmc committed
444

445 446
	// We were able to send successfully.
	onSent()
447

448 449
	// Set a timer to wait for responses
	mq.simulateDontHaveWithTimeout(wantlist)
dirkmc's avatar
dirkmc committed
450

451 452 453 454 455
	// If the message was too big and only a subset of wants could be
	// sent, schedule sending the rest of the wants in the next
	// iteration of the event loop.
	if mq.hasPendingWork() {
		mq.signalWorkReady()
456 457
	}
}
458

459 460 461 462
// If want-block times out, simulate a DONT_HAVE reponse.
// This is necessary when making requests to peers running an older version of
// Bitswap that doesn't support the DONT_HAVE response, and is also useful to
// mitigate getting blocked by a peer that takes a long time to respond.
463
func (mq *MessageQueue) simulateDontHaveWithTimeout(wantlist []bsmsg.Entry) {
464 465
	// Get the CID of each want-block that expects a DONT_HAVE response
	wants := make([]cid.Cid, 0, len(wantlist))
466 467 468

	mq.wllock.Lock()

469 470 471 472 473
	for _, entry := range wantlist {
		if entry.WantType == pb.Message_Wantlist_Block && entry.SendDontHave {
			// Unlikely, but just in case check that the block hasn't been
			// received in the interim
			c := entry.Cid
474
			if _, ok := mq.peerWants.sent.Contains(c); ok {
475 476 477 478 479 480 481 482 483 484 485
				wants = append(wants, c)
			}
		}
	}

	mq.wllock.Unlock()

	// Add wants to DONT_HAVE timeout manager
	mq.dhTimeoutMgr.AddPending(wants)
}

486
func (mq *MessageQueue) logOutgoingMessage(wantlist []bsmsg.Entry) {
Dirk McCormick's avatar
Dirk McCormick committed
487
	// Save some CPU cycles and allocations if log level is higher than debug
Steven Allen's avatar
Steven Allen committed
488
	if ce := sflog.Check(zap.DebugLevel, "sent message"); ce == nil {
Dirk McCormick's avatar
Dirk McCormick committed
489 490 491
		return
	}

Dirk McCormick's avatar
Dirk McCormick committed
492
	self := mq.network.Self()
493
	for _, e := range wantlist {
Dirk McCormick's avatar
Dirk McCormick committed
494 495
		if e.Cancel {
			if e.WantType == pb.Message_Wantlist_Have {
Steven Allen's avatar
Steven Allen committed
496 497 498 499 500 501
				log.Debugw("sent message",
					"type", "CANCEL_WANT_HAVE",
					"cid", e.Cid,
					"local", self,
					"to", mq.p,
				)
Dirk McCormick's avatar
Dirk McCormick committed
502
			} else {
Steven Allen's avatar
Steven Allen committed
503 504 505 506 507 508
				log.Debugw("sent message",
					"type", "CANCEL_WANT_BLOCK",
					"cid", e.Cid,
					"local", self,
					"to", mq.p,
				)
Dirk McCormick's avatar
Dirk McCormick committed
509 510 511
			}
		} else {
			if e.WantType == pb.Message_Wantlist_Have {
Steven Allen's avatar
Steven Allen committed
512 513 514 515 516 517
				log.Debugw("sent message",
					"type", "WANT_HAVE",
					"cid", e.Cid,
					"local", self,
					"to", mq.p,
				)
Dirk McCormick's avatar
Dirk McCormick committed
518
			} else {
Steven Allen's avatar
Steven Allen committed
519 520 521 522 523 524
				log.Debugw("sent message",
					"type", "WANT_BLOCK",
					"cid", e.Cid,
					"local", self,
					"to", mq.p,
				)
Dirk McCormick's avatar
Dirk McCormick committed
525 526 527 528
			}
		}
	}
}
dirkmc's avatar
dirkmc committed
529

530
// Whether there is work to be processed
dirkmc's avatar
dirkmc committed
531
func (mq *MessageQueue) hasPendingWork() bool {
Steven Allen's avatar
Steven Allen committed
532 533 534
	return mq.pendingWorkCount() > 0
}

535
// The amount of work that is waiting to be processed
Steven Allen's avatar
Steven Allen committed
536
func (mq *MessageQueue) pendingWorkCount() int {
dirkmc's avatar
dirkmc committed
537 538 539
	mq.wllock.Lock()
	defer mq.wllock.Unlock()

Steven Allen's avatar
Steven Allen committed
540
	return mq.bcstWants.pending.Len() + mq.peerWants.pending.Len() + mq.cancels.Len()
dirkmc's avatar
dirkmc committed
541 542
}

543
// Convert the lists of wants into a Bitswap message
544
func (mq *MessageQueue) extractOutgoingMessage(supportsHave bool) (bsmsg.BitSwapMessage, func()) {
dirkmc's avatar
dirkmc committed
545 546 547 548 549 550 551 552 553 554
	mq.wllock.Lock()
	defer mq.wllock.Unlock()

	// Get broadcast and regular wantlist entries
	bcstEntries := mq.bcstWants.pending.SortedEntries()
	peerEntries := mq.peerWants.pending.SortedEntries()

	// Size of the message so far
	msgSize := 0

555
	// Always prioritize cancels, then targeted, then broadcast.
dirkmc's avatar
dirkmc committed
556

557 558
	// Add each cancel to the message
	cancels := mq.cancels.Keys()
559 560 561 562
	for _, c := range cancels {
		if msgSize >= mq.maxMessageSize {
			break
		}
563 564 565 566 567
		msgSize += mq.msg.Cancel(c)

		// Clear the cancel - we make a best effort to let peers know about
		// cancels but won't save them to resend if there's a failure.
		mq.cancels.Remove(c)
dirkmc's avatar
dirkmc committed
568 569 570
	}

	// Add each regular want-have / want-block to the message
571 572 573 574 575 576
	peerSent := peerEntries[:0]
	for _, e := range peerEntries {
		if msgSize >= mq.maxMessageSize {
			break
		}

dirkmc's avatar
dirkmc committed
577 578 579 580 581
		// If the remote peer doesn't support HAVE / DONT_HAVE messages,
		// don't send want-haves (only send want-blocks)
		if !supportsHave && e.WantType == pb.Message_Wantlist_Have {
			mq.peerWants.RemoveType(e.Cid, pb.Message_Wantlist_Have)
		} else {
582
			msgSize += mq.msg.AddEntry(e.Cid, e.Priority, e.WantType, true)
583
			peerSent = append(peerSent, e)
dirkmc's avatar
dirkmc committed
584 585 586
		}
	}

587
	// Add each broadcast want-have to the message
588 589 590 591 592 593
	bcstSent := bcstEntries[:0]
	for _, e := range bcstEntries {
		if msgSize >= mq.maxMessageSize {
			break
		}

594 595
		// Broadcast wants are sent as want-have
		wantType := pb.Message_Wantlist_Have
dirkmc's avatar
dirkmc committed
596

597 598 599 600 601
		// If the remote peer doesn't support HAVE / DONT_HAVE messages,
		// send a want-block instead
		if !supportsHave {
			wantType = pb.Message_Wantlist_Block
		}
dirkmc's avatar
dirkmc committed
602

603
		msgSize += mq.msg.AddEntry(e.Cid, e.Priority, wantType, false)
604
		bcstSent = append(bcstSent, e)
dirkmc's avatar
dirkmc committed
605 606
	}

607
	// Called when the message has been successfully sent.
608
	onMessageSent := func() {
609 610
		mq.wllock.Lock()
		defer mq.wllock.Unlock()
dirkmc's avatar
dirkmc committed
611

612
		// Move the keys from pending to sent
613 614
		for _, e := range bcstSent {
			mq.bcstWants.MarkSent(e)
615
		}
616 617
		for _, e := range peerSent {
			mq.peerWants.MarkSent(e)
618 619 620 621 622 623
		}
	}

	return mq.msg, onMessageSent
}

624 625 626 627 628 629 630 631 632 633
func (mq *MessageQueue) initializeSender() (bsnet.MessageSender, error) {
	if mq.sender == nil {
		opts := &bsnet.MessageSenderOpts{
			MaxRetries:       maxRetries,
			SendTimeout:      sendTimeout,
			SendErrorBackoff: sendErrorBackoff,
		}
		nsender, err := mq.network.NewMessageSender(mq.ctx, mq.p, opts)
		if err != nil {
			return nil, err
634
		}
635

636
		mq.sender = nsender
637
	}
638
	return mq.sender, nil
639
}