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

import (
	"context"
5 6
	"errors"
	"fmt"
7 8 9
	"sync"
	"time"

10
	blocks "github.com/ipfs/go-block-format"
Hannah Howard's avatar
Hannah Howard committed
11 12
	logging "github.com/ipfs/go-log"
	"github.com/libp2p/go-libp2p-core/peer"
13

14 15
	gsmsg "github.com/ipfs/go-graphsync/message"
	gsnet "github.com/ipfs/go-graphsync/network"
16
	"github.com/ipfs/go-graphsync/notifications"
17 18 19 20 21 22
)

var log = logging.Logger("graphsync")

const maxRetries = 10

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
type EventName uint64

const (
	Queued EventName = iota
	Sent
	Error
)

type Event struct {
	Name EventName
	Err  error
}

type Topic uint64

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
// MessageNetwork is any network that can connect peers and generate a message
// sender.
type MessageNetwork interface {
	NewMessageSender(context.Context, peer.ID) (gsnet.MessageSender, error)
	ConnectTo(context.Context, peer.ID) error
}

// MessageQueue implements queue of want messages to send to peers.
type MessageQueue struct {
	p       peer.ID
	network MessageNetwork
	ctx     context.Context

	outgoingWork chan struct{}
	done         chan struct{}

	// internal do not touch outside go routines
55
	nextMessage        gsmsg.GraphSyncMessage
56
	nextMessageTopic   Topic
57
	nextMessageLk      sync.RWMutex
58
	nextAvailableTopic Topic
59 60
	processedNotifiers []chan struct{}
	sender             gsnet.MessageSender
61
	eventPublisher     notifications.Publisher
62 63 64 65 66
}

// New creats a new MessageQueue.
func New(ctx context.Context, p peer.ID, network MessageNetwork) *MessageQueue {
	return &MessageQueue{
67 68 69 70 71 72
		ctx:            ctx,
		network:        network,
		p:              p,
		outgoingWork:   make(chan struct{}, 1),
		done:           make(chan struct{}),
		eventPublisher: notifications.NewPublisher(),
73 74 75 76
	}
}

// AddRequest adds an outgoing request to the message queue.
77
func (mq *MessageQueue) AddRequest(graphSyncRequest gsmsg.GraphSyncRequest, notifees ...notifications.Notifee) {
78 79

	if mq.mutateNextMessage(func(nextMessage gsmsg.GraphSyncMessage) {
80
		nextMessage.AddRequest(graphSyncRequest)
81
	}, notifees) {
82 83 84 85
		mq.signalWork()
	}
}

86 87
// AddResponses adds the given blocks and responses to the next message and
// returns a channel that sends a notification when sending initiates. If ignored by the consumer
88
// sending will not block.
89
func (mq *MessageQueue) AddResponses(responses []gsmsg.GraphSyncResponse, blks []blocks.Block, notifees ...notifications.Notifee) {
90
	if mq.mutateNextMessage(func(nextMessage gsmsg.GraphSyncMessage) {
91 92 93
		for _, response := range responses {
			nextMessage.AddResponse(response)
		}
94 95 96
		for _, block := range blks {
			nextMessage.AddBlock(block)
		}
97
	}, notifees) {
98 99 100 101
		mq.signalWork()
	}
}

102 103 104 105 106 107 108 109 110 111 112 113
// Startup starts the processing of messages, and creates an initial message
// based on the given initial wantlist.
func (mq *MessageQueue) Startup() {
	go mq.runQueue()
}

// Shutdown stops the processing of messages for a message queue.
func (mq *MessageQueue) Shutdown() {
	close(mq.done)
}

func (mq *MessageQueue) runQueue() {
114 115
	defer mq.eventPublisher.Shutdown()
	mq.eventPublisher.Startup()
116 117 118 119 120
	for {
		select {
		case <-mq.outgoingWork:
			mq.sendMessage()
		case <-mq.done:
121 122 123 124 125 126 127 128
			select {
			case <-mq.outgoingWork:
				message, topic := mq.extractOutgoingMessage()
				if message != nil || !message.Empty() {
					mq.eventPublisher.Publish(topic, Event{Name: Error, Err: fmt.Errorf("message queue shutdown")})
				}
			default:
			}
129 130 131 132 133 134
			if mq.sender != nil {
				mq.sender.Close()
			}
			return
		case <-mq.ctx.Done():
			if mq.sender != nil {
Hannah Howard's avatar
Hannah Howard committed
135
				_ = mq.sender.Reset()
136 137 138 139 140 141
			}
			return
		}
	}
}

142
func (mq *MessageQueue) mutateNextMessage(mutator func(gsmsg.GraphSyncMessage), notifees []notifications.Notifee) bool {
143 144 145 146
	mq.nextMessageLk.Lock()
	defer mq.nextMessageLk.Unlock()
	if mq.nextMessage == nil {
		mq.nextMessage = gsmsg.New()
147 148
		mq.nextMessageTopic = mq.nextAvailableTopic
		mq.nextAvailableTopic++
149 150
	}
	mutator(mq.nextMessage)
151
	for _, notifee := range notifees {
152
		notifications.SubscribeWithData(mq.eventPublisher, mq.nextMessageTopic, notifee)
153
	}
154 155 156 157 158 159 160 161 162 163
	return !mq.nextMessage.Empty()
}

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

164
func (mq *MessageQueue) extractOutgoingMessage() (gsmsg.GraphSyncMessage, Topic) {
165 166 167
	// grab outgoing message
	mq.nextMessageLk.Lock()
	message := mq.nextMessage
168
	topic := mq.nextMessageTopic
169 170
	mq.nextMessage = nil
	mq.nextMessageLk.Unlock()
171
	return message, topic
172 173 174
}

func (mq *MessageQueue) sendMessage() {
175
	message, topic := mq.extractOutgoingMessage()
176 177 178
	if message == nil || message.Empty() {
		return
	}
179 180
	mq.eventPublisher.Publish(topic, Event{Name: Queued, Err: nil})
	defer mq.eventPublisher.Close(topic)
181 182 183 184 185

	err := mq.initializeSender()
	if err != nil {
		log.Infof("cant open message sender to peer %s: %s", mq.p, err)
		// TODO: cant connect, what now?
186
		mq.eventPublisher.Publish(topic, Event{Name: Error, Err: fmt.Errorf("cant open message sender to peer %s: %w", mq.p, err)})
187 188 189 190
		return
	}

	for i := 0; i < maxRetries; i++ { // try to send this message until we fail.
191
		if mq.attemptSendAndRecovery(message, topic) {
192 193 194
			return
		}
	}
195
	mq.eventPublisher.Publish(topic, Event{Name: Error, Err: fmt.Errorf("expended retries on SendMsg(%s)", mq.p)})
196 197 198 199 200 201 202 203 204 205 206 207 208 209
}

func (mq *MessageQueue) initializeSender() error {
	if mq.sender != nil {
		return nil
	}
	nsender, err := openSender(mq.ctx, mq.network, mq.p)
	if err != nil {
		return err
	}
	mq.sender = nsender
	return nil
}

210
func (mq *MessageQueue) attemptSendAndRecovery(message gsmsg.GraphSyncMessage, topic Topic) bool {
211 212
	err := mq.sender.SendMsg(mq.ctx, message)
	if err == nil {
213
		mq.eventPublisher.Publish(topic, Event{Name: Sent})
214 215 216 217
		return true
	}

	log.Infof("graphsync send error: %s", err)
Hannah Howard's avatar
Hannah Howard committed
218
	_ = mq.sender.Reset()
219 220 221
	mq.sender = nil

	select {
222
	case <-mq.done:
223
		mq.eventPublisher.Publish(topic, Event{Name: Error, Err: errors.New("queue shutdown")})
224
		return true
225
	case <-mq.ctx.Done():
226
		mq.eventPublisher.Publish(topic, Event{Name: Error, Err: errors.New("context cancelled")})
227 228 229
		return true
	case <-time.After(time.Millisecond * 100):
		// wait 100ms in case disconnect notifications are still propogating
Hannah Howard's avatar
Hannah Howard committed
230
		log.Warn("SendMsg errored but neither 'done' nor context.Done() were set")
231 232 233 234 235 236 237 238 239
	}

	err = mq.initializeSender()
	if err != nil {
		log.Infof("couldnt open sender again after SendMsg(%s) failed: %s", mq.p, err)
		// TODO(why): what do we do now?
		// I think the *right* answer is to probably put the message we're
		// trying to send back, and then return to waiting for new work or
		// a disconnect.
240
		mq.eventPublisher.Publish(topic, Event{Name: Error, Err: fmt.Errorf("couldnt open sender again after SendMsg(%s) failed: %w", mq.p, err)})
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
		return true
	}

	return false
}

func openSender(ctx context.Context, network MessageNetwork, p peer.ID) (gsnet.MessageSender, error) {
	// allow ten minutes for connections this includes looking them up in the
	// dht dialing them, and handshaking
	conctx, cancel := context.WithTimeout(ctx, time.Minute*10)
	defer cancel()

	err := network.ConnectTo(conctx, p)
	if err != nil {
		return nil, err
	}

	nsender, err := network.NewMessageSender(ctx, p)
	if err != nil {
		return nil, err
	}

	return nsender, nil
}