-
Notifications
You must be signed in to change notification settings - Fork 798
/
stream.go
487 lines (397 loc) · 13.4 KB
/
stream.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 sofarpc
import (
"context"
"sync"
"errors"
"strconv"
"sync/atomic"
"time"
"mosn.io/mosn/pkg/buffer"
mosnctx "mosn.io/mosn/pkg/context"
"mosn.io/mosn/pkg/log"
"mosn.io/mosn/pkg/protocol"
"mosn.io/mosn/pkg/protocol/rpc"
"mosn.io/mosn/pkg/protocol/rpc/sofarpc"
str "mosn.io/mosn/pkg/stream"
"mosn.io/mosn/pkg/trace"
"mosn.io/mosn/pkg/types"
)
// StreamDirection represent the stream's direction
type StreamDirection int
// ServerStream = 1
// ClientStream = 0
const (
ServerStream StreamDirection = 1
ClientStream StreamDirection = 0
)
var (
directionText = map[StreamDirection]string{
ClientStream: "request",
ServerStream: "response",
}
ErrNotSofarpcCmd = errors.New("not sofarpc command")
ErrNotResponseBuilder = errors.New("no response builder")
)
func init() {
str.Register(protocol.SofaRPC, &streamConnFactory{})
}
type streamConnFactory struct{}
func (f *streamConnFactory) CreateClientStream(context context.Context, connection types.ClientConnection,
clientCallbacks types.StreamConnectionEventListener, connCallbacks types.ConnectionEventListener) types.ClientStreamConnection {
return newStreamConnection(context, connection, clientCallbacks, nil)
}
func (f *streamConnFactory) CreateServerStream(context context.Context, connection types.Connection,
serverCallbacks types.ServerStreamConnectionEventListener) types.ServerStreamConnection {
return newStreamConnection(context, connection, nil, serverCallbacks)
}
func (f *streamConnFactory) CreateBiDirectStream(context context.Context, connection types.ClientConnection,
clientCallbacks types.StreamConnectionEventListener,
serverCallbacks types.ServerStreamConnectionEventListener) types.ClientStreamConnection {
return newStreamConnection(context, connection, clientCallbacks, serverCallbacks)
}
func (f *streamConnFactory) ProtocolMatch(context context.Context, prot string, magic []byte) error {
return str.FAILED
}
// types.DecodeFilter
// types.StreamConnection
// types.ClientStreamConnection
// types.ServerStreamConnection
type streamConnection struct {
ctx context.Context
conn types.Connection
contextManager *str.ContextManager
mutex sync.RWMutex
currStreamID uint64
streams map[uint64]*stream // client conn fields
codecEngine types.ProtocolEngine
streamConnectionEventListener types.StreamConnectionEventListener
serverStreamConnectionEventListener types.ServerStreamConnectionEventListener
}
func newStreamConnection(ctx context.Context, connection types.Connection, clientCallbacks types.StreamConnectionEventListener,
serverCallbacks types.ServerStreamConnectionEventListener) types.ClientStreamConnection {
sc := &streamConnection{
ctx: ctx,
conn: connection,
codecEngine: sofarpc.Engine(),
streamConnectionEventListener: clientCallbacks,
serverStreamConnectionEventListener: serverCallbacks,
contextManager: str.NewContextManager(ctx),
}
// init first context
sc.contextManager.Next()
if sc.streamConnectionEventListener != nil {
sc.streams = make(map[uint64]*stream, 2)
}
// set support transfer connection
sc.conn.SetTransferEventListener(func() bool {
return true
})
return sc
}
// types.StreamConnection
func (conn *streamConnection) Dispatch(buf types.IoBuffer) {
for {
// 1. pre alloc stream-level ctx with bufferCtx
ctx := conn.contextManager.Get()
// 2. decode process
// TODO: maybe pass sub protocol type
cmd, err := conn.codecEngine.Decode(ctx, buf)
// No enough data
if cmd == nil && err == nil {
break
}
if err != nil {
var data []byte
if buf != nil {
data = buf.Bytes()
if len(data) > 50 {
data = data[:50]
}
}
log.Proxy.Errorf(conn.ctx, "[stream] [sofarpc] conn %d, %v decode error: %v, buf data: %v", conn.conn.ID(), conn.conn.RemoteAddr(), err, data)
}
// Do handle staff. Error would also be passed to this function.
conn.handleCommand(ctx, cmd, err)
if err != nil {
break
}
conn.contextManager.Next()
}
}
func (conn *streamConnection) Protocol() types.Protocol {
return protocol.SofaRPC
}
func (conn *streamConnection) GoAway() {
// unsupported
}
func (conn *streamConnection) ActiveStreamsNum() int {
conn.mutex.RLock()
defer conn.mutex.RUnlock()
return len(conn.streams)
}
func (conn *streamConnection) Reset(reason types.StreamResetReason) {
conn.mutex.Lock()
defer conn.mutex.Unlock()
for _, stream := range conn.streams {
stream.connReset = true
stream.ResetStream(reason)
}
}
func (conn *streamConnection) NewStream(ctx context.Context, receiver types.StreamReceiveListener) types.StreamSender {
buffers := sofaBuffersByContext(ctx)
stream := &buffers.client
//stream := &stream{}
stream.id = atomic.AddUint64(&conn.currStreamID, 1)
stream.ctx = mosnctx.WithValue(ctx, types.ContextKeyStreamID, stream.id)
stream.direction = ClientStream
stream.sc = conn
stream.receiver = receiver
if stream.receiver != nil {
conn.mutex.Lock()
conn.streams[stream.id] = stream
conn.mutex.Unlock()
}
return stream
}
func (conn *streamConnection) handleCommand(ctx context.Context, model interface{}, err error) {
if err != nil {
conn.handleError(ctx, model, err)
return
}
cmd, ok := model.(sofarpc.SofaRpcCmd)
if !ok {
conn.handleError(ctx, model, ErrNotSofarpcCmd)
return
}
stream := conn.processStream(ctx, cmd)
// header, data notify
if stream != nil {
timeoutInt := cmd.GetTimeout()
timeout := strconv.Itoa(timeoutInt) // timeout, ms
cmd.Set(types.HeaderGlobalTimeout, timeout)
stream.receiver.OnReceive(stream.ctx, cmd, cmd.Data(), nil)
}
}
func (conn *streamConnection) handleError(ctx context.Context, cmd interface{}, err error) {
switch err {
case rpc.ErrUnrecognizedCode, sofarpc.ErrUnKnownCmdType, sofarpc.ErrUnKnownCmdCode, ErrNotSofarpcCmd:
addr := conn.conn.RemoteAddr()
log.Proxy.Alertf(conn.ctx, types.ErrorKeyCodec, "error occurs while proceeding codec logic: %v. close connection, remote addr: %v", err, addr)
//protocol decode error, close the connection directly
conn.conn.Close(types.NoFlush, types.LocalClose)
case types.ErrCodecException, types.ErrDeserializeException:
if cmd, ok := cmd.(sofarpc.SofaRpcCmd); ok {
if reqID := cmd.RequestID(); reqID > 0 {
// TODO: to see some error handling if is necessary to passed to proxy level, or just handle it at stream level
stream := conn.processStream(ctx, cmd)
// valid sofarpc cmd with positive requestID, send exception response in this case
if stream != nil {
stream.receiver.OnDecodeError(stream.ctx, err, cmd)
}
return
}
}
// if no request id found, no reason to send response, so close connection
conn.conn.Close(types.NoFlush, types.LocalClose)
}
}
func (conn *streamConnection) processStream(ctx context.Context, cmd sofarpc.SofaRpcCmd) *stream {
switch cmd.CommandType() {
case sofarpc.REQUEST, sofarpc.REQUEST_ONEWAY:
var span types.Span
if trace.IsEnabled() {
// try build trace span
tracer := trace.Tracer(protocol.SofaRPC)
if tracer != nil {
span = tracer.Start(ctx, cmd, time.Now())
}
}
return conn.onNewStreamDetect(ctx, cmd, span)
case sofarpc.RESPONSE:
return conn.onStreamRecv(ctx, cmd)
}
return nil
}
func (conn *streamConnection) onNewStreamDetect(ctx context.Context, cmd sofarpc.SofaRpcCmd, span types.Span) *stream {
buffers := sofaBuffersByContext(ctx)
stream := &buffers.server
//stream := &stream{}
stream.id = cmd.RequestID()
stream.ctx = mosnctx.WithValue(ctx, types.ContextKeyStreamID, stream.id)
stream.ctx = mosnctx.WithValue(ctx, types.ContextSubProtocol, cmd.ProtocolCode())
stream.ctx = conn.contextManager.InjectTrace(stream.ctx, span)
stream.direction = ServerStream
stream.sc = conn
if log.Proxy.GetLogLevel() >= log.DEBUG {
log.Proxy.Debugf(stream.ctx, "[stream] [sofarpc] new stream detect, requestId = %v", stream.id)
}
if cmd.CommandType() == sofarpc.REQUEST_ONEWAY {
stream.receiver = conn.serverStreamConnectionEventListener.NewStreamDetect(stream.ctx, nil, span)
} else {
stream.receiver = conn.serverStreamConnectionEventListener.NewStreamDetect(stream.ctx, stream, span)
}
return stream
}
func (conn *streamConnection) onStreamRecv(ctx context.Context, cmd sofarpc.SofaRpcCmd) *stream {
requestID := cmd.RequestID()
// for client stream, remove stream on response read
conn.mutex.Lock()
defer conn.mutex.Unlock()
if stream, ok := conn.streams[requestID]; ok {
delete(conn.streams, requestID)
// transmit buffer ctx
buffer.TransmitBufferPoolContext(stream.ctx, ctx)
if log.Proxy.GetLogLevel() >= log.DEBUG {
log.Proxy.Debugf(stream.ctx, "[stream] [sofarpc] receive response, requestId = %v", stream.id)
}
return stream
}
return nil
}
// types.Stream
// types.StreamSender
type stream struct {
str.BaseStream
connReset bool
ctx context.Context
sc *streamConnection
id uint64
direction StreamDirection // 0: out, 1: in
receiver types.StreamReceiveListener
sendCmd sofarpc.SofaRpcCmd
sendBuf types.IoBuffer
}
// ~~ types.Stream
func (s *stream) ID() uint64 {
return s.id
}
func (s *stream) ReadDisable(disable bool) {
s.sc.conn.SetReadDisable(disable)
}
func (s *stream) BufferLimit() uint32 {
return s.sc.conn.BufferLimit()
}
// types.StreamSender
func (s *stream) AppendHeaders(ctx context.Context, headers types.HeaderMap, endStream bool) error {
cmd, ok := headers.(sofarpc.SofaRpcCmd)
if !ok {
return ErrNotSofarpcCmd
}
var err error
switch s.direction {
case ClientStream:
// use origin request from downstream
s.sendCmd = cmd
case ServerStream:
switch cmd.CommandType() {
case sofarpc.RESPONSE:
// use origin response from upstream
s.sendCmd = cmd
case sofarpc.REQUEST, sofarpc.REQUEST_ONEWAY:
// the command type is request, indicates the invocation is under hijack scene
s.sendCmd, err = s.buildHijackResp(cmd)
}
}
if log.Proxy.GetLogLevel() >= log.DEBUG {
log.Proxy.Debugf(s.ctx, "[stream] [sofarpc] %s appendHeaders, requestId = %d", directionText[s.direction], s.id)
}
if endStream {
s.endStream()
}
return err
}
func (s *stream) buildHijackResp(request sofarpc.SofaRpcCmd) (sofarpc.SofaRpcCmd, error) {
if status, ok := request.Get(types.HeaderStatus); ok {
request.Del(types.HeaderStatus)
statusCode, _ := strconv.Atoi(status)
hijackResp := sofarpc.NewResponse(request.ProtocolCode(), sofarpc.MappingFromHttpStatus(statusCode))
if hijackResp != nil {
return hijackResp, nil
}
return nil, ErrNotResponseBuilder
}
return nil, types.ErrNoStatusCodeForHijack
}
func (s *stream) AppendData(context context.Context, data types.IoBuffer, endStream bool) error {
if s.sendCmd != nil {
// TODO: may affect buffer reuse
s.sendCmd.SetData(data)
}
if log.Proxy.GetLogLevel() >= log.DEBUG {
log.Proxy.Debugf(s.ctx, "[stream] [sofarpc] %s appendData, requestId = %d", directionText[s.direction], s.id)
}
if endStream {
s.endStream()
}
return nil
}
func (s *stream) AppendTrailers(context context.Context, trailers types.HeaderMap) error {
s.endStream()
return nil
}
// Flush stream data
// For server stream, write out response
// For client stream, write out request
func (s *stream) endStream() {
defer func() {
if s.direction == ServerStream {
s.DestroyStream()
}
}()
if s.sendCmd != nil {
// replace requestID
s.sendCmd.SetRequestID(s.id)
// remove the inject header
s.sendCmd.Del(types.HeaderGlobalTimeout)
// TODO: replaced with EncodeTo, and pre-alloc send buf
buf, err := s.sc.codecEngine.Encode(s.ctx, s.sendCmd)
if err != nil {
log.Proxy.Errorf(s.ctx, "[stream] [sofarpc] %s encode error:%s", directionText[s.direction], err.Error())
s.ResetStream(types.StreamLocalReset)
return
}
if dataBuf := s.sendCmd.Data(); dataBuf != nil {
err = s.sc.conn.Write(buf, dataBuf)
} else {
err = s.sc.conn.Write(buf)
}
if log.Proxy.GetLogLevel() >= log.DEBUG {
log.Proxy.Debugf(s.ctx, "[stream] [sofarpc] send %s, requestId = %v", directionText[s.direction], s.id)
}
if err != nil {
log.Proxy.Errorf(s.ctx, "[stream] [sofarpc] requestId = %v, error = %v", s.id, err)
if err == types.ErrConnectionHasClosed {
s.ResetStream(types.StreamConnectionFailed)
} else {
s.ResetStream(types.StreamLocalReset)
}
}
}
}
func (s *stream) GetStream() types.Stream {
return s
}
func (s *stream) ResetStream(reason types.StreamResetReason) {
if s.direction == ClientStream && !s.connReset {
s.sc.mutex.Lock()
delete(s.sc.streams, s.id)
s.sc.mutex.Unlock()
}
s.BaseStream.ResetStream(reason)
}