-
Notifications
You must be signed in to change notification settings - Fork 204
/
transport.go
321 lines (294 loc) · 6.75 KB
/
transport.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
/*--------------------------------------------------------*\
| |
| hprose |
| |
| Official WebSite: https://hprose.com |
| |
| rpc/websocket/transport.go |
| |
| LastModified: May 22, 2021 |
| Author: Ma Bingyao <andot@hprose.com> |
| |
\*________________________________________________________*/
package websocket
import (
"context"
"net/http"
"runtime"
"sync"
"sync/atomic"
"github.com/fasthttp/websocket"
"github.com/hprose/hprose-golang/v3/rpc/core"
)
type conn struct {
*websocket.Conn
requests chan data
results map[int]chan data
lock sync.Mutex
counter int32
onClose func(*websocket.Conn)
once sync.Once
}
func dial(ctx context.Context) (*websocket.Conn, error) {
u := core.GetClientContext(ctx).URL
var d websocket.Dialer
switch u.Scheme {
case "ws", "wss":
header := http.Header{"Sec-WebSocket-Protocol": []string{"hprose"}}
conn, response, err := d.DialContext(ctx, u.String(), header)
if response != nil {
response.Body.Close()
}
return conn, err
}
return nil, core.UnsupportedProtocolError{Scheme: u.Scheme}
}
func newConn(ctx context.Context, onConnect func(*websocket.Conn) *websocket.Conn, onClose func(*websocket.Conn)) (*conn, error) {
c, err := dial(ctx)
if err != nil {
return nil, err
}
return &conn{
Conn: onConnect(c),
requests: make(chan data),
onClose: onClose,
results: make(map[int]chan data),
}, nil
}
func (c *conn) store(index int, resultChan chan data) {
c.lock.Lock()
c.results[index] = resultChan
c.lock.Unlock()
}
func (c *conn) delete(index int) {
c.lock.Lock()
delete(c.results, index)
c.lock.Unlock()
}
func (c *conn) loadAndDelete(index int) (resultChan chan data, loaded bool) {
c.lock.Lock()
if resultChan, loaded = c.results[index]; loaded {
delete(c.results, index)
}
c.lock.Unlock()
return
}
func (c *conn) rangeAndClean(f func(index int, resultChan chan data)) {
c.lock.Lock()
for len(c.results) > 0 {
results := c.results
c.results = make(map[int]chan data)
c.lock.Unlock()
for index, resultChan := range results {
f(index, resultChan)
}
runtime.Gosched()
c.lock.Lock()
}
c.lock.Unlock()
}
func (c *conn) Transport(ctx context.Context, request []byte) (response []byte, err error) {
index := int(atomic.AddInt32(&c.counter, 1) & 0x7fffffff)
resultChan := make(chan data, 1)
c.store(index, resultChan)
select {
case <-ctx.Done():
c.delete(index)
return nil, ctx.Err()
case c.requests <- data{
Index: index,
Body: request,
}:
case res := <-resultChan:
return res.Body, res.Error
}
select {
case <-ctx.Done():
c.delete(index)
return nil, ctx.Err()
case res := <-resultChan:
return res.Body, res.Error
}
}
func (c *conn) Exit(onExit func(), err error) {
onExit()
if e := recover(); e != nil {
err = core.NewPanicError(e)
}
if err != nil {
c.Close(err)
}
}
func (c *conn) send(request data) error {
header := makeHeader(request.Index)
writer, err := c.NextWriter(websocket.BinaryMessage)
if err == nil {
_, err = writer.Write(header[:])
if err == nil {
_, err = writer.Write(request.Body)
if err == nil {
err = writer.Close()
}
}
}
return err
}
func (c *conn) Send(ctx context.Context, onExit func()) {
var err error
defer func() {
c.Exit(onExit, err)
}()
for {
select {
case <-ctx.Done():
return
case request := <-c.requests:
if err = c.send(request); err != nil {
return
}
}
}
}
func (c *conn) receive() (err error) {
var (
messageType int
body []byte
)
messageType, body, err = c.ReadMessage()
if err != nil {
return
}
switch messageType {
case websocket.CloseMessage:
err = core.ErrClosed
return
case websocket.BinaryMessage:
default:
return
}
index, ok := parseHeader(body[:4])
body = body[4:]
if !ok {
if string(body) == core.RequestEntityTooLarge {
err = core.ErrRequestEntityTooLarge
} else {
err = core.InvalidResponseError{Response: body}
}
return
}
if resultChan, loaded := c.loadAndDelete(index); loaded {
resultChan <- data{
Index: index,
Body: body,
}
}
return
}
func (c *conn) Receive(ctx context.Context, onExit func()) {
var err error
defer func() {
c.Exit(onExit, err)
}()
for {
select {
case <-ctx.Done():
return
default:
if err = c.receive(); err != nil {
return
}
}
}
}
func (c *conn) Close(err error) {
c.once.Do(func() {
c.onClose(c.Conn)
_ = c.Conn.Close()
})
c.rangeAndClean(func(index int, resultChan chan data) {
resultChan <- data{
Index: index,
Error: err,
}
})
}
type Transport struct {
OnConnect func(*websocket.Conn) *websocket.Conn
OnClose func(*websocket.Conn)
conns map[string]*conn
lock sync.RWMutex
}
func (trans *Transport) getConn(ctx context.Context) (conn *conn, err error) {
u := core.GetClientContext(ctx).URL
key := u.String()
trans.lock.RLock()
if conn = trans.conns[key]; conn != nil {
trans.lock.RUnlock()
return
}
trans.lock.RUnlock()
trans.lock.Lock()
defer trans.lock.Unlock()
if conn = trans.conns[key]; conn != nil {
return
}
conn, err = newConn(ctx, trans.onConnect, trans.onClose)
if err != nil {
return
}
trans.conns[key] = conn
ctx, cancel := context.WithCancel(context.Background())
onExit := func() {
trans.lock.Lock()
if trans.conns[key] == conn {
delete(trans.conns, key)
cancel()
}
trans.lock.Unlock()
}
go conn.Send(ctx, onExit)
go conn.Receive(ctx, onExit)
return
}
func (trans *Transport) onConnect(conn *websocket.Conn) *websocket.Conn {
if trans.OnConnect != nil {
return trans.OnConnect(conn)
}
return conn
}
func (trans *Transport) onClose(conn *websocket.Conn) {
if trans.OnClose != nil {
trans.OnClose(conn)
}
}
func (trans *Transport) Transport(ctx context.Context, request []byte) ([]byte, error) {
conn, err := trans.getConn(ctx)
if err != nil {
return nil, err
}
return conn.Transport(ctx, request)
}
func (trans *Transport) Abort() {
trans.lock.Lock()
conns := trans.conns
trans.conns = make(map[string]*conn)
trans.lock.Unlock()
for _, conn := range conns {
conn.Close(core.ErrClosed)
}
}
type transportFactory struct {
schemes []string
}
func (factory transportFactory) Schemes() []string {
return factory.schemes
}
func (factory transportFactory) New() core.Transport {
transport := &Transport{
conns: make(map[string]*conn),
}
return transport
}
func RegisterTransport() {
core.RegisterTransport("websocket", transportFactory{[]string{"ws", "wss"}})
}