-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathstate.go
371 lines (309 loc) · 6.96 KB
/
state.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package server
import (
"log"
"sync"
"time"
"github.com/khlieng/dispatch/pkg/irc"
"github.com/khlieng/dispatch/pkg/session"
"github.com/khlieng/dispatch/storage"
)
const (
// AnonymousUserExpiration is the time to wait before removing an anonymous
// user that has no irc or websocket connections
AnonymousUserExpiration = 1 * time.Minute
)
// State is the live state of a single user
type State struct {
stateData
networks map[string]*storage.Network
pendingDCCSends map[string]*irc.DCCSend
ws map[string]*wsConn
broadcast chan WSResponse
srv *Dispatch
user *storage.User
expiration *time.Timer
reset chan time.Duration
lock sync.Mutex
}
func NewState(user *storage.User, srv *Dispatch) *State {
return &State{
stateData: stateData{m: map[string]interface{}{}},
networks: make(map[string]*storage.Network),
pendingDCCSends: make(map[string]*irc.DCCSend),
ws: make(map[string]*wsConn),
broadcast: make(chan WSResponse, 32),
srv: srv,
user: user,
expiration: time.NewTimer(AnonymousUserExpiration),
reset: make(chan time.Duration, 1),
}
}
func (s *State) network(host string) (*storage.Network, bool) {
s.lock.Lock()
n, ok := s.networks[host]
s.lock.Unlock()
return n, ok
}
func (s *State) client(host string) (*irc.Client, bool) {
if network, ok := s.network(host); ok {
return network.Client(), true
}
return nil, false
}
func (s *State) setNetwork(host string, network *storage.Network) {
s.lock.Lock()
s.networks[host] = network
s.lock.Unlock()
s.reset <- 0
}
func (s *State) deleteNetwork(host string) {
s.lock.Lock()
delete(s.networks, host)
s.lock.Unlock()
s.resetExpirationIfEmpty()
}
func (s *State) numIRC() int {
s.lock.Lock()
n := len(s.networks)
s.lock.Unlock()
return n
}
func (s *State) pendingDCC(filename string) (*irc.DCCSend, bool) {
s.lock.Lock()
pack, ok := s.pendingDCCSends[filename]
s.lock.Unlock()
return pack, ok
}
func (s *State) setPendingDCC(filename string, pack *irc.DCCSend) {
s.lock.Lock()
s.pendingDCCSends[filename] = pack
s.lock.Unlock()
}
func (s *State) deletePendingDCC(filename string) {
s.lock.Lock()
delete(s.pendingDCCSends, filename)
s.lock.Unlock()
}
func (s *State) setWS(addr string, w *wsConn) {
s.lock.Lock()
s.ws[addr] = w
s.lock.Unlock()
s.reset <- 0
}
func (s *State) deleteWS(addr string) {
s.lock.Lock()
delete(s.ws, addr)
s.lock.Unlock()
s.resetExpirationIfEmpty()
}
func (s *State) numWS() int {
s.lock.Lock()
n := len(s.ws)
s.lock.Unlock()
return n
}
func (s *State) sendJSON(t string, v interface{}) {
s.broadcast <- WSResponse{t, v}
}
func (s *State) sendLastMessages(network, channel string, count int) {
messages, hasMore, err := s.user.LastMessages(network, channel, count)
if err == nil && len(messages) > 0 {
res := Messages{
Network: network,
To: channel,
Messages: messages,
}
if hasMore {
res.Next = messages[0].ID
}
s.sendJSON("messages", res)
}
}
func (s *State) sendMessages(network, channel string, count int, fromID string) {
messages, hasMore, err := s.user.Messages(network, channel, count, fromID)
if err == nil && len(messages) > 0 {
res := Messages{
Network: network,
To: channel,
Messages: messages,
Prepend: true,
}
if hasMore {
res.Next = messages[0].ID
}
s.sendJSON("messages", res)
}
}
func (s *State) resetExpirationIfEmpty() {
if s.numIRC() == 0 && s.numWS() == 0 {
s.reset <- AnonymousUserExpiration
}
}
func (s *State) kill() {
s.lock.Lock()
for _, ws := range s.ws {
ws.conn.Close()
}
for _, network := range s.networks {
network.Client().Quit()
}
s.lock.Unlock()
}
func (s *State) run() {
for {
select {
case res := <-s.broadcast:
s.lock.Lock()
for _, ws := range s.ws {
ws.out <- res
}
s.lock.Unlock()
case <-s.expiration.C:
s.srv.states.delete(s.user.ID)
s.user.Remove()
return
case duration := <-s.reset:
if duration == 0 {
s.expiration.Stop()
} else {
s.expiration.Reset(duration)
}
}
}
}
type stateData struct {
m map[string]interface{}
lock sync.Mutex
}
func (s *stateData) Get(key string) interface{} {
s.lock.Lock()
v := s.m[key]
s.lock.Unlock()
return v
}
func (s *stateData) Set(key string, value interface{}) {
s.lock.Lock()
s.m[key] = value
s.lock.Unlock()
}
func (s *stateData) String(key string) string {
if v, ok := s.Get(key).(string); ok {
return v
}
return ""
}
func (s *stateData) Int(key string) int {
if v, ok := s.Get(key).(int); ok {
return v
}
return 0
}
func (s *stateData) Bool(key string) bool {
if v, ok := s.Get(key).(bool); ok {
return v
}
return false
}
type stateStore struct {
states map[uint64]*State
sessions map[string]*session.Session
sessionStore storage.SessionStore
lock sync.Mutex
}
func newStateStore(sessionStore storage.SessionStore) *stateStore {
store := &stateStore{
states: make(map[uint64]*State),
sessions: make(map[string]*session.Session),
sessionStore: sessionStore,
}
sessions, err := sessionStore.Sessions()
if err != nil {
log.Fatal(err)
}
log.Printf("[Init] %d sessions", len(sessions))
for _, session := range sessions {
if !session.Expired() {
store.sessions[session.Key()] = session
} else {
go sessionStore.DeleteSession(session.Key())
}
}
return store
}
func (s *stateStore) run() {
pruneSessions := time.Tick(time.Minute * 5)
for {
select {
case <-pruneSessions:
s.lock.Lock()
for key, session := range s.sessions {
if session.Expired() {
s.internalDeleteSession(key)
}
}
s.lock.Unlock()
}
}
}
func (s *stateStore) get(id uint64) *State {
s.lock.Lock()
state := s.states[id]
s.lock.Unlock()
return state
}
func (s *stateStore) set(state *State) {
s.lock.Lock()
s.states[state.user.ID] = state
s.lock.Unlock()
}
func (s *stateStore) delete(id uint64) {
s.lock.Lock()
delete(s.states, id)
for key, session := range s.sessions {
if session.UserID == id {
delete(s.sessions, key)
go s.sessionStore.DeleteSession(key)
}
}
s.lock.Unlock()
}
func (s *stateStore) getSession(key string) *session.Session {
s.lock.Lock()
session := s.sessions[key]
s.lock.Unlock()
return session
}
func (s *stateStore) setSession(session *session.Session) {
s.lock.Lock()
s.sessions[session.Key()] = session
s.lock.Unlock()
go s.sessionStore.SaveSession(session)
}
func (s *stateStore) deleteSession(key string) {
s.lock.Lock()
s.internalDeleteSession(key)
s.lock.Unlock()
}
func (s *stateStore) internalDeleteSession(key string) {
id := s.sessions[key].UserID
delete(s.sessions, key)
n := 0
for _, session := range s.sessions {
if session.UserID == id {
n++
}
}
state := s.states[id]
if n == 0 {
delete(s.states, id)
}
go func() {
if n == 0 {
// This anonymous user is not reachable anymore since all sessions have
// expired, so we clean it up
state.kill()
state.user.Remove()
}
s.sessionStore.DeleteSession(key)
}()
}