-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
330 lines (259 loc) · 5.85 KB
/
session.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
package mux
import (
"io"
"bufio"
"bytes"
"sync"
"errors"
"log"
"encoding/binary"
"fmt"
"time"
"math"
"net"
)
const LatestMuxVersion = 0x0001
type ClientSession interface {
Close() error
Dispatch(msg Tdispatch) (Rdispatch, error)
Ping() (time.Duration, error)
}
func SimpleDispatch(s ClientSession, data []byte) (out []byte, err error) {
disp := Tdispatch{
Body: data,
}
var rdisp Rdispatch
rdisp,err = s.Dispatch(disp)
if err != nil {
return
}
out = rdisp.Body
return
}
// Basic client dispatcher
type baseStreamState struct {
streamId int32 // stream id associated with this stream
parent *baseClientSession
input chan Message // only a single element will go in the channel
}
func (b *baseStreamState) discard() {
close(b.input)
session := b.parent
session.lock.Lock()
defer session.lock.Unlock()
delete(session.streams.openStreams, b.streamId)
}
// TODO: we don't have any information about error in this
type baseClientSession struct {
lock sync.RWMutex
rw *bufio.ReadWriter
streams baseTracker
c codec
}
func (s *baseClientSession) Ping() (out time.Duration, err error) {
now := time.Now()
panic("This is not a real function...")
end := time.Now()
out = now.Sub(end)
return
}
func (s *baseClientSession) Dispatch(in Tdispatch) (out Rdispatch, err error) {
var stream *baseStreamState
stream, err = makeStreamState(s)
if err != nil {
return
}
defer stream.discard()
frame := Frame{
streamId: stream.streamId,
message: &in,
}
err = s.c.encodeFrame(s.rw.Writer, &frame)
if err != nil {
return
}
message, ok := <- stream.input
if !ok {
err = io.EOF
return
}
switch msg := message.(type) {
case *Rdispatch:
out = *msg
case *Rerr:
err = errors.New(msg.error)
default:
err = errors.New(fmt.Sprintf("Unexpcted message type: %d", msg.Type()))
}
return
}
func baseReadLoop(s *baseClientSession) {
for {
frame, err := s.c.decodeFrame(s.rw)
if err != nil {
log.Println("Graceful shutdown not implemented. Error: " + err.Error())
break
}
switch msg := frame.message.(type) {
case *Rdispatch:
baseSessionRdispatch(s, &frame, msg)
default:
panic("I don't know what this is!")
}
}
}
func baseSessionRdispatch(session *baseClientSession, frame *Frame, d *Rdispatch) (err error) {
tracker := &session.streams
session.lock.RLock()
defer session.lock.RUnlock()
stream, ok := tracker.openStreams[frame.streamId]
if !ok {
log.Printf("Received Rdispatch frame from non-existant stream %d", frame.streamId)
return
}
stream.input <- d
return
}
func (s *baseClientSession) Close() error {
panic("not implemented")
}
// Intended to be a simple constructor function
func makeStreamState(parent *baseClientSession) (state *baseStreamState, err error) {
parent.lock.Lock()
defer parent.lock.Unlock()
state = &baseStreamState{}
state.streamId, err = parent.streams.nextStreamId()
if err != nil {
return
}
state.parent = parent
state.input = make(chan Message)
parent.streams.openStreams[state.streamId] = state
return
}
func NewClientSession(address string, maxFrameSize int32) (session ClientSession, err error) {
var raw net.Conn
raw, err = net.Dial("tcp", address)
if err != nil {
return
}
if maxFrameSize == math.MaxInt32 {
// No need to negotiate framing, its slower anyway
session = newBaseClientSession(raw)
return
}
var canInit bool
canInit, err = canTinit(raw)
if err != nil {
return
}
if canInit {
headers := ClientHeaders(maxFrameSize)
err = sendInit(raw, LatestMuxVersion, headers)
if err != nil {
return
}
var frame Frame
frame, err = DecodeFrame(raw)
if err != nil {
return
}
switch rmsg := frame.message.(type) {
case *Rinit:
fmt.Printf("Found rinit msg. Headers:\n")
for _, h := range rmsg.headers {
fmt.Printf("('%s', '%s')\n", string(h.Key), string(h.Value))
}
// TODO: we have nogotiated to mux v1... We should use it.
panic("Not implemented")
default:
err = errors.New(fmt.Sprintf("Failed to init! Type: %d\n", frame.message.Type()))
}
} else {
// Don't support protocol nogotiation, just use the default.
session = newBaseClientSession(raw)
}
return
}
func newBaseClientSession(raw io.ReadWriteCloser) ClientSession {
rw := bufio.NewReadWriter(bufio.NewReader(raw), bufio.NewWriter(raw))
bSession := &baseClientSession{
rw: rw,
c: &baseCodec{},
streams: newBaseStreamTracker(),
}
go baseReadLoop(bSession)
return bSession
}
func ClientHeaders(maxFrameSize int32) []Header {
buffer := bytes.NewBuffer([]byte{})
binary.Write(buffer, binary.BigEndian, maxFrameSize)
header := Header{
Key: []byte("mux-framer"),
Value: buffer.Bytes(),
}
return []Header {header}
}
func sendInit(writer io.Writer, version int16, headers []Header) (err error) {
msg := Tinit{
version: version,
headers: headers,
}
err = EncodeFrame(writer, &Frame{
streamId: 1,
message: &msg,
})
return
}
func canTinit(rw io.ReadWriter) (canInit bool, err error) {
msg := Rerr{
error: "tinit check",
}
err = EncodeFrame(rw, &Frame{
streamId: 1,
message: &msg,
})
if err != nil {
return
}
var frame Frame
frame, err = DecodeFrame(rw)
if frame.streamId != 1 {
canInit = false
return
}
switch rmsg := frame.message.(type) {
case *Rerr:
canInit = msg.error == rmsg.error
default:
canInit = false
}
return
}
type baseTracker struct {
nextId int32
openStreams map[int32]*baseStreamState
}
func newBaseStreamTracker() baseTracker {
return baseTracker{
nextId: 1,
openStreams: make(map[int32]*baseStreamState),
}
}
func (s *baseTracker) nextStreamId() (int32, error) {
start := s.nextId
for {
i := s.nextId
_, occupied := s.openStreams[i]
s.nextId += 1
if s.nextId > MaxStreamId {
s.nextId = 1
}
if !occupied {
return i, nil // success
}
if s.nextId == start {
return 0, errors.New("Exhausted tag numbers")
}
}
}