-
Notifications
You must be signed in to change notification settings - Fork 0
/
sessionstore.go
343 lines (312 loc) · 7.18 KB
/
sessionstore.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
package sessionstore
import (
"encoding/json"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/getblank/blank-sr/bdb"
"github.com/getblank/blank-sr/berror"
"github.com/getblank/uuid"
)
var (
bucket = "__sessions"
ttl = time.Hour * 24
sessions = map[string]*Session{}
locker sync.RWMutex
sessionUpdateHandlers = []func(*Session){}
sessionDeleteHandlers = []func(*Session){}
db = bdb.DB{}
)
// Session represents user session in Blank
type Session struct {
APIKey string `json:"apiKey"`
UserID string `json:"userId"`
Connections []*Conn `json:"connections"`
LastRequest time.Time `json:"lastRequest"`
V int `json:"__v"`
ttl time.Duration
sync.RWMutex
}
// Conn represents WAMP connection in session
type Conn struct {
ConnID string `json:"connId"`
Subscriptions map[string]interface{} `json:"subscriptions"`
}
// Init is the entrypoint of sessionstore
func Init() {
loadSessions()
go ttlWatcher()
}
// New created new user session. Optional bool param for creating session with 1 minute ttl
func New(userID string, tmp ...bool) *Session {
s := &Session{
uuid.NewV4(),
userID,
[]*Conn{},
time.Now(),
0,
0,
sync.RWMutex{},
}
if len(tmp) > 0 && tmp[0] {
s.ttl = time.Minute
}
s.LastRequest = time.Now()
locker.Lock()
defer locker.Unlock()
sessions[s.APIKey] = s
sessionUpdated(s, true)
return s
}
func DeleteAllConnections() {
locker.Lock()
defer locker.Unlock()
for _, s := range sessions {
s.Connections = []*Conn{}
s.Save(true)
}
}
// GetAll returns all stored sessions
func GetAll() []*Session {
result := make([]*Session, len(sessions))
var i int
locker.RLock()
defer locker.RUnlock()
for _, s := range sessions {
result[i] = s
i++
}
return result
}
// GetByAPIKey returns point to Session or error if it is not exists.
func GetByAPIKey(APIKey string) (s *Session, err error) {
return getByAPIKey(APIKey)
}
// GetByUserID returns point to Session or error if it is not exists.
func GetByUserID(id string) (s *Session, err error) {
return getByUserID(id)
}
// Delete removes session by the APIKey provided from store
func Delete(APIKey string) {
err := db.Delete(bucket, APIKey)
if err != nil {
log.Error("Can't delete session", APIKey, err.Error())
}
locker.Lock()
defer locker.Unlock()
s := sessions[APIKey]
delete(sessions, APIKey)
if s != nil {
sessionDeleted(s)
}
}
// DeleteAllForUser removes all sessions for user from store
func DeleteAllForUser(userID string) {
locker.RLock()
defer locker.RUnlock()
for _, s := range sessions {
if s.UserID == userID {
go s.Delete()
}
}
}
// AddSubscription adds subscription URI with provided params to user session
func (s *Session) AddSubscription(connID, uri string, extra interface{}) {
s.Lock()
defer s.Unlock()
var c *Conn
for _, _c := range s.Connections {
if _c.ConnID == connID {
c = _c
break
}
}
if c == nil {
c = new(Conn)
c.ConnID = connID
c.Subscriptions = map[string]interface{}{}
s.Connections = append(s.Connections, c)
}
c.Subscriptions[uri] = extra
sessionUpdated(s)
}
// DeleteConnection deletes WAMP connection from user session
func (s *Session) DeleteConnection(connID string) {
s.Lock()
defer s.Unlock()
for i, _c := range s.Connections {
if _c.ConnID == connID {
s.Connections = append(s.Connections[:i], s.Connections[i+1:]...)
break
}
}
sessionUpdated(s)
}
// DeleteSubscription deletes subscription from connection of user session
func (s *Session) DeleteSubscription(connID, uri string) {
s.Lock()
defer s.Unlock()
var c *Conn
for _, _c := range s.Connections {
if _c.ConnID == connID {
c = _c
break
}
}
if c == nil {
return
}
delete(c.Subscriptions, uri)
sessionUpdated(s)
}
// Delete removes Session from store
func (s *Session) Delete() {
err := db.Delete(bucket, s.APIKey)
if err != nil {
log.Error("Can't delete session", s, err.Error())
}
locker.Lock()
defer locker.Unlock()
delete(sessions, s.APIKey)
sessionDeleted(s)
}
// Save saves session in store and update LastRequest prop in it.
func (s *Session) Save(noLastRequestUpdate bool) {
if !noLastRequestUpdate {
s.LastRequest = time.Now()
}
s = copySession(s)
err := db.Save(bucket, s.APIKey, s)
if err != nil {
log.Error("Can't save session", s, err.Error())
}
}
// GetUserID returns userID stored in session
func (s *Session) GetUserID() string {
return s.UserID
}
// GetAPIKey returns apiKey of session
func (s *Session) GetAPIKey() string {
return s.APIKey
}
// OnSessionUpdate registers callback that will called when session updated
func OnSessionUpdate(handler func(*Session)) {
sessionUpdateHandlers = append(sessionUpdateHandlers, handler)
return
}
// OnSessionDelete registers callback that will called when session deleted
func OnSessionDelete(handler func(*Session)) {
sessionDeleteHandlers = append(sessionDeleteHandlers, handler)
return
}
func getByAPIKey(APIKey string) (s *Session, err error) {
locker.Lock()
defer locker.Unlock()
s, ok := sessions[APIKey]
if !ok {
return s, berror.DbNotFound
}
if s.ttl > 0 {
s.Lock()
defer s.Unlock()
s.ttl = 0
s.APIKey = uuid.NewV4()
sessions[s.APIKey] = s
delete(sessions, APIKey)
sessionUpdated(s)
}
return s, err
}
func getByUserID(id string) (s *Session, err error) {
locker.RLock()
defer locker.RUnlock()
for _, v := range sessions {
if v.UserID == id {
v.Lock()
defer v.Unlock()
return copySession(v), nil
}
}
return nil, berror.DbNotFound
}
func clearRottenSessions() {
locker.Lock()
defer locker.Unlock()
now := time.Now()
for _, s := range sessions {
if now.Sub(s.LastRequest) > ttl || (s.ttl > 0 && now.Sub(s.LastRequest) > s.ttl) {
err := db.Delete(bucket, s.APIKey)
if err != nil {
log.Error("Can't delete session", s, err.Error())
}
delete(sessions, s.APIKey)
}
}
}
func loadSessions() {
_sessions, err := db.GetAll(bucket)
if err != nil && err != berror.DbNotFound {
log.Error("Can't read all sessions", err.Error())
}
now := time.Now()
locker.Lock()
defer locker.Unlock()
for _, _s := range _sessions {
var s Session
err := json.Unmarshal(_s, &s)
if err != nil {
log.Error("Can't unmarshal session", _s, err.Error())
continue
}
if now.Sub(s.LastRequest) > ttl {
err := db.Delete(bucket, s.APIKey)
if err != nil {
log.Error("Can't delete session when Init()", s, err.Error())
}
continue
}
s.Connections = []*Conn{}
s.Save(true)
sessions[s.APIKey] = &s
}
}
func ttlWatcher() {
c := time.Tick(time.Minute)
for {
<-c
clearRottenSessions()
}
}
func sessionUpdated(s *Session, userUpdated ...bool) {
var b bool
if userUpdated != nil {
b = userUpdated[0]
}
s.Save(b)
_s := copySession(s)
if !b {
}
s.V++
for _, handler := range sessionUpdateHandlers {
go handler(_s)
}
}
func sessionDeleted(s *Session) {
s.V++
for _, handler := range sessionDeleteHandlers {
go handler(s)
}
}
func copySession(s *Session) *Session {
_s := *s
for i := range _s.Connections {
c := *_s.Connections[i]
subs := map[string]interface{}{}
for k, v := range c.Subscriptions {
subs[k] = v
}
c.Subscriptions = subs
_s.Connections[i] = &c
}
return &_s
}