-
Notifications
You must be signed in to change notification settings - Fork 1
/
dialer_websocket.go
68 lines (56 loc) · 1.52 KB
/
dialer_websocket.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
package emissary
import (
"context"
"io"
"net"
"time"
"github.com/cockroachdb/errors"
"github.com/gorilla/websocket"
"github.com/rs/zerolog/log"
"go.encore.dev/emissary/internal/ws"
)
const HandshakeTimeout = 20 * time.Second
const PingTime = 30 * time.Second
// The websocket dialer is one way of accessing an Emissary server.
type websocketDialer struct {
address string
}
var _ transportDialer = (*websocketDialer)(nil)
func (w *websocketDialer) Dial(network, addr string) (c net.Conn, err error) {
return w.DialContext(context.Background(), network, addr)
}
func (w *websocketDialer) DialContext(ctx context.Context, network, _ string) (net.Conn, error) {
if network != "tcp" {
return nil, errors.New("tcp only supported")
}
// Dial the basic websocket
dialer := &websocket.Dialer{
HandshakeTimeout: HandshakeTimeout,
}
wsc, _, err := dialer.DialContext(ctx, w.address, nil)
if err != nil {
return nil, errors.Wrap(err, "unable to connect to the emissary websocket")
}
wsc.EnableWriteCompression(true)
// Wrap the websocket so it can be used like a net.Conn and return it
conn := ws.NewClient(wsc)
// Startup a background keep-alive so the socket doesn't close when there's no traffic
go func() {
t := time.NewTicker(PingTime)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if err := conn.SendPing(); err != nil {
if !errors.Is(err, io.EOF) {
log.Err(err).Msg("unable to send websocket keep-alive")
}
return
}
}
}
}()
return conn, nil
}