forked from apache/dubbo-go-hessian2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
272 lines (230 loc) · 7.02 KB
/
response.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
// Copyright 2016-2019 Alex Stocks, Yincheng Fang
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hessian
import (
"encoding/binary"
"math"
"reflect"
"strconv"
"strings"
)
import (
perrors "github.com/pkg/errors"
)
// dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java
// v2.7.1 line 256 encodeResponse
// hessian encode response
func packResponse(header DubboHeader, attachments map[string]string, ret interface{}) ([]byte, error) {
var (
byteArray []byte
)
hb := header.Type == PackageHeartbeat
// magic
if hb {
byteArray = append(byteArray, DubboResponseHeartbeatHeader[:]...)
} else {
byteArray = append(byteArray, DubboResponseHeaderBytes[:]...)
}
// set serialID, identify serialization types, eg: fastjson->6, hessian2->2
byteArray[2] |= header.SerialID & SERIAL_MASK
// response status
if header.ResponseStatus != 0 {
byteArray[3] = header.ResponseStatus
}
// request id
binary.BigEndian.PutUint64(byteArray[4:], uint64(header.ID))
// body
encoder := NewEncoder()
encoder.Append(byteArray[:HEADER_LENGTH])
if hb {
encoder.Encode(nil)
} else {
// com.alibaba.dubbo.rpc.protocol.dubbo.DubboCodec.DubboCodec.java
// v2.7.1 line191 encodeRequestData
atta := isSupportResponseAttachment(attachments[DUBBO_VERSION_KEY])
var resWithException, resValue, resNullValue int32
if atta {
resWithException = RESPONSE_WITH_EXCEPTION
resValue = RESPONSE_VALUE
resNullValue = RESPONSE_NULL_VALUE
} else {
resWithException = RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS
resValue = RESPONSE_VALUE_WITH_ATTACHMENTS
resNullValue = RESPONSE_NULL_VALUE_WITH_ATTACHMENTS
}
if e, ok := ret.(error); ok { // throw error
encoder.Encode(resWithException)
encoder.Encode(e.Error())
} else {
if ret == nil {
encoder.Encode(resNullValue)
} else {
encoder.Encode(resValue)
encoder.Encode(ret) // result
}
}
if atta {
encoder.Encode(attachments) // attachments
}
}
byteArray = encoder.Buffer()
byteArray = encNull(byteArray) // if not, "java client" will throw exception "unexpected end of file"
pkgLen := len(byteArray)
if pkgLen > int(DEFAULT_LEN) { // 8M
return nil, perrors.Errorf("Data length %d too large, max payload %d", pkgLen, DEFAULT_LEN)
}
// byteArray{body length}
binary.BigEndian.PutUint32(byteArray[12:], uint32(pkgLen-HEADER_LENGTH))
return byteArray, nil
}
// hessian decode response body
// todo: need to read attachments, but don't known it's effect yet
func unpackResponseBody(buf []byte, rspObj interface{}) error {
// body
decoder := NewDecoder(buf[:])
rspType, err := decoder.Decode()
if err != nil {
return perrors.WithStack(err)
}
switch rspType {
case RESPONSE_WITH_EXCEPTION, RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS:
expt, err := decoder.Decode()
if err != nil {
return perrors.WithStack(err)
}
return perrors.Errorf("got exception: %+v", expt)
case RESPONSE_VALUE, RESPONSE_VALUE_WITH_ATTACHMENTS:
rsp, err := decoder.Decode()
if err != nil {
return perrors.WithStack(err)
}
return perrors.WithStack(ReflectResponse(rsp, rspObj))
case RESPONSE_NULL_VALUE, RESPONSE_NULL_VALUE_WITH_ATTACHMENTS:
return perrors.New("Received null")
}
return nil
}
// CopySlice copy from inSlice to outSlice
func CopySlice(inSlice, outSlice reflect.Value) error {
if inSlice.IsNil() {
return perrors.New("@in is nil")
}
if inSlice.Kind() != reflect.Slice {
return perrors.Errorf("@in is not slice, but %v", inSlice.Kind())
}
for outSlice.Kind() == reflect.Ptr {
outSlice = outSlice.Elem()
}
size := inSlice.Len()
outSlice.Set(reflect.MakeSlice(outSlice.Type(), size, size))
for i := 0; i < size; i++ {
inSliceValue := inSlice.Index(i)
if !inSliceValue.Type().AssignableTo(outSlice.Index(i).Type()) {
return perrors.Errorf("in element type [%s] can not assign to out element type [%s]",
inSliceValue.Type().String(), outSlice.Type().String())
}
outSlice.Index(i).Set(inSliceValue)
}
return nil
}
// CopyMap copy from in map to out map
func CopyMap(inMapValue, outMapValue reflect.Value) error {
if inMapValue.IsNil() {
return perrors.New("@in is nil")
}
if !inMapValue.CanInterface() {
return perrors.New("@in's Interface can not be used.")
}
if inMapValue.Kind() != reflect.Map {
return perrors.Errorf("@in is not map, but %v", inMapValue.Kind())
}
outMapType := UnpackPtrType(outMapValue.Type())
SetValue(outMapValue, reflect.MakeMap(outMapType))
outKeyType := outMapType.Key()
outMapValue = UnpackPtrValue(outMapValue)
outValueType := outMapValue.Type().Elem()
for _, inKey := range inMapValue.MapKeys() {
inValue := inMapValue.MapIndex(inKey)
if !inKey.Type().AssignableTo(outKeyType) {
return perrors.Errorf("in Key:{type:%s, value:%#v} can not assign to out Key:{type:%s} ",
inKey.Type().String(), inKey, outKeyType.String())
}
if !inValue.Type().AssignableTo(outValueType) {
return perrors.Errorf("in Value:{type:%s, value:%#v} can not assign to out value:{type:%s}",
inValue.Type().String(), inValue, outValueType.String())
}
outMapValue.SetMapIndex(inKey, inValue)
}
return nil
}
// ReflectResponse reflect return value
func ReflectResponse(in interface{}, out interface{}) error {
if in == nil {
return perrors.Errorf("@in is nil")
}
if out == nil {
return perrors.Errorf("@out is nil")
}
if reflect.TypeOf(out).Kind() != reflect.Ptr {
return perrors.Errorf("@out should be a pointer")
}
inValue := EnsurePackValue(in)
outValue := EnsurePackValue(out)
switch inValue.Type().Kind() {
case reflect.Slice, reflect.Array:
return CopySlice(inValue, outValue)
case reflect.Map:
return CopyMap(inValue, outValue)
default:
SetValue(outValue, inValue)
}
return nil
}
var versionInt = make(map[string]int)
// isSupportResponseAttachment is for compatibility among some dubbo version
// but we haven't used it yet.
// dubbo-common/src/main/java/org/apache/dubbo/common/Version.java
// v2.7.1 line 96
func isSupportResponseAttachment(version string) bool {
if version == "" {
return false
}
v, ok := versionInt[version]
if !ok {
v = version2Int(version)
if v == -1 {
return false
}
}
if v >= 2001000 && v <= 2060200 { // 2.0.10 ~ 2.6.2
return false
}
return v >= LOWEST_VERSION_FOR_RESPONSE_ATTACHMENT
}
func version2Int(version string) int {
var v = 0
varr := strings.Split(version, ".")
length := len(varr)
for key, value := range varr {
v0, err := strconv.Atoi(value)
if err != nil {
return -1
}
v += v0 * int(math.Pow10((length-key-1)*2))
}
if length == 3 {
return v * 100
}
return v
}