message.go 9.35 KB
Newer Older
1 2 3 4
package message

import (
	"fmt"
5
	"io"
6 7

	ggio "github.com/gogo/protobuf/io"
8
	cid "github.com/ipfs/go-cid"
9 10
	pb "github.com/ipfs/go-graphsync/message/pb"
	gsselector "github.com/ipfs/go-graphsync/selector"
11
	inet "github.com/libp2p/go-libp2p-net"
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
)

// GraphSyncRequestID is a unique identifier for a GraphSync request.
type GraphSyncRequestID int32

// GraphSyncPriority a priority for a GraphSync request.
type GraphSyncPriority int32

// GraphSyncResponseStatusCode is a status returned for a GraphSync Request.
type GraphSyncResponseStatusCode int32

const (

	// GraphSync Response Status Codes

	// Informational Response Codes (partial)

	// RequestAcknowledged means the request was received and is being worked on.
30
	RequestAcknowledged = GraphSyncResponseStatusCode(10)
31 32
	// AdditionalPeers means additional peers were found that may be able
	// to satisfy the request and contained in the extra block of the response.
33
	AdditionalPeers = GraphSyncResponseStatusCode(11)
34
	// NotEnoughGas means fulfilling this request requires payment.
35
	NotEnoughGas = GraphSyncResponseStatusCode(12)
36 37
	// OtherProtocol means a different type of response than GraphSync is
	// contained in extra.
38
	OtherProtocol = GraphSyncResponseStatusCode(13)
39 40 41 42 43

	// Success Response Codes (request terminated)

	// RequestCompletedFull means the entire fulfillment of the GraphSync request
	// was sent back.
44
	RequestCompletedFull = GraphSyncResponseStatusCode(20)
45 46
	// RequestCompletedPartial means the response is completed, and part of the
	// GraphSync request was sent back, but not the complete request.
47
	RequestCompletedPartial = GraphSyncResponseStatusCode(21)
48 49 50 51

	// Error Response Codes (request terminated)

	// RequestRejected means the node did not accept the incoming request.
52
	RequestRejected = GraphSyncResponseStatusCode(30)
53 54
	// RequestFailedBusy means the node is too busy, try again later. Backoff may
	// be contained in extra.
55
	RequestFailedBusy = GraphSyncResponseStatusCode(31)
56 57
	// RequestFailedUnknown means the request failed for an unspecified reason. May
	// contain data about why in extra.
58
	RequestFailedUnknown = GraphSyncResponseStatusCode(32)
59
	// RequestFailedLegal means the request failed for legal reasons.
60
	RequestFailedLegal = GraphSyncResponseStatusCode(33)
61
	// RequestFailedContentNotFound means the respondent does not have the content.
62
	RequestFailedContentNotFound = GraphSyncResponseStatusCode(34)
63 64 65 66 67 68
)

// GraphSyncRequest is an interface for accessing data on request contained in a
// GraphSyncMessage.
type GraphSyncRequest interface {
	Selector() gsselector.Selector
69
	Root() cid.Cid
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
	Priority() GraphSyncPriority
	ID() GraphSyncRequestID
	IsCancel() bool
}

// GraphSyncResponse is an interface for accessing data on a response sent back
// in a GraphSyncMessage.
type GraphSyncResponse interface {
	RequestID() GraphSyncRequestID
	Status() GraphSyncResponseStatusCode
	Response() gsselector.SelectionResponse
}

// GraphSyncMessage is interface that can be serialized and deserialized to send
// over the GraphSync network
type GraphSyncMessage interface {
	Requests() []GraphSyncRequest

	Responses() []GraphSyncResponse

	AddRequest(id GraphSyncRequestID,
		selector gsselector.Selector,
92
		root cid.Cid,
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
		priority GraphSyncPriority)

	Cancel(id GraphSyncRequestID)

	AddResponse(
		requestID GraphSyncRequestID,
		status GraphSyncResponseStatusCode,
		response gsselector.SelectionResponse)

	Exportable

	Loggable() map[string]interface{}
}

// Exportable is an interface that can serialize to a protobuf
type Exportable interface {
	ToProto() *pb.Message
110
	ToNet(w io.Writer) error
111 112 113 114
}

type graphSyncRequest struct {
	selector gsselector.Selector
115
	root     cid.Cid
116 117 118 119 120 121 122 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
	priority GraphSyncPriority
	id       GraphSyncRequestID
	isCancel bool
}

type graphSyncResponse struct {
	requestID GraphSyncRequestID
	status    GraphSyncResponseStatusCode
	response  gsselector.SelectionResponse
}

type graphSyncMessage struct {
	requests  map[GraphSyncRequestID]*graphSyncRequest
	responses map[GraphSyncRequestID]*graphSyncResponse
}

// DecodeSelectorFunc is a function that can build a type that satisfies
// the Selector interface from a raw byte array.
type DecodeSelectorFunc func([]byte) gsselector.Selector

// DecodeSelectionResponseFunc is a function that can build a type that satisfies
// the SelectionResponse interface from a raw byte array.
type DecodeSelectionResponseFunc func([]byte) gsselector.SelectionResponse

// New initializes a new blank GraphSyncMessage
func New() GraphSyncMessage {
	return newMsg()
}

func newMsg() *graphSyncMessage {
	return &graphSyncMessage{
		requests:  make(map[GraphSyncRequestID]*graphSyncRequest),
		responses: make(map[GraphSyncRequestID]*graphSyncResponse),
	}
}

func newMessageFromProto(pbm pb.Message,
	decodeSelector DecodeSelectorFunc,
	decodeSelectionResponse DecodeSelectionResponseFunc) (GraphSyncMessage, error) {
	gsm := newMsg()
	for _, req := range pbm.Reqlist {
		selector := decodeSelector(req.Selector)
158 159 160 161
		root, err := cid.Cast([]byte(req.Root))
		if err != nil {
			return nil, fmt.Errorf("incorrectly formatted cid in request queery: %s", err)
		}
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
		gsm.addRequest(GraphSyncRequestID(req.Id), selector, root, GraphSyncPriority(req.Priority), req.Cancel)
	}

	for _, res := range pbm.Reslist {
		selectionResponse := decodeSelectionResponse(res.Data)
		gsm.AddResponse(GraphSyncRequestID(res.Id), GraphSyncResponseStatusCode(res.Status), selectionResponse)
	}

	return gsm, nil
}

func (gsm *graphSyncMessage) Requests() []GraphSyncRequest {
	requests := make([]GraphSyncRequest, 0, len(gsm.requests))
	for _, request := range gsm.requests {
		requests = append(requests, request)
	}
	return requests
}

func (gsm *graphSyncMessage) Responses() []GraphSyncResponse {
	responses := make([]GraphSyncResponse, 0, len(gsm.responses))
	for _, response := range gsm.responses {
		responses = append(responses, response)
	}
	return responses
}

func (gsm *graphSyncMessage) Cancel(id GraphSyncRequestID) {
	delete(gsm.requests, id)
191
	gsm.addRequest(id, nil, cid.Cid{}, 0, true)
192 193 194 195
}

func (gsm *graphSyncMessage) AddRequest(id GraphSyncRequestID,
	selector gsselector.Selector,
196
	root cid.Cid,
197 198 199 200 201 202 203
	priority GraphSyncPriority,
) {
	gsm.addRequest(id, selector, root, priority, false)
}

func (gsm *graphSyncMessage) addRequest(id GraphSyncRequestID,
	selector gsselector.Selector,
204
	root cid.Cid,
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
	priority GraphSyncPriority,
	isCancel bool) {
	gsm.requests[id] = &graphSyncRequest{
		id:       id,
		selector: selector,
		root:     root,
		priority: priority,
		isCancel: isCancel,
	}
}

func (gsm *graphSyncMessage) AddResponse(requestID GraphSyncRequestID,
	status GraphSyncResponseStatusCode,
	response gsselector.SelectionResponse) {
	gsm.responses[requestID] = &graphSyncResponse{
		requestID: requestID,
		status:    status,
		response:  response,
	}
}

226 227 228 229 230 231 232 233
// FromNet can read a network stream to deserialized a GraphSyncMessage
func FromNet(r io.Reader,
	decodeSelector DecodeSelectorFunc,
	decodeSelectionResponse DecodeSelectionResponseFunc) (GraphSyncMessage, error) {
	pbr := ggio.NewDelimitedReader(r, inet.MessageSizeMax)
	return FromPBReader(pbr, decodeSelector, decodeSelectionResponse)
}

234 235 236 237 238 239 240 241 242
// FromPBReader can deserialize a protobuf message into a GraphySyncMessage.
func FromPBReader(pbr ggio.Reader,
	decodeSelector DecodeSelectorFunc,
	decodeSelectionResponse DecodeSelectionResponseFunc) (GraphSyncMessage, error) {
	pb := new(pb.Message)
	if err := pbr.ReadMsg(pb); err != nil {
		return nil, err
	}

243
	return newMessageFromProto(*pb, decodeSelector, decodeSelectionResponse)
244 245 246 247 248 249 250 251
}

func (gsm *graphSyncMessage) ToProto() *pb.Message {
	pbm := new(pb.Message)
	pbm.Reqlist = make([]pb.Message_Request, 0, len(gsm.requests))
	for _, request := range gsm.requests {
		pbm.Reqlist = append(pbm.Reqlist, pb.Message_Request{
			Id:       int32(request.id),
252
			Root:     request.root.Bytes(),
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
			Selector: request.selector.RawData(),
			Priority: int32(request.priority),
			Cancel:   request.isCancel,
		})
	}

	pbm.Reslist = make([]pb.Message_Response, 0, len(gsm.responses))
	for _, response := range gsm.responses {
		pbm.Reslist = append(pbm.Reslist, pb.Message_Response{
			Id:     int32(response.requestID),
			Status: int32(response.status),
			Data:   response.response.RawData(),
		})
	}
	return pbm
}

270 271 272 273 274 275
func (gsm *graphSyncMessage) ToNet(w io.Writer) error {
	pbw := ggio.NewDelimitedWriter(w)

	return pbw.WriteMsg(gsm.ToProto())
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
func (gsm *graphSyncMessage) Loggable() map[string]interface{} {
	requests := make([]string, 0, len(gsm.requests))
	for _, request := range gsm.requests {
		requests = append(requests, fmt.Sprintf("%d", request.id))
	}
	responses := make([]string, 0, len(gsm.responses))
	for _, response := range gsm.responses {
		responses = append(responses, fmt.Sprintf("%d", response.requestID))
	}
	return map[string]interface{}{
		"requests":  requests,
		"responses": responses,
	}
}

func (gsr *graphSyncRequest) ID() GraphSyncRequestID        { return gsr.id }
292
func (gsr *graphSyncRequest) Root() cid.Cid                 { return gsr.root }
293 294 295 296 297 298 299
func (gsr *graphSyncRequest) Selector() gsselector.Selector { return gsr.selector }
func (gsr *graphSyncRequest) Priority() GraphSyncPriority   { return gsr.priority }
func (gsr *graphSyncRequest) IsCancel() bool                { return gsr.isCancel }

func (gsr *graphSyncResponse) RequestID() GraphSyncRequestID          { return gsr.requestID }
func (gsr *graphSyncResponse) Status() GraphSyncResponseStatusCode    { return gsr.status }
func (gsr *graphSyncResponse) Response() gsselector.SelectionResponse { return gsr.response }