forked from linkerd/linkerd2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto_over_http.go
157 lines (126 loc) · 4.06 KB
/
proto_over_http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
package public
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/golang/protobuf/proto"
pb "github.com/linkerd/linkerd2/controller/gen/public"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/status"
)
const (
errorHeader = "linkerd-error"
defaultHttpErrorStatusCode = http.StatusInternalServerError
contentTypeHeader = "Content-Type"
protobufContentType = "application/octet-stream"
numBytesForMessageLength = 4
)
type httpError struct {
Code int
WrappedError error
}
type flushableResponseWriter interface {
http.ResponseWriter
http.Flusher
}
func (e httpError) Error() string {
return fmt.Sprintf("HTTP error, status Code [%d], wrapped error is: %v", e.Code, e.WrappedError)
}
func httpRequestToProto(req *http.Request, protoRequestOut proto.Message) error {
bytes, err := ioutil.ReadAll(req.Body)
if err != nil {
return httpError{
Code: http.StatusBadRequest,
WrappedError: err,
}
}
err = proto.Unmarshal(bytes, protoRequestOut)
if err != nil {
return httpError{
Code: http.StatusBadRequest,
WrappedError: err,
}
}
return nil
}
func writeErrorToHttpResponse(w http.ResponseWriter, errorObtained error) {
statusCode := defaultHttpErrorStatusCode
errorToReturn := errorObtained
if httpErr, ok := errorObtained.(httpError); ok {
statusCode = httpErr.Code
errorToReturn = httpErr.WrappedError
}
w.Header().Set(errorHeader, http.StatusText(statusCode))
errorMessageToReturn := errorToReturn.Error()
if grpcError, ok := status.FromError(errorObtained); ok {
errorMessageToReturn = grpcError.Message()
}
errorAsProto := &pb.ApiError{Error: errorMessageToReturn}
err := writeProtoToHttpResponse(w, errorAsProto)
if err != nil {
log.Errorf("Error writing error to http response: %v", err)
w.Header().Set(errorHeader, err.Error())
}
}
func writeProtoToHttpResponse(w http.ResponseWriter, msg proto.Message) error {
w.Header().Set(contentTypeHeader, protobufContentType)
marshalledProtobufMessage, err := proto.Marshal(msg)
if err != nil {
return err
}
fullPayload, err := serializeAsPayload(marshalledProtobufMessage)
if err != nil {
return err
}
_, err = w.Write(fullPayload)
return err
}
func newStreamingWriter(w http.ResponseWriter) (flushableResponseWriter, error) {
flushableWriter, ok := w.(flushableResponseWriter)
if !ok {
return nil, fmt.Errorf("streaming not supported by this writer")
}
flushableWriter.Header().Set("Connection", "keep-alive")
flushableWriter.Header().Set("Transfer-Encoding", "chunked")
return flushableWriter, nil
}
func serializeAsPayload(messageContentsInBytes []byte) ([]byte, error) {
lengthOfThePayload := uint32(len(messageContentsInBytes))
messageLengthInBytes := make([]byte, numBytesForMessageLength)
binary.LittleEndian.PutUint32(messageLengthInBytes, lengthOfThePayload)
return append(messageLengthInBytes, messageContentsInBytes...), nil
}
func deserializePayloadFromReader(reader *bufio.Reader) ([]byte, error) {
messageLengthAsBytes := make([]byte, numBytesForMessageLength)
_, err := io.ReadFull(reader, messageLengthAsBytes)
if err != nil {
return nil, fmt.Errorf("error while reading message length: %v", err)
}
messageLength := int(binary.LittleEndian.Uint32(messageLengthAsBytes))
messageContentsAsBytes := make([]byte, messageLength)
_, err = io.ReadFull(reader, messageContentsAsBytes)
if err != nil {
return nil, fmt.Errorf("error while reading bytes from message: %v", err)
}
return messageContentsAsBytes, nil
}
func checkIfResponseHasError(rsp *http.Response) error {
errorMsg := rsp.Header.Get(errorHeader)
if errorMsg != "" {
reader := bufio.NewReader(rsp.Body)
var apiError pb.ApiError
err := fromByteStreamToProtocolBuffers(reader, &apiError)
if err != nil {
return fmt.Errorf("Response has %s header [%s], but response body didn't contain protobuf error: %v", errorHeader, errorMsg, err)
}
return errors.New(apiError.Error)
}
if rsp.StatusCode != http.StatusOK {
return fmt.Errorf("Unexpected API response: %s", rsp.Status)
}
return nil
}