/
room_registry.go
87 lines (75 loc) · 1.99 KB
/
room_registry.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
package kecpsignal
import kchan "github.com/fourdim/kecp/modules/kecp-channel"
type Registry struct {
rooms map[string]*Room
// register is written by the rooms
register *kchan.Channel[*Room]
// unregister is written by the rooms
unregister *kchan.Channel[*Room]
// roomQuery is written by the clients
roomQuery *kchan.Channel[*roomQuery]
// roomDeletionRequest
roomDeletionRequest chan *roomDeletion
}
func NewRegistry() *Registry {
reg := &Registry{
rooms: make(map[string]*Room),
register: kchan.New[*Room](),
unregister: kchan.New[*Room](),
roomQuery: kchan.New[*roomQuery](),
roomDeletionRequest: make(chan *roomDeletion),
}
go reg.run()
return reg
}
func (reg *Registry) run() {
// Only this goroutine can access
// Registry.rooms
for {
select {
case room := <-reg.register.Read():
reg.rooms[room.RoomID] = room
room.created <- true
case room := <-reg.unregister.Read():
if _, ok := reg.rooms[room.RoomID]; ok {
delete(reg.rooms, room.RoomID)
room.broadcast.Close()
room.register.Close()
room.unregister.Close()
close(room.created)
close(room.selfDestruction)
}
case roomQuery := <-reg.roomQuery.Read():
if room, ok := reg.rooms[roomQuery.roomID]; ok {
roomQuery.room <- room
} else {
roomQuery.room <- nil
}
close(roomQuery.room)
case roomDele := <-reg.roomDeletionRequest:
if room, ok := reg.rooms[roomDele.roomID]; ok && room.MgtKey == roomDele.mgtKey {
room.selfDestruction <- true
}
}
}
}
type roomQuery struct {
roomID string
room chan *Room
}
func (reg *Registry) GetRoom(roomID string) *Room {
roomQuery := &roomQuery{
roomID: roomID,
room: make(chan *Room),
}
reg.roomQuery.Write(roomQuery)
room := <-roomQuery.room
return room
}
type roomDeletion struct {
roomID string
mgtKey string
}
func (reg *Registry) DeleteRoom(roomID string, managementKey string) {
reg.roomDeletionRequest <- &roomDeletion{roomID: roomID, mgtKey: managementKey}
}