forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.go
169 lines (144 loc) Β· 3.75 KB
/
socket.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
package server
import (
"context"
"errors"
"net/http"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/evcc-io/evcc/util"
)
const (
// Time allowed to write a message to the peer
socketWriteTimeout = 10 * time.Second
)
// socketSubscriber is a middleman between the websocket connection and the hub.
type socketSubscriber struct {
send chan []byte
closeSlow func()
}
func writeTimeout(ctx context.Context, timeout time.Duration, c *websocket.Conn, msg []byte) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return c.Write(ctx, websocket.MessageText, msg)
}
// SocketHub maintains the set of active clients and broadcasts messages to the
// clients.
type SocketHub struct {
mu sync.RWMutex
register chan *socketSubscriber
subscribers map[*socketSubscriber]struct{}
}
// NewSocketHub creates a web socket hub that distributes meter status and
// query results for the ui or other clients
func NewSocketHub() *SocketHub {
return &SocketHub{
register: make(chan *socketSubscriber, 1),
subscribers: make(map[*socketSubscriber]struct{}),
}
}
// ServeWebsocket handles websocket requests from the peer.
func (h *SocketHub) ServeWebsocket(w http.ResponseWriter, r *http.Request) {
acceptOptions := &websocket.AcceptOptions{
InsecureSkipVerify: true,
}
// https://github.com/nhooyr/websocket/issues/218
ua := strings.ToLower(r.Header.Get("User-Agent"))
if strings.Contains(ua, "safari") && !strings.Contains(ua, "chrome") && !strings.Contains(ua, "android") {
acceptOptions.CompressionMode = websocket.CompressionDisabled
}
conn, err := websocket.Accept(w, r, acceptOptions)
if err != nil {
log.ERROR.Println(err)
return
}
defer conn.Close(websocket.StatusInternalError, "")
err = h.subscribe(r.Context(), conn)
if errors.Is(err, context.Canceled) {
return
}
if cs := websocket.CloseStatus(err); cs == websocket.StatusNormalClosure || cs == websocket.StatusGoingAway {
return
}
if err != nil {
log.ERROR.Println(err)
return
}
}
func (h *SocketHub) subscribe(ctx context.Context, conn *websocket.Conn) error {
ctx = conn.CloseRead(ctx)
s := &socketSubscriber{
send: make(chan []byte, 1024),
closeSlow: func() {
conn.Close(websocket.StatusPolicyViolation, "connection too slow to keep up with messages")
},
}
h.addSubscriber(s)
defer h.deleteSubscriber(s)
// send welcome message
h.register <- s
for {
select {
case msg := <-s.send:
if err := writeTimeout(ctx, socketWriteTimeout, conn, msg); err != nil {
return err
}
case <-ctx.Done():
return ctx.Err()
}
}
}
// addSubscriber registers a subscriber.
func (h *SocketHub) addSubscriber(s *socketSubscriber) {
h.mu.Lock()
h.subscribers[s] = struct{}{}
h.mu.Unlock()
}
// deleteSubscriber deletes the given subscriber.
func (h *SocketHub) deleteSubscriber(s *socketSubscriber) {
h.mu.Lock()
delete(h.subscribers, s)
h.mu.Unlock()
}
func (h *SocketHub) welcome(subscriber *socketSubscriber, params []util.Param) {
var msg strings.Builder
msg.WriteString("{")
for _, p := range params {
if msg.Len() > 1 {
msg.WriteString(",")
}
msg.WriteString(kv(p))
}
msg.WriteString("}")
// should not block
subscriber.send <- []byte(msg.String())
}
func (h *SocketHub) broadcast(p util.Param) {
h.mu.RLock()
defer h.mu.RUnlock()
if len(h.subscribers) > 0 {
msg := "{" + kv(p) + "}"
for s := range h.subscribers {
select {
case s.send <- []byte(msg):
default:
s.closeSlow()
}
}
}
}
// Run starts data and status distribution
func (h *SocketHub) Run(in <-chan util.Param, cache *util.Cache) {
for {
select {
case client := <-h.register:
h.welcome(client, cache.All())
case msg, ok := <-in:
if !ok {
return // break if channel closed
}
h.broadcast(msg)
}
}
}