-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathwebsocket_push_session.go
331 lines (272 loc) · 8.85 KB
/
websocket_push_session.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
// Copyright 2019 Aporeto Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bahamut
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"net/url"
"sync"
"time"
"github.com/gofrs/uuid"
"github.com/gorilla/websocket"
"go.aporeto.io/elemental"
"go.aporeto.io/wsc"
"go.uber.org/zap"
)
const (
// enableErrorsQueryParam contains the name of the query parameter that can be passed in by the client to declare that
// it can handle error events
enableErrorsQueryParam = "enableErrors"
)
type unregisterFunc func(*wsPushSession)
type wsPushSession struct {
parametersLock sync.RWMutex
startTime time.Time
errorStateLock sync.RWMutex
currentPushConfigLock sync.RWMutex
metadata any
ctx context.Context
conn wsc.Websocket
dataCh chan []byte
unregister unregisterFunc
pushConfig *elemental.PushConfig
closeCh chan struct{}
claimsMap map[string]string
parameters url.Values
cancel context.CancelFunc
headers http.Header
tlsConnectionState *tls.ConnectionState
encodingWrite elemental.EncodingType
remoteAddr string
id string
encodingRead elemental.EncodingType
claims []string
cookies []*http.Cookie
cfg config
errorStateActive bool
}
func newWSPushSession(
request *http.Request,
cfg config,
unregister unregisterFunc,
encodingRead elemental.EncodingType,
encodingWrite elemental.EncodingType,
) *wsPushSession {
id := uuid.Must(uuid.NewV4()).String()
ctx, cancel := context.WithCancel(request.Context())
return &wsPushSession{
dataCh: make(chan []byte, 64),
id: id,
claims: []string{},
claimsMap: map[string]string{},
cfg: cfg,
headers: request.Header,
parameters: request.URL.Query(),
startTime: time.Now(),
closeCh: make(chan struct{}),
unregister: unregister,
ctx: ctx,
cancel: cancel,
tlsConnectionState: request.TLS,
remoteAddr: request.RemoteAddr,
encodingRead: encodingRead,
encodingWrite: encodingWrite,
}
}
func (s *wsPushSession) DirectPush(events ...*elemental.Event) {
for _, event := range events {
if event.Timestamp.Before(s.startTime) {
continue
}
f := s.currentPushConfig()
if f != nil && f.IsFilteredOut(event.Identity, event.Type) {
continue
}
// We convert the inner Entity to the requested encoding. We don't need additional
// check as elemental.Convert will do anything if the EncodingTypes are identical.
if err := event.Convert(s.encodingWrite); err != nil {
zap.L().Error("Unable to convert event",
zap.Stringer("event", event),
zap.Error(err),
)
continue
}
data, err := elemental.Encode(s.encodingWrite, event)
if err != nil {
zap.L().Error("Unable to encode event",
zap.Stringer("event", event),
zap.Error(err),
)
continue
}
s.send(data)
}
}
func (s *wsPushSession) String() string {
return fmt.Sprintf("<pushsession id:%s>", s.id)
}
// SetClaims implements elemental.ClaimsHolder.
func (s *wsPushSession) SetClaims(claims []string) {
s.claims = append([]string{}, claims...)
s.claimsMap = claimsToMap(s.claims)
}
func (s *wsPushSession) ClaimsMap() map[string]string {
copiedClaimsMap := map[string]string{}
for k, v := range s.claimsMap {
copiedClaimsMap[k] = v
}
return copiedClaimsMap
}
func (s *wsPushSession) Identifier() string { return s.id }
func (s *wsPushSession) Claims() []string { return append([]string{}, s.claims...) }
func (s *wsPushSession) Token() string { return s.Parameter("token") }
func (s *wsPushSession) Context() context.Context { return s.ctx }
func (s *wsPushSession) TLSConnectionState() *tls.ConnectionState { return s.tlsConnectionState }
func (s *wsPushSession) Metadata() any { return s.metadata }
func (s *wsPushSession) SetMetadata(m any) { s.metadata = m }
func (s *wsPushSession) ClientIP() string { return s.remoteAddr }
func (s *wsPushSession) setRemoteAddress(addr string) { s.remoteAddr = addr }
func (s *wsPushSession) setConn(conn wsc.Websocket) { s.conn = conn }
func (s *wsPushSession) close(code int) { s.conn.Close(code) }
func (s *wsPushSession) setTLSConnectionState(st *tls.ConnectionState) { s.tlsConnectionState = st }
func (s *wsPushSession) Header(key string) string { return s.headers.Get(key) }
func (s *wsPushSession) PushConfig() *elemental.PushConfig { return s.currentPushConfig() }
func (s *wsPushSession) Parameter(key string) string {
s.parametersLock.RLock()
defer s.parametersLock.RUnlock()
return s.parameters.Get(key)
}
func (s *wsPushSession) inErrorState() bool {
s.errorStateLock.RLock()
defer s.errorStateLock.RUnlock()
return s.errorStateActive
}
func (s *wsPushSession) setErrorState(on bool) {
s.errorStateLock.Lock()
defer s.errorStateLock.Unlock()
s.errorStateActive = on
}
func (s *wsPushSession) handlesErrorEvents() bool {
_, ok := s.parameters[enableErrorsQueryParam]
return ok
}
func (s *wsPushSession) sendWSError(ee elemental.Error) {
s.setErrorState(true)
msgpack, json, err := prepareEventData(elemental.NewErrorEvent(ee, s.encodingWrite))
if err != nil {
zap.L().Error("elemental: unable to prepare error event - closing socket",
zap.String("sessionID", s.id),
zap.Error(err))
s.close(websocket.CloseInternalServerErr)
return
}
switch s.encodingWrite {
case elemental.EncodingTypeMSGPACK:
s.send(msgpack)
case elemental.EncodingTypeJSON:
s.send(json)
}
}
func (s *wsPushSession) currentPushConfig() *elemental.PushConfig {
s.currentPushConfigLock.RLock()
defer s.currentPushConfigLock.RUnlock()
if s.pushConfig == nil {
return nil
}
return s.pushConfig.Duplicate()
}
func (s *wsPushSession) setCurrentPushConfig(f *elemental.PushConfig) {
s.currentPushConfigLock.Lock()
defer s.currentPushConfigLock.Unlock()
s.pushConfig = f
if f == nil {
return
}
s.parametersLock.Lock()
for k, v := range f.Parameters() {
s.parameters[k] = v
}
s.parametersLock.Unlock()
}
func (s *wsPushSession) Cookie(name string) (*http.Cookie, error) {
for _, cookie := range s.cookies {
if cookie.Name == name {
return cookie, nil
}
}
return nil, http.ErrNoCookie
}
// send sends the given bytes as is, with no
// additional checks.
func (s *wsPushSession) send(data []byte) {
select {
case s.dataCh <- data:
default:
zap.L().Warn("Slow consumer. event dropped",
zap.String("sessionID", s.id),
zap.Strings("claims", s.claims),
)
}
}
func (s *wsPushSession) listen() {
defer s.unregister(s)
for {
select {
case data := <-s.dataCh:
s.conn.Write(data)
case data := <-s.conn.Read():
pushConfig := elemental.NewPushConfig()
if err := elemental.Decode(s.encodingRead, data, pushConfig); err != nil {
if !s.handlesErrorEvents() {
s.close(websocket.CloseUnsupportedData)
return
}
s.sendWSError(elemental.Error{
Title: "Bad request",
Subject: "bahamut",
Description: fmt.Sprintf("could not decode message into %T: %s", pushConfig, err),
})
continue
}
if err := pushConfig.ParseIdentityFilters(); err != nil {
zap.L().Debug("error parsing filter(s) in the received *elemental.PushConfig",
zap.Error(err),
zap.String("sessionID", s.id),
zap.String("pushConfig", pushConfig.String()),
)
if !s.handlesErrorEvents() {
s.close(websocket.CloseUnsupportedData)
return
}
s.sendWSError(elemental.Error{
Title: "Bad request",
Subject: "bahamut",
Description: fmt.Sprintf("unable to parse identity filters: %s", err),
Data: map[string]any{
"pushconfig": "filters",
},
})
continue
}
s.setErrorState(false)
s.setCurrentPushConfig(pushConfig)
case err := <-s.conn.Error():
zap.L().Error("Error received from websocket", zap.String("session", s.id), zap.Error(err))
case <-s.conn.Done():
return
case <-s.ctx.Done():
s.close(websocket.CloseGoingAway)
return
}
}
}