-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
514 lines (446 loc) · 12.6 KB
/
connection.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
package cri
import (
"crypto/tls"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
"github.com/mitchellh/mapstructure"
)
// DefaultAddress for remote debugging protocol
const DefaultAddress = "127.0.0.1:9222"
// DefaultEventTimeout specifies default duration to receive an event
const DefaultEventTimeout = 10 * time.Second
// DefaultCommandTimeout specifies default duration to receive command response
const DefaultCommandTimeout = 10 * time.Second
const maxIntValue = 1<<31 - 1
// ConnectionOption defines a function type to set values of ConnectionOptions
type ConnectionOption func(*ConnectionOptions)
// ConnectionOptions defines connection parameters
type ConnectionOptions struct {
// Address of remote devtools instance, default used is DefaultAddress
Address string
// TargetID of target to connect
TargetID string
// SocketAddress of target to connect
SocketAddress string
// TLSClientConfig specifies TLS configuration to use
TLSConfig *tls.Config
// EventTimeout specifies duration to receive an event, default used is DefaultEventTimeout
EventTimeout time.Duration
// CommandTimeout specifies duration to receive command response, default used is DefaultCommandTimeout
CommandTimeout time.Duration
// Logger if provided is used to print errors from connection reader.
Logger *log.Logger
}
// option iterates over all arguments to set final options
func (co *ConnectionOptions) option(opts ...ConnectionOption) {
for i := 0; i < len(opts); i++ {
opts[i](co)
}
}
// SetAddress sets remote address for connection
func SetAddress(addr string) ConnectionOption {
return func(co *ConnectionOptions) {
co.Address = addr
}
}
// SetSocketAddress sets target websocket connection address
func SetSocketAddress(addr string) ConnectionOption {
return func(co *ConnectionOptions) {
co.SocketAddress = addr
}
}
// SetTargetID sets target for connection
func SetTargetID(targetID string) ConnectionOption {
return func(co *ConnectionOptions) {
co.TargetID = targetID
}
}
// SetTLSConfig sets tls config for connection
func SetTLSConfig(config *tls.Config) ConnectionOption {
return func(co *ConnectionOptions) {
co.TLSConfig = config
}
}
// SetEventTimeout sets eventTimeout for connection
func SetEventTimeout(timeout time.Duration) ConnectionOption {
return func(co *ConnectionOptions) {
co.EventTimeout = timeout
}
}
// SetCommandTimeout sets commandTimeout for connection
func SetCommandTimeout(timeout time.Duration) ConnectionOption {
return func(co *ConnectionOptions) {
co.CommandTimeout = timeout
}
}
// SetLogger sets logging for connection
func SetLogger(logger *log.Logger) ConnectionOption {
return func(co *ConnectionOptions) {
co.Logger = logger
}
}
type commandsStore struct {
sync.RWMutex
commands map[int32]commandRequest
}
func (cs *commandsStore) addCommand(cmd commandRequest) {
cs.Lock()
defer cs.Unlock()
if cs.commands == nil {
cs.commands = make(map[int32]commandRequest)
}
cs.commands[cmd.ID] = cmd
}
func (cs *commandsStore) deleteCommand(id int32) {
cs.Lock()
defer cs.Unlock()
if cs.commands != nil {
delete(cs.commands, id)
}
}
func (cs *commandsStore) getCommand(id int32) (commandRequest, bool) {
cs.RLock()
defer cs.RUnlock()
if cs.commands != nil {
if val, ok := cs.commands[id]; ok {
return val, ok
}
}
return commandRequest{}, false
}
type eventsStore struct {
sync.RWMutex
events map[string]map[eventRequest]bool
}
func (es *eventsStore) addEvent(ereq eventRequest) {
es.Lock()
defer es.Unlock()
if es.events == nil {
es.events = make(map[string]map[eventRequest]bool)
}
if _, ok := es.events[ereq.Method]; !ok {
es.events[ereq.Method] = make(map[eventRequest]bool)
}
es.events[ereq.Method][ereq] = true
}
func (es *eventsStore) deleteEvent(ereq eventRequest) {
es.Lock()
defer es.Unlock()
if es.events == nil {
return
}
if _, ok := es.events[ereq.Method]; !ok {
return
}
delete(es.events[ereq.Method], ereq)
}
func (es *eventsStore) forEvents(cmd string, fn func(eventRequest)) {
es.RLock()
defer es.RUnlock()
if es.events == nil {
return
}
if _, ok := es.events[cmd]; !ok {
return
}
for eve := range es.events[cmd] {
go fn(eve)
}
}
// Connection contains socket connection to remote target. Its safe to share
// same instance among multiple goroutines.
type Connection struct {
addr, wsAddr string
tlsConfig *tls.Config
eventTimeout, cmdTimeout time.Duration
conn *websocket.Conn
reqChn chan commandRequest
closeChn chan struct{}
commands commandsStore
events eventsStore
counter int32
log *log.Logger
}
// NewConnection creates a connection to remote target. Connection options can be
// given in arguments using SetAddress, SetTargetID, SetSocketAddress etc.
// To see all options check ConnectionOptions.
//
// When no arguments are provided, connection is created using DefaultAddress.
// If TargetID is provided, connection looks for remote target and connects to it.
// If SocketAddress is provided then Address and TargetID are ignored.
func NewConnection(opts ...ConnectionOption) (*Connection, error) {
opt := &ConnectionOptions{
Address: DefaultAddress,
EventTimeout: DefaultEventTimeout,
CommandTimeout: DefaultCommandTimeout,
}
opt.option(opts...)
instance := &Connection{
eventTimeout: opt.EventTimeout,
cmdTimeout: opt.CommandTimeout,
tlsConfig: opt.TLSConfig,
reqChn: make(chan commandRequest),
closeChn: make(chan struct{}),
log: opt.Logger,
}
if len(opt.SocketAddress) != 0 {
parsedAddr, addrParseErr := url.Parse(opt.SocketAddress)
if addrParseErr != nil {
return nil, addrParseErr
}
instance.wsAddr = parsedAddr.String()
instance.addr = parsedAddr.Host
} else {
targets, targetsErr := GetTargets(opts...)
if targetsErr != nil {
return nil, targetsErr
}
wsAddr := targets[0].WebSocketDebuggerURL
if len(opt.TargetID) != 0 {
for i := range targets {
if targets[i].ID == opt.TargetID {
wsAddr = targets[i].WebSocketDebuggerURL
break
}
}
}
instance.wsAddr = wsAddr
instance.addr = opt.Address
}
dialer := &websocket.Dialer{TLSClientConfig: instance.tlsConfig}
conn, res, resErr := dialer.Dial(instance.wsAddr, nil)
if resErr != nil {
return nil, resErr
}
if res.StatusCode != 101 {
return nil, errors.New("Invalid status code")
}
instance.conn = conn
go instance.reader()
go instance.writer()
return instance, nil
}
type commandResponse struct {
ID int32 `json:"id"` // id of the command request or 0 in case of event
Method string `json:"method"` // command or event name
Result map[string]interface{} `json:"result"` // parameters returned for command
Error *struct {
Message string `json:"message"`
Code int `json:"code"`
} `json:"error"` // error returned for command
Params map[string]interface{} `json:"params"` // parameters returned for event
}
type commandRequest struct {
ID int32 `json:"id"` // id of the command request, should be greater than 0
Method string `json:"method"` // method takes the command to be sent
Params interface{} `json:"params"` // params contains parameters taken by command
resChn chan commandResponse
errChn chan error
timeoutTimer *time.Timer
}
// Send writes command and associated parameters to underlying connection.
// It waits for command response and decodes it in response argument.
// Timeout error is returned if response is not received.
func (c *Connection) Send(command string, request, response interface{}) error {
cmd := commandRequest{
ID: c.id(),
Method: command,
Params: request,
resChn: make(chan commandResponse, 1),
errChn: make(chan error, 1),
timeoutTimer: time.NewTimer(c.cmdTimeout),
}
c.commands.addCommand(cmd)
defer func() {
c.commands.deleteCommand(cmd.ID)
}()
if cmd.Params == nil {
cmd.Params = struct{}{}
}
c.reqChn <- cmd
select {
case cmdRes := <-cmd.resChn:
cmd.timeoutTimer.Stop()
if response == nil {
return nil
}
return mapstructure.Decode(cmdRes.Result, response)
case resErr := <-cmd.errChn:
cmd.timeoutTimer.Stop()
return resErr
case <-cmd.timeoutTimer.C:
return errors.New("command response timeout")
}
}
type eventRequest struct {
Method string
eventChn chan commandResponse
}
// On listens for subscribed event. It takes event name and a non nil channel as arguments.
// It returns a function, which blocks current routine till channel is closed.
// When event is received, parameters are decoded in params argument or error is returned.
func (c *Connection) On(event string, closeChn chan struct{}) func(params interface{}) error {
eve := eventRequest{
Method: event,
eventChn: make(chan commandResponse, 1),
}
c.events.addEvent(eve)
defer func() {
go func() {
<-closeChn
c.events.deleteEvent(eve)
}()
}()
return func(params interface{}) error {
res := <-eve.eventChn
if params != nil {
return mapstructure.Decode(res.Params, params)
}
return nil
}
}
// Close stops websocket connection.
func (c *Connection) Close() error {
close(c.closeChn)
if closeErr := c.conn.Close(); closeErr != nil {
return closeErr
}
return nil
}
func (c *Connection) id() int32 {
if atomic.CompareAndSwapInt32(&c.counter, maxIntValue, 1) {
return 1
} else {
return atomic.AddInt32(&c.counter, 1)
}
}
func (c *Connection) writer() {
for {
select {
case <-c.closeChn:
return
case req := <-c.reqChn:
if writeErr := c.conn.WriteJSON(req); writeErr != nil {
req.errChn <- writeErr
}
}
}
}
func (c *Connection) reader() {
for {
select {
case <-c.closeChn:
// TODO cleanup events and commands after shutdown
// any pending command or event should should raise
// shutting down error.
return
default:
var data commandResponse
if decodeErr := c.conn.ReadJSON(&data); decodeErr != nil {
if c.log != nil {
c.log.Println(decodeErr.Error())
}
}
if data.ID > 0 {
if cmd, ok := c.commands.getCommand(data.ID); ok {
if data.Error != nil {
cmd.errChn <- errors.New(data.Error.Message)
} else {
cmd.resChn <- data
}
}
} else if len(data.Method) > 0 {
c.events.forEvents(data.Method, func(val eventRequest) {
val.eventChn <- data
})
}
}
}
}
// VersionResponse contains fields received in response to version query.
type VersionResponse struct {
Browser string `json:"Browser"`
ProtocolVersion string `json:"Protocol-Version"`
UserAgent string `json:"User-Agent"`
V8Version string `json:"V8-Version"`
WebKitVersion string `json:"WebKit-Version"`
WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
}
// GetVersion fetches the protocol version of remote
func GetVersion(opts ...ConnectionOption) (VersionResponse, error) {
opt := &ConnectionOptions{
Address: DefaultAddress,
}
opt.option(opts...)
client := &http.Client{}
if opt.TLSConfig != nil {
client.Transport = &http.Transport{
TLSClientConfig: opt.TLSConfig,
}
}
var data VersionResponse
res, resErr := client.Get(getAddress(opt) + "/json/version")
if resErr != nil {
return data, resErr
}
if res.StatusCode != 200 {
return data, errors.New("Invalid status code")
}
if decodeErr := json.NewDecoder(res.Body).Decode(&data); decodeErr != nil {
return data, decodeErr
}
return data, nil
}
// Targets represent a list of connectable remotes
type Targets []struct {
Description string `json:"description"`
DevtoolsFrontendURL string `json:"devtoolsFrontendUrl"`
ID string `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
URL string `json:"url"`
WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
}
// GetTargets retreives targets in remote connection
func GetTargets(opts ...ConnectionOption) (Targets, error) {
opt := &ConnectionOptions{
Address: DefaultAddress,
}
opt.option(opts...)
client := &http.Client{}
if opt.TLSConfig != nil {
client.Transport = &http.Transport{
TLSClientConfig: opt.TLSConfig,
}
}
var data Targets
res, resErr := client.Get(getAddress(opt) + "/json/list")
if resErr != nil {
return data, resErr
}
if res.StatusCode != 200 {
return data, errors.New("Invalid status code")
}
if decodeErr := json.NewDecoder(res.Body).Decode(&data); decodeErr != nil {
return data, decodeErr
}
if len(data) < 1 {
return data, errors.New("No valid targets")
}
return data, nil
}
// getAddress adds https if tls config is present
func getAddress(opts *ConnectionOptions) string {
if opts.TLSConfig != nil {
return "https://" + opts.Address
} else {
return "http://" + opts.Address
}
}