-
Notifications
You must be signed in to change notification settings - Fork 82
/
reqres.go
296 lines (247 loc) · 8.86 KB
/
reqres.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
// Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package tchannel
import (
"fmt"
"github.com/uber/tchannel-go/typed"
)
type errReqResWriterStateMismatch struct {
state reqResWriterState
expectedState reqResWriterState
}
func (e errReqResWriterStateMismatch) Error() string {
return fmt.Sprintf("attempting write outside of expected state, in %v expected %v",
e.state, e.expectedState)
}
type errReqResReaderStateMismatch struct {
state reqResReaderState
expectedState reqResReaderState
}
func (e errReqResReaderStateMismatch) Error() string {
return fmt.Sprintf("attempting read outside of expected state, in %v expected %v",
e.state, e.expectedState)
}
// reqResWriterState defines the state of a request/response writer
type reqResWriterState int
const (
reqResWriterPreArg1 reqResWriterState = iota
reqResWriterPreArg2
reqResWriterPreArg3
reqResWriterComplete
)
//go:generate stringer -type=reqResWriterState
// messageForFragment determines which message should be used for the given
// fragment
type messageForFragment func(initial bool) message
// A reqResWriter writes out requests/responses. Exactly which it does is
// determined by its messageForFragment function which returns the appropriate
// message to use when building an initial or follow-on fragment.
type reqResWriter struct {
conn *Connection
contents *fragmentingWriter
mex *messageExchange
state reqResWriterState
messageForFragment messageForFragment
log Logger
err error
}
//go:generate stringer -type=reqResReaderState
func (w *reqResWriter) argWriter(last bool, inState reqResWriterState, outState reqResWriterState) (ArgWriter, error) {
if w.err != nil {
return nil, w.err
}
if w.state != inState {
return nil, w.failed(errReqResWriterStateMismatch{state: w.state, expectedState: inState})
}
argWriter, err := w.contents.ArgWriter(last)
if err != nil {
return nil, w.failed(err)
}
w.state = outState
return argWriter, nil
}
func (w *reqResWriter) arg1Writer() (ArgWriter, error) {
return w.argWriter(false /* last */, reqResWriterPreArg1, reqResWriterPreArg2)
}
func (w *reqResWriter) arg2Writer() (ArgWriter, error) {
return w.argWriter(false /* last */, reqResWriterPreArg2, reqResWriterPreArg3)
}
func (w *reqResWriter) arg3Writer() (ArgWriter, error) {
return w.argWriter(true /* last */, reqResWriterPreArg3, reqResWriterComplete)
}
// newFragment creates a new fragment for marshaling into
func (w *reqResWriter) newFragment(initial bool, checksum Checksum) (*writableFragment, error) {
if err := w.mex.checkError(); err != nil {
return nil, w.failed(err)
}
message := w.messageForFragment(initial)
// Create the frame
frame := w.conn.opts.FramePool.Get()
frame.Header.ID = w.mex.msgID
frame.Header.messageType = message.messageType()
// Write the message into the fragment, reserving flags and checksum bytes
wbuf := typed.NewWriteBuffer(frame.Payload[:])
fragment := new(writableFragment)
fragment.frame = frame
fragment.flagsRef = wbuf.DeferByte()
if err := message.write(wbuf); err != nil {
return nil, err
}
wbuf.WriteSingleByte(byte(checksum.TypeCode()))
fragment.checksumRef = wbuf.DeferBytes(checksum.Size())
fragment.checksum = checksum
fragment.contents = wbuf
return fragment, wbuf.Err()
}
// flushFragment sends a fragment to the peer over the connection
func (w *reqResWriter) flushFragment(fragment *writableFragment) error {
if w.err != nil {
return w.err
}
frame := fragment.frame
frame.Header.SetPayloadSize(uint16(fragment.contents.BytesWritten()))
if err := w.mex.checkError(); err != nil {
return w.failed(err)
}
select {
case <-w.mex.ctx.Done():
return w.failed(GetContextError(w.mex.ctx.Err()))
case <-w.mex.errCh.c:
return w.failed(w.mex.errCh.err)
case w.conn.sendCh <- frame:
return nil
}
}
// failed marks the writer as having failed
func (w *reqResWriter) failed(err error) error {
w.log.Debugf("writer failed: %v existing err: %v", err, w.err)
if w.err != nil {
return w.err
}
w.mex.shutdown()
w.err = err
return w.err
}
// reqResReaderState defines the state of a request/response reader
type reqResReaderState int
const (
reqResReaderPreArg1 reqResReaderState = iota
reqResReaderPreArg2
reqResReaderPreArg3
reqResReaderComplete
)
// A reqResReader is capable of reading arguments from a request or response object.
type reqResReader struct {
contents *fragmentingReader
mex *messageExchange
state reqResReaderState
messageForFragment messageForFragment
initialFragment *readableFragment
previousFragment *readableFragment
log Logger
err error
}
// arg1Reader returns an ArgReader to read arg1.
func (r *reqResReader) arg1Reader() (ArgReader, error) {
return r.argReader(false /* last */, reqResReaderPreArg1, reqResReaderPreArg2)
}
// arg2Reader returns an ArgReader to read arg2.
func (r *reqResReader) arg2Reader() (ArgReader, error) {
return r.argReader(false /* last */, reqResReaderPreArg2, reqResReaderPreArg3)
}
// arg3Reader returns an ArgReader to read arg3.
func (r *reqResReader) arg3Reader() (ArgReader, error) {
return r.argReader(true /* last */, reqResReaderPreArg3, reqResReaderComplete)
}
// argReader returns an ArgReader that can be used to read an argument. The
// ReadCloser must be closed once the argument has been read.
func (r *reqResReader) argReader(last bool, inState reqResReaderState, outState reqResReaderState) (ArgReader, error) {
if r.state != inState {
return nil, r.failed(errReqResReaderStateMismatch{state: r.state, expectedState: inState})
}
argReader, err := r.contents.ArgReader(last)
if err != nil {
return nil, r.failed(err)
}
r.state = outState
return argReader, nil
}
// recvNextFragment receives the next fragment from the underlying message exchange.
func (r *reqResReader) recvNextFragment(initial bool) (*readableFragment, error) {
if r.initialFragment != nil {
fragment := r.initialFragment
r.initialFragment = nil
r.previousFragment = fragment
return fragment, nil
}
// Wait for the appropriate message from the peer
message := r.messageForFragment(initial)
frame, err := r.mex.recvPeerFrameOfType(message.messageType())
if err != nil {
if err, ok := err.(errorMessage); ok {
// If we received a serialized error from the other side, then we should go through
// the normal doneReading path so stats get updated with this error.
r.err = err.AsSystemError()
return nil, err
}
return nil, r.failed(err)
}
// Parse the message and setup the fragment
fragment, err := parseInboundFragment(r.mex.framePool, frame, message)
if err != nil {
return nil, r.failed(err)
}
r.previousFragment = fragment
return fragment, nil
}
// releasePreviousFrament releases the last fragment returned by the reader if
// it's still around. This operation is idempotent.
func (r *reqResReader) releasePreviousFragment() {
fragment := r.previousFragment
r.previousFragment = nil
if fragment != nil {
fragment.done()
}
}
// failed indicates the reader failed
func (r *reqResReader) failed(err error) error {
r.log.Debugf("reader failed: %v existing err: %v", err, r.err)
if r.err != nil {
return r.err
}
r.mex.shutdown()
r.err = err
return r.err
}
// parseInboundFragment parses an incoming fragment based on the given message
func parseInboundFragment(framePool FramePool, frame *Frame, message message) (*readableFragment, error) {
rbuf := typed.NewReadBuffer(frame.SizedPayload())
fragment := new(readableFragment)
fragment.flags = rbuf.ReadSingleByte()
if err := message.read(rbuf); err != nil {
return nil, err
}
fragment.checksumType = ChecksumType(rbuf.ReadSingleByte())
fragment.checksum = rbuf.ReadBytes(fragment.checksumType.ChecksumSize())
fragment.contents = rbuf
fragment.onDone = func() {
framePool.Release(frame)
}
return fragment, rbuf.Err()
}