-
Notifications
You must be signed in to change notification settings - Fork 3
/
room.go
185 lines (161 loc) · 4.63 KB
/
room.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
package ayu
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-redis/redis/v8"
)
const (
roomMaxMembers = 2
roomLockExpiration = 30 * time.Second
)
type roomMessageType string
const (
roomMessageTypeForward roomMessageType = "forward"
roomMessageTypeJoin roomMessageType = "join"
roomMessageTypeLeave roomMessageType = "leave"
)
var (
errRoomIsFull = errors.New("room is full")
)
type roomMessage struct {
Sender ClientID `json:"sender"`
Type roomMessageType `json:"type"`
Payload string `json:"payload"`
}
func redisRoomMembersKey(roomID RoomID) string {
return fmt.Sprintf("ayu:room:members:%s", roomID)
}
func redisRoomLockKey(roomID RoomID) string {
return fmt.Sprintf("ayu:room:lock:%s", roomID)
}
type roomLock struct {
roomID RoomID
mu *redisMutex
logger Logger
}
func newRoomLock(mu *redisMutex, roomID RoomID, logger Logger) *roomLock {
return &roomLock{
roomID: roomID,
mu: mu,
logger: logger,
}
}
func (l *roomLock) Unlock() {
if err := l.mu.Unlock(); err != nil {
l.logger.Errorf("failed to unlock room (room: %s): %+v", l.roomID, err)
}
}
type redisRoomManager struct {
client *redis.Client
logger Logger
roomExpiration time.Duration
}
func newRedisRoomManager(client *redis.Client, logger Logger, roomExpiration time.Duration) *redisRoomManager {
return &redisRoomManager{
client: client,
logger: logger,
roomExpiration: roomExpiration,
}
}
func (m *redisRoomManager) JoinRoom(ctx context.Context, roomID RoomID, clientID ClientID) (bool, error) {
numClients, err := m.CountClients(ctx, roomID)
if err != nil {
return false, err
}
if numClients >= roomMaxMembers {
return false, errRoomIsFull
}
otherClientExists := numClients > 0
key := redisRoomMembersKey(roomID)
if _, err := m.client.SAdd(ctx, key, string(clientID)).Result(); err != nil {
return false, fmt.Errorf("failed to exec SADD for %s: %w", key, err)
}
if _, err := m.client.Expire(ctx, key, m.roomExpiration).Result(); err != nil {
return false, fmt.Errorf("failed to exec EXPIRE for %s: %w", key, err)
}
return otherClientExists, nil
}
func (m *redisRoomManager) LeaveRoom(ctx context.Context, roomID RoomID, clientID ClientID) (bool, error) {
key := redisRoomMembersKey(roomID)
reply, err := m.client.Exists(ctx, key).Result()
if err != nil {
return false, err
}
roomExists := reply == 1
if !roomExists {
return false, nil
}
if _, err := m.client.SRem(ctx, key, string(clientID)).Result(); err != nil {
return false, fmt.Errorf("failed to exec SREM for %s: %w", key, err)
}
numClients, err := m.CountClients(ctx, roomID)
if err != nil {
return false, err
}
otherClientExists := numClients > 0
// If one client leaves the room, the room will be deleted.
if err := m.DeleteRoom(ctx, roomID); err != nil {
return false, fmt.Errorf("failed to delete room: %w", err)
}
return otherClientExists, nil
}
func (m *redisRoomManager) DeleteRoom(ctx context.Context, roomID RoomID) error {
if _, err := m.client.Del(ctx, redisRoomMembersKey(roomID)).Result(); err != nil {
return err
}
m.logger.Infof("room deleted (room: %s)", roomID)
return nil
}
func (m *redisRoomManager) BeginRoomLock(roomID RoomID) (*roomLock, error) {
mu := newRedisMutex(m.client, redisRoomLockKey(roomID), roomLockExpiration, redisOperationTimeout)
if err := mu.Lock(); err != nil {
return nil, err
}
return newRoomLock(mu, roomID, m.logger), nil
}
func (m *redisRoomManager) CountClients(ctx context.Context, roomID RoomID) (int, error) {
key := redisRoomMembersKey(roomID)
members, err := m.client.SMembers(ctx, key).Result()
if err != nil {
return 0, fmt.Errorf("failed to exec SMEMBERS for %s: %w", key, err)
}
return len(members), nil
}
type redisMutex struct {
client *redis.Client
key string
expiration time.Duration
operationTimeout time.Duration
}
func newRedisMutex(client *redis.Client, key string, expiration, operationTimeout time.Duration) *redisMutex {
return &redisMutex{
client: client,
key: key,
expiration: expiration,
operationTimeout: operationTimeout,
}
}
func (m *redisMutex) Lock() error {
ctx, cancel := context.WithTimeout(context.Background(), m.operationTimeout)
defer cancel()
for {
acquired, err := m.client.SetNX(ctx, m.key, "1", m.expiration).Result()
if err != nil {
return err
}
if acquired {
return nil
}
time.Sleep(50 * time.Millisecond)
}
}
func (m *redisMutex) Unlock() error {
ctx, cancel := context.WithTimeout(context.Background(), m.operationTimeout)
defer cancel()
if _, err := m.client.Del(ctx, m.key).Result(); err != nil {
return err
}
return nil
}