-
Notifications
You must be signed in to change notification settings - Fork 2
/
session.go
320 lines (250 loc) · 6.85 KB
/
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
package models
import (
"context"
"fmt"
"sync"
"time"
"github.com/aukilabs/go-tooling/pkg/logs"
hwebsocket "github.com/aukilabs/hagall-common/websocket"
"github.com/google/uuid"
)
// Session represents a session that contains entities and participants who can
// communicate between each other.
type Session struct {
ID uint32
SessionUUID string
AppKey string
participantIDs SequentialIDGenerator
participantMutex sync.RWMutex
participants map[uint32]*Participant
entityIDs SequentialIDGenerator
entityMutex sync.RWMutex
entities map[uint32]*Entity
moduleStates map[string]any
moduleMutex sync.RWMutex
startFrameOnce sync.Once
closeFrameChan chan struct{}
frameTicker *time.Ticker
frameHandlerIDs SequentialIDGenerator
frameHandlers map[uint32]func()
frameMutex sync.RWMutex
entityComponents *EntityComponentStore
closeOnce sync.Once
}
func NewSession(id uint32, frameDuration time.Duration) *Session {
return &Session{
ID: id,
SessionUUID: uuid.New().String(),
closeFrameChan: make(chan struct{}, 1),
frameTicker: time.NewTicker(frameDuration),
participants: make(map[uint32]*Participant),
entities: make(map[uint32]*Entity),
moduleStates: make(map[string]any),
frameHandlers: make(map[uint32]func()),
entityComponents: newEntityComponentStore(),
}
}
func (s *Session) Close() {
s.closeOnce.Do(func() {
s.frameTicker.Stop()
s.closeFrameChan <- struct{}{}
})
}
func (s *Session) NewParticipantID() uint32 {
return s.participantIDs.New()
}
func (s *Session) AddParticipant(p *Participant) {
s.participantMutex.Lock()
defer s.participantMutex.Unlock()
s.participants[p.ID] = p
}
func (s *Session) RemoveParticipant(p *Participant) {
s.participantMutex.Lock()
defer s.participantMutex.Unlock()
delete(s.participants, p.ID)
}
func (s *Session) GetParticipants() []*Participant {
s.participantMutex.RLock()
defer s.participantMutex.RUnlock()
participants := make([]*Participant, 0, len(s.participants))
for _, p := range s.participants {
participants = append(participants, p)
}
return participants
}
func (s *Session) GetParticipantsByIDs(ids ...uint32) []*Participant {
s.participantMutex.RLock()
defer s.participantMutex.RUnlock()
participants := make([]*Participant, 0, len(ids))
for _, id := range ids {
p, ok := s.participants[id]
if ok {
participants = append(participants, p)
}
}
return participants
}
func (s *Session) ParticipantCount() int {
s.participantMutex.RLock()
defer s.participantMutex.RUnlock()
return len(s.participants)
}
func (s *Session) NewEntityID() uint32 {
return s.entityIDs.New()
}
func (s *Session) AddEntity(e *Entity) {
s.entityMutex.Lock()
defer s.entityMutex.Unlock()
s.entities[e.ID] = e
}
func (s *Session) RemoveEntity(e *Entity) {
s.entityMutex.Lock()
defer s.entityMutex.Unlock()
delete(s.entities, e.ID)
}
func (s *Session) EntityByID(id uint32) (*Entity, bool) {
s.entityMutex.RLock()
defer s.entityMutex.RUnlock()
e, ok := s.entities[id]
return e, ok
}
func (s *Session) Entities() []*Entity {
s.entityMutex.RLock()
defer s.entityMutex.RUnlock()
entities := make([]*Entity, 0, len(s.entities))
for _, e := range s.entities {
entities = append(entities, e)
}
return entities
}
func (s *Session) Broadcast(sender *Participant, protoMsg hwebsocket.ProtoMsg) {
s.participantMutex.RLock()
defer s.participantMutex.RUnlock()
msg, err := hwebsocket.MsgFromProto(protoMsg)
if err != nil {
logs.WithTag("message", protoMsg).Debug(err)
return
}
for _, p := range s.participants {
if p == sender {
continue
}
p.Responder.SendMsg(msg)
}
}
func (s *Session) BroadcastTo(sender *Participant, protoMsg hwebsocket.ProtoMsg, participantIds ...uint32) {
participants := s.GetParticipantsByIDs(participantIds...)
isParticipantHandled := make(map[uint32]struct{}, len(participantIds))
msg, err := hwebsocket.MsgFromProto(protoMsg)
if err != nil {
logs.WithTag("message", protoMsg).Debug(err)
return
}
for _, p := range participants {
if p == sender {
continue
}
if _, ok := isParticipantHandled[p.ID]; ok {
continue
}
isParticipantHandled[p.ID] = struct{}{}
p.Responder.SendMsg(msg)
}
}
func (s *Session) SetModuleState(moduleName string, state any) {
s.moduleMutex.Lock()
defer s.moduleMutex.Unlock()
s.moduleStates[moduleName] = state
}
func (s *Session) ModuleState(moduleName string) (any, bool) {
s.moduleMutex.RLock()
defer s.moduleMutex.RUnlock()
state, ok := s.moduleStates[moduleName]
return state, ok
}
func (s *Session) HandleFrame(h func()) (cancel func()) {
s.frameMutex.Lock()
defer s.frameMutex.Unlock()
id := s.frameHandlerIDs.New()
s.frameHandlers[id] = h
return func() {
s.frameMutex.Lock()
defer s.frameMutex.Unlock()
delete(s.frameHandlers, id)
s.frameHandlerIDs.Reuse(id)
}
}
func (s *Session) StartDispatchFrames() {
s.startFrameOnce.Do(func() {
for {
select {
case <-s.closeFrameChan:
return
case <-s.frameTicker.C:
s.frameMutex.RLock()
for _, h := range s.frameHandlers {
h()
}
s.frameMutex.RUnlock()
}
}
})
}
func (s *Session) GetEntityComponents() *EntityComponentStore {
return s.entityComponents
}
type SessionStore struct {
// The session discovery service where sessions are registered.
DiscoveryService SessionDiscoveryService
initOnce sync.Once
mutex sync.RWMutex
sessions map[string]*Session
ids SequentialIDGenerator
}
func (s *SessionStore) init() {
s.sessions = map[string]*Session{}
if s.DiscoveryService == nil {
s.DiscoveryService = defaultSessionDiscoveryService{}
}
}
func (s *SessionStore) NewID() uint32 {
return s.ids.New()
}
func (s *SessionStore) Add(ctx context.Context, session *Session) error {
s.initOnce.Do(s.init)
s.mutex.Lock()
defer s.mutex.Unlock()
s.sessions[s.GlobalSessionID(session.ID)] = session
instrumentIncreaseSessionGauge(session.AppKey)
instrumentCountSession(session.AppKey)
return nil
}
func (s *SessionStore) Remove(ctx context.Context, session *Session) {
s.initOnce.Do(s.init)
s.mutex.Lock()
defer s.mutex.Unlock()
delete(s.sessions, s.GlobalSessionID(session.ID))
session.Close()
s.ids.Reuse(session.ID)
instrumentDecreaseSessionGauge(session.AppKey)
}
func (s *SessionStore) GetByGlobalID(v string) (*Session, bool) {
s.initOnce.Do(s.init)
s.mutex.RLock()
defer s.mutex.RUnlock()
session, ok := s.sessions[v]
return session, ok
}
func (s *SessionStore) GlobalSessionID(sessionID uint32) string {
return fmt.Sprintf("%sx%x", s.DiscoveryService.ServerID(), sessionID)
}
// SessionDiscoveryService is the interface to communicate with a session discovery
// service such as HDS.
type SessionDiscoveryService interface {
// Returns the id attributed to the current Hagall server.
ServerID() string
}
type defaultSessionDiscoveryService struct{}
func (s defaultSessionDiscoveryService) ServerID() string {
return "ted"
}