/
conn.go
189 lines (170 loc) · 3.91 KB
/
conn.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
package ws
import (
"context"
"fmt"
"io"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/apigear-io/objectlink-core-go/log"
"github.com/gorilla/websocket"
)
const (
// max message size in bytes
maxMessageSize = 512
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
sendWait = 3 * time.Second
)
var connId atomic.Int32
func nextConnId() string {
next := connId.Add(1)
return "c" + strconv.Itoa(int(next))
}
func Dial(ctx context.Context, url string) (*Connection, error) {
log.Debug().Msgf("dial: %s", url)
ws, _, err := websocket.DefaultDialer.DialContext(ctx, url, nil)
if err != nil {
return nil, fmt.Errorf("dial: %w", err)
}
log.Debug().Msgf("connected to: %s", url)
conn := NewConnection(ctx, ws)
return conn, nil
}
type Connection struct {
sync.RWMutex
id string
socket *websocket.Conn
in chan []byte
ctx context.Context
ctxCancel context.CancelFunc
out io.WriteCloser
closeHandlers []func()
}
func NewConnection(ctx context.Context, socket *websocket.Conn) *Connection {
ctx, cancel := context.WithCancel(ctx)
p := &Connection{
id: nextConnId(),
socket: socket,
in: make(chan []byte),
ctx: ctx,
ctxCancel: cancel,
}
socket.SetReadLimit(maxMessageSize)
socket.SetPongHandler(func(string) error {
deadline := time.Now().Add(pongWait)
log.Debug().Msgf("conn: handle pong %v", deadline)
return socket.SetReadDeadline(deadline)
})
socket.SetCloseHandler(func(code int, text string) error {
p.Close()
return nil
})
go p.WritePump()
go p.ReadPump()
return p
}
func (c *Connection) OnClosing(onClosing func()) {
c.Lock()
defer c.Unlock()
c.closeHandlers = append(c.closeHandlers, onClosing)
}
func (c *Connection) EmitClosing() {
c.RLock()
handlers := c.closeHandlers
c.RUnlock()
for _, h := range handlers {
h()
}
}
func (c *Connection) Close() error {
c.ctxCancel()
return nil
}
func (c *Connection) Id() string {
c.RLock()
defer c.RUnlock()
return c.id
}
func (c *Connection) Url() string {
c.RLock()
defer c.RUnlock()
return c.socket.RemoteAddr().String()
}
func (c *Connection) SetOutput(out io.WriteCloser) {
c.Lock()
c.out = out
c.Unlock()
}
func (c *Connection) WritePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
c.Close()
ticker.Stop()
log.Debug().Msgf("%s: exit write pump ", c.id)
}()
for {
select {
case <-c.ctx.Done():
log.Info().Msgf("%s: closing", c.id)
if c.out != nil {
c.out.Close()
}
c.socket.Close()
c.EmitClosing()
return
case <-ticker.C:
err := c.socket.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(sendWait))
if err != nil {
log.Error().Msgf("%s: write ping error: %v", c.id, err)
}
case bytes := <-c.in:
log.Debug().Msgf("%s: write: %s", c.id, string(bytes))
err := c.socket.SetWriteDeadline(time.Now().Add(sendWait))
if err != nil {
log.Error().Msgf("%s: set write deadline error: %v", c.id, err)
}
err = c.socket.WriteMessage(websocket.TextMessage, bytes)
if err != nil {
log.Error().Msgf("%s: write error: %v", c.id, err)
}
}
}
}
func (c *Connection) ReadPump() {
defer func() {
c.Close()
log.Debug().Msgf("%s: exit read pump ", c.id)
}()
for {
select {
case <-c.ctx.Done():
return
default:
c.socket.SetReadDeadline(time.Now().Add(pongWait))
_, bytes, err := c.socket.ReadMessage()
if err != nil {
log.Info().Msgf("%s: can not read: %v", c.id, err)
return
}
c.RLock()
out := c.out
c.RUnlock()
if out == nil {
log.Debug().Msgf("%s: no output", c.id)
continue
}
_, err = out.Write(bytes)
if err != nil {
log.Debug().Msgf("%s: write error: %v", c.id, err)
}
}
}
}
func (c *Connection) Write(bytes []byte) (int, error) {
c.in <- bytes
return len(bytes), nil
}