forked from go-chassis/go-chassis
/
highway_msgobj.go
executable file
·363 lines (327 loc) · 9.07 KB
/
highway_msgobj.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
158
159
160
161
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package highway
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"reflect"
"strings"
"sync"
"github.com/go-chassis/go-chassis/client/highway/pb"
"github.com/go-chassis/go-chassis/core/lager"
"github.com/go-chassis/go-chassis/core/provider"
"github.com/go-chassis/go-chassis/core/util/string"
"github.com/golang/protobuf/proto"
"io"
)
//number const
const (
FrameHeadLen = 23
MagicLen = 7
)
//status code
const (
Ok = 200
ServerError = 505
)
var localSupportLogin = true
var gCurMSGID uint64
var msgIDMtx sync.Mutex
//GenerateMsgID generate message ID
func GenerateMsgID() uint64 {
msgIDMtx.Lock()
gCurMSGID++
msgIDMtx.Unlock()
return gCurMSGID
}
//Request Highway request
type Request struct {
MsgID uint64
MsgType int
TwoWay bool
Arg interface{}
MethodName string
SvcName string
Schema string
Attachments map[string]string
}
//Response Highway response
type Response struct {
MsgID uint64
Status int
Err string
MsgType int
Result interface{}
Attachments map[string]string
}
var magID = "CSE.TCP"
var magicID = [MagicLen]byte{0x43, 0x53, 0x45, 0x2E, 0x54, 0x43, 0x50}
type highwayFrameHead struct {
Magic [MagicLen]byte
MsgID uint64
TotalLen uint32
HeaderLen uint32
}
func (frHead *highwayFrameHead) serialize() []byte {
buf := new(bytes.Buffer)
binary.Write(buf, binary.BigEndian, frHead.Magic)
binary.Write(buf, binary.BigEndian, frHead.MsgID)
binary.Write(buf, binary.BigEndian, frHead.TotalLen)
binary.Write(buf, binary.BigEndian, frHead.HeaderLen)
return buf.Bytes()
}
func (frHead *highwayFrameHead) deserialize(buf []byte) error {
if len(buf) < FrameHeadLen {
return errors.New("Too few bytes")
}
rdBuf := bytes.NewBuffer(buf)
binary.Read(rdBuf, binary.BigEndian, &frHead.Magic)
if !strings.EqualFold(magID, stringutil.Bytes2str(frHead.Magic[0:])) {
return errors.New("Invalid magicID")
}
binary.Read(rdBuf, binary.BigEndian, &frHead.MsgID)
binary.Read(rdBuf, binary.BigEndian, &frHead.TotalLen)
binary.Read(rdBuf, binary.BigEndian, &frHead.HeaderLen)
return nil
}
func newHeadFrame(msgID uint64) *highwayFrameHead {
return &highwayFrameHead{magicID, msgID, 0, 0}
}
//ProtocolObject highway Protocal
type ProtocolObject struct {
FrHead highwayFrameHead
payLoad []byte
}
//ProtocolName protocal name
func (msgObj *ProtocolObject) ProtocolName() string {
return "Highway"
}
//SerializeReq Serialize request
func (msgObj *ProtocolObject) SerializeReq(req *Request, wBuf *bufio.Writer) {
frHead := newHeadFrame(uint64(req.MsgID))
//flags:Indicates whether compression , temporarily not to use
reqHeader := highway.RequestHeader{
MsgType: highway.MsgTypeRequest,
Flags: int32(0),
DestMicroservice: req.SvcName,
OperationName: req.MethodName,
SchemaID: req.Schema,
Context: req.Attachments,
}
header, err := proto.Marshal(&reqHeader)
if err != nil {
lager.Logger.Errorf(err, "client marshal highway request header failed.")
return
}
frHead.HeaderLen = uint32(len(header))
body, err := proto.Marshal(req.Arg.(proto.Message))
if err != nil {
return
}
frHead.TotalLen = frHead.HeaderLen + uint32(len(body))
wBuf.Write(frHead.serialize())
wBuf.Write(header)
wBuf.Write(body)
}
//SerializeRsp Serialize frame
func (msgObj *ProtocolObject) SerializeRsp(rsp *Response, wBuf *bufio.Writer) {
frHead := newHeadFrame(uint64(rsp.MsgID))
//todo parse meta
//flags:Indicates whether compression , temporarily not to use
respHeader := &highway.ResponseHeader{}
respHeader.StatusCode = int32(rsp.Status)
respHeader.Reason = rsp.Err
rsp.Attachments = respHeader.Context
respHeader.Flags = 0
header, err := proto.Marshal(respHeader)
if err != nil {
lager.Logger.Errorf(err, "client marshal highway request header failed.")
return
}
var body []byte
frHead.HeaderLen = uint32(len(header))
if rsp.Result != nil {
body, err = proto.Marshal(rsp.Result.(proto.Message))
if err != nil {
return
}
frHead.TotalLen = frHead.HeaderLen + uint32(len(body))
} else {
frHead.TotalLen = frHead.HeaderLen
}
wBuf.Write(frHead.serialize())
wBuf.Write(header)
if body != nil {
wBuf.Write(body)
}
}
//DeSerializeFrame Deserialize frame
func (msgObj *ProtocolObject) DeSerializeFrame(rdBuf *bufio.Reader) error {
var err error
var count int
//Parse frame head
buf := make([]byte, FrameHeadLen)
count = 0
for count < FrameHeadLen {
tmpsize, rdErr := rdBuf.Read(buf[count:])
if rdErr != nil {
if rdErr != io.EOF {
lager.Logger.Errorf(rdErr, "Recv Frame head failed.")
}
return rdErr
}
count += tmpsize
}
msgObj.FrHead = highwayFrameHead{}
err = msgObj.FrHead.deserialize(buf)
if err != nil {
lager.Logger.Errorf(err, "Frame head error.")
return err
}
msgObj.payLoad = make([]byte, msgObj.FrHead.TotalLen)
count = 0
for count < int(msgObj.FrHead.TotalLen) {
tmpsize, rdErr := rdBuf.Read(msgObj.payLoad[count:])
if rdErr != nil {
lager.Logger.Errorf(rdErr, "Read frame body failed")
return rdErr
}
count += tmpsize
}
return nil
}
//DeSerializeRsp Deserialize rsp
func (msgObj *ProtocolObject) DeSerializeRsp(rsp *Response) error {
var err error
rsp.MsgID = msgObj.FrHead.MsgID
respHeader := &highway.ResponseHeader{}
//Head
err = proto.Unmarshal(msgObj.payLoad[0:msgObj.FrHead.HeaderLen], respHeader)
if err != nil {
lager.Logger.Errorf(err, "Unmarshal response header failed")
return err
}
rsp.Status = int(respHeader.GetStatusCode())
rsp.Err = respHeader.GetReason()
rsp.Attachments = respHeader.Context
//Body
if msgObj.FrHead.HeaderLen != msgObj.FrHead.TotalLen {
err = proto.Unmarshal(msgObj.payLoad[msgObj.FrHead.HeaderLen:], (rsp.Result).(proto.Message))
if err != nil {
lager.Logger.Errorf(err, "Unmarshal response body failed")
rsp.Err = err.Error()
return err
}
}
return nil
}
//DeSerializeReq Deserialize req
func (msgObj *ProtocolObject) DeSerializeReq(req *Request) error {
var err error
req.MsgID = msgObj.FrHead.MsgID
reqHeader := &highway.RequestHeader{}
err = proto.Unmarshal(msgObj.payLoad[0:msgObj.FrHead.HeaderLen], reqHeader)
if err != nil {
lager.Logger.Errorf(err, "Unmarshal request header failed")
return err
}
if req.Arg == nil {
req.MethodName = reqHeader.GetOperationName()
req.SvcName = reqHeader.GetDestMicroservice()
req.Schema = reqHeader.GetSchemaID()
req.Attachments = reqHeader.Context
req.MsgType = int(reqHeader.MsgType)
//Here we need to parse Attachments, indicating whether it is TwoWay,Current only twoway
req.TwoWay = true
var op provider.Operation
op, err = provider.GetOperation(req.SvcName, req.Schema, req.MethodName)
if err != nil {
return err
}
if op != nil && op.Args() != nil && len(op.Args()) > 0 {
if op.Args()[1].Kind() != reflect.Ptr {
err = errors.New("second arg not ptr")
return err
}
argv := reflect.New(op.Args()[1].Elem())
req.Arg = argv.Interface()
//Body
err = proto.Unmarshal(msgObj.payLoad[msgObj.FrHead.HeaderLen:], (req.Arg).(proto.Message))
if err != nil {
lager.Logger.Errorf(err, "Unmarshal request body failed")
return err
}
}
} else {
err = proto.Unmarshal(msgObj.payLoad[msgObj.FrHead.HeaderLen:], (req.Arg).(proto.Message))
if err != nil {
lager.Logger.Errorf(err, "Unmarshal hello request body failed")
return err
}
}
return nil
}
//SerializeHelloReq Serialize hello req
func (msgObj *ProtocolObject) SerializeHelloReq(wBuf *bufio.Writer) error {
frHead := newHeadFrame(GenerateMsgID())
reqHeader := highway.RequestHeader{
MsgType: highway.MsgTypeLogin,
Flags: int32(0),
DestMicroservice: "",
OperationName: "",
SchemaID: "",
Context: nil,
}
header, err := proto.Marshal(&reqHeader)
if err != nil {
lager.Logger.Errorf(err, "Marshal highway login header failed")
return err
}
frHead.HeaderLen = uint32(len(header))
loginBody := highway.LoginRequest{
Protocol: "highway",
ZipName: "z",
UseProtobufMapCodec: localSupportLogin,
}
body, err := proto.Marshal(&loginBody)
if err != nil {
lager.Logger.Errorf(err, "Marshal highway login body failed")
return err
}
frHead.TotalLen = uint32(len(body)) + frHead.HeaderLen
wBuf.Write(frHead.serialize())
wBuf.Write(header)
wBuf.Write(body)
return nil
}
//SerializeLoginRap Serialize hello req
func (msgObj *ProtocolObject) SerializeLoginRap(msgID uint64, wBuf *bufio.Writer) error {
frHead := newHeadFrame(msgID)
reqHeader := &highway.ResponseHeader{
Flags: int32(0),
StatusCode: Ok,
Reason: "",
Context: nil,
}
header, err := proto.Marshal(reqHeader)
if err != nil {
lager.Logger.Errorf(err, "Marshal highway login header failed")
return err
}
frHead.HeaderLen = uint32(len(header))
loginRspBody := &highway.LoginResponse{
Protocol: "highway",
ZipName: "z",
UseProtobufMapCodec: true,
}
body, err := proto.Marshal(loginRspBody)
if err != nil {
lager.Logger.Errorf(err, "Marshal highway login body failed")
return err
}
frHead.TotalLen = uint32(len(body)) + frHead.HeaderLen
wBuf.Write(frHead.serialize())
wBuf.Write(header)
wBuf.Write(body)
return nil
}