1package server
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "log"
8 "sync"
9 "time"
10
11 "github.com/gofrs/uuid"
12 "github.com/speps/go-hashids"
13 "github.com/zikaeroh/codies/internal/game"
14 "github.com/zikaeroh/codies/internal/protocol"
15 "go.uber.org/atomic"
16 "golang.org/x/sync/errgroup"
17 "nhooyr.io/websocket"
18 "nhooyr.io/websocket/wsjson"
19)
20
21const maxRooms = 1000
22
23var (
24 ErrRoomExists = errors.New("server: rooms exist")
25 ErrTooManyRooms = errors.New("server: too many rooms")
26)
27
28type Server struct {
29 clientCount atomic.Int64
30 roomCount atomic.Int64
31 doPrune chan struct{}
32 ready chan struct{}
33
34 mu sync.Mutex
35
36 ctx context.Context
37 rooms map[string]*Room
38 roomIDs map[string]*Room
39
40 hid *hashids.HashID
41 nextID int64
42}
43
44func NewServer() *Server {
45 hd := hashids.NewData()
46 hd.MinLength = 8
47 hd.Salt = uuid.Must(uuid.NewV4()).String() // IDs are only valid for this server instance; ok to randomize salt.
48 hid, err := hashids.NewWithData(hd)
49 if err != nil {
50 panic(err)
51 }
52
53 return &Server{
54 ready: make(chan struct{}),
55 doPrune: make(chan struct{}, 1),
56 rooms: make(map[string]*Room),
57 roomIDs: make(map[string]*Room),
58 hid: hid,
59 }
60}
61
62func (s *Server) Run(ctx context.Context) error {
63 s.ctx = ctx
64
65 close(s.ready)
66 ticker := time.NewTicker(5 * time.Minute)
67 defer ticker.Stop()
68
69 for {
70 select {
71 case <-ctx.Done():
72 return ctx.Err()
73
74 case <-s.doPrune:
75 s.prune()
76
77 case <-ticker.C:
78 s.prune()
79 }
80 }
81}
82
83func (s *Server) FindRoom(name string) *Room {
84 <-s.ready
85
86 s.mu.Lock()
87 defer s.mu.Unlock()
88 return s.rooms[name]
89}
90
91func (s *Server) FindRoomByID(id string) *Room {
92 <-s.ready
93
94 s.mu.Lock()
95 defer s.mu.Unlock()
96 return s.roomIDs[id]
97}
98
99func (s *Server) CreateRoom(name, password string) (*Room, error) {
100 <-s.ready
101
102 s.mu.Lock()
103 defer s.mu.Unlock()
104
105 room := s.rooms[name]
106 if room != nil {
107 return nil, ErrRoomExists
108 }
109
110 if len(s.rooms) >= maxRooms {
111 return nil, ErrTooManyRooms
112 }
113
114 id, err := s.hid.EncodeInt64([]int64{s.nextID})
115 if err != nil {
116 return nil, err
117 }
118 s.nextID++
119
120 ctx, cancel := context.WithCancel(s.ctx)
121
122 room = &Room{
123 Name: name,
124 Password: password,
125 ID: id,
126 clientCount: &s.clientCount,
127 roomCount: &s.roomCount,
128 ctx: ctx,
129 cancel: cancel,
130 room: game.NewRoom(nil),
131 players: make(map[game.PlayerID]noteSender),
132 turnSeconds: 60,
133 }
134
135 room.lastSeen.Store(time.Now())
136
137 room.room.NewGame()
138
139 s.rooms[name] = room
140 s.roomIDs[room.ID] = room
141 s.roomCount.Inc()
142
143 log.Printf("created new room '%s' (%s)", name, room.ID)
144
145 if s.nextID%100 == 0 {
146 s.triggerPrune()
147 }
148
149 return room, nil
150}
151
152func (s *Server) triggerPrune() {
153 select {
154 case s.doPrune <- struct{}{}:
155 default:
156 }
157}
158
159func (s *Server) prune() {
160 s.mu.Lock()
161 defer s.mu.Unlock()
162
163 toRemove := make([]string, 0, 1)
164
165 for name, room := range s.rooms {
166 lastSeen := room.lastSeen.Load().(time.Time)
167 if time.Since(lastSeen) > 10*time.Minute {
168 toRemove = append(toRemove, name)
169 }
170 }
171
172 if len(toRemove) == 0 {
173 return
174 }
175
176 for _, name := range toRemove {
177 room := s.rooms[name]
178 room.mu.Lock()
179 room.stopTimer()
180 room.mu.Unlock()
181
182 room.cancel()
183 delete(s.rooms, name)
184 delete(s.roomIDs, room.ID)
185 s.roomCount.Dec()
186 }
187
188 log.Printf("pruned %d rooms", len(toRemove))
189}
190
191func (s *Server) Stats() (rooms, clients int) {
192 s.mu.Lock()
193 defer s.mu.Unlock()
194 return len(s.rooms), int(s.clientCount.Load())
195}
196
197type Room struct {
198 Name string
199 Password string
200 ID string
201
202 ctx context.Context
203 cancel context.CancelFunc
204 clientCount *atomic.Int64
205 roomCount *atomic.Int64
206
207 mu sync.Mutex
208 room *game.Room
209 players map[game.PlayerID]noteSender
210 state *stateCache
211 lastSeen atomic.Value
212
213 timed bool
214 turnSeconds int
215 turnDeadline *time.Time
216 turnTimer *time.Timer
217}
218
219type noteSender func(protocol.ServerNote)
220
221func (r *Room) HandleConn(playerID uuid.UUID, nickname string, c *websocket.Conn) {
222 clientCount := r.clientCount.Inc()
223 log.Printf("client connected to room '%s' (%s); %v clients currently connected to %v rooms", r.Name, r.ID, clientCount, r.roomCount.Load())
224
225 defer func() {
226 clientCount := r.clientCount.Dec()
227 log.Printf("client disconnected from room '%s' (%s); %v clients currently connected to %v rooms", r.Name, r.ID, clientCount, r.roomCount.Load())
228 }()
229
230 defer c.Close(websocket.StatusGoingAway, "going away")
231 g, ctx := errgroup.WithContext(r.ctx)
232
233 r.mu.Lock()
234 r.players[playerID] = func(s protocol.ServerNote) {
235 g.Go(func() error {
236 ctx, cancel := context.WithTimeout(ctx, time.Second)
237 defer cancel()
238 return wsjson.Write(ctx, c, &s)
239 })
240 }
241 r.room.AddPlayer(playerID, nickname)
242 r.sendAll()
243 r.mu.Unlock()
244
245 defer func() {
246 r.mu.Lock()
247 defer r.mu.Unlock()
248 delete(r.players, playerID)
249 r.room.RemovePlayer(playerID)
250 r.sendAll()
251 }()
252
253 g.Go(func() error {
254 ticker := time.NewTicker(time.Minute)
255 defer ticker.Stop()
256
257 for {
258 select {
259 case <-ctx.Done():
260 return ctx.Err()
261 case <-ticker.C:
262 }
263
264 if err := c.Ping(ctx); err != nil {
265 return err
266 }
267
268 r.lastSeen.Store(time.Now())
269 }
270 })
271
272 g.Go(func() error {
273 for {
274 var note protocol.ClientNote
275
276 if err := wsjson.Read(ctx, c, ¬e); err != nil {
277 return err
278 }
279
280 r.lastSeen.Store(time.Now())
281
282 if err := r.handleNote(playerID, ¬e); err != nil {
283 log.Println("error handling note:", err)
284 return err
285 }
286 }
287 })
288
289 _ = g.Wait()
290}
291
292func (r *Room) handleNote(playerID game.PlayerID, note *protocol.ClientNote) error {
293 r.mu.Lock()
294 defer r.mu.Unlock()
295
296 // The client's version was wrong; reject and send them the current state.
297 if note.Version != r.room.Version {
298 r.sendOne(playerID, r.players[playerID])
299 return nil
300 }
301
302 before := r.room.Version
303 resetTimer := false
304
305 defer func() {
306 if r.room.Version != before {
307 if r.timed && resetTimer {
308 r.startTimer()
309 }
310 r.sendAll()
311 }
312 }()
313
314 switch note.Method {
315 case protocol.RevealMethod:
316 var params protocol.RevealParams
317 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
318 return err
319 }
320 resetTimer = true
321 r.room.Reveal(playerID, params.Row, params.Col)
322
323 case protocol.NewGameMethod:
324 var params protocol.NewGameParams
325 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
326 return err
327 }
328 resetTimer = true
329 r.room.NewGame()
330
331 case protocol.EndTurnMethod:
332 var params protocol.EndTurnParams
333 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
334 return err
335 }
336 resetTimer = true
337 r.room.EndTurn(playerID)
338
339 case protocol.RandomizeTeamsMethod:
340 var params protocol.RandomizeTeamsParams
341 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
342 return err
343 }
344 r.room.RandomizeTeams()
345
346 case protocol.ChangeTeamMethod:
347 var params protocol.ChangeTeamParams
348 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
349 return err
350 }
351 r.room.ChangeTeam(playerID, params.Team)
352
353 case protocol.ChangeNicknameMethod:
354 var params protocol.ChangeNicknameParams
355 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
356 return err
357 }
358
359 // Sync with protocol.go's validation method.
360 if len(params.Nickname) < 3 || len(params.Nickname) > 16 {
361 return nil
362 }
363
364 r.room.AddPlayer(playerID, params.Nickname)
365
366 case protocol.ChangeRoleMethod:
367 var params protocol.ChangeRoleParams
368 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
369 return err
370 }
371 r.room.ChangeRole(playerID, params.Spymaster)
372
373 case protocol.ChangePackMethod:
374 var params protocol.ChangePackParams
375 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
376 return err
377 }
378 r.room.ChangePack(params.Num, params.Enable)
379
380 case protocol.ChangeTurnModeMethod:
381 var params protocol.ChangeTurnModeParams
382 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
383 return err
384 }
385 r.changeTurnMode(params.Timed)
386
387 case protocol.ChangeTurnTimeMethod:
388 var params protocol.ChangeTurnTimeParams
389 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
390 return err
391 }
392 r.changeTurnTime(params.Seconds)
393
394 case protocol.AddPacksMethod:
395 var params protocol.AddPacksParams
396 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
397 return err
398 }
399 for _, p := range params.Packs {
400 r.room.AddPack(p.Name, p.Words)
401 }
402
403 case protocol.RemovePackMethod:
404 var params protocol.RemovePackParams
405 if err := json.Unmarshal(note.Params, ¶ms); err != nil {
406 return err
407 }
408 r.room.RemovePack(params.Num)
409
410 default:
411 log.Printf("unhandled method: %s", note.Method)
412 }
413
414 return nil
415}
416
417// Must be called with r.mu locked.
418func (r *Room) sendAll() {
419 for playerID, sender := range r.players {
420 r.sendOne(playerID, sender)
421 }
422}
423
424// Must be called with r.mu locked.
425func (r *Room) sendOne(playerID game.PlayerID, sender noteSender) {
426 state := r.createStateFor(playerID)
427 note := protocol.StateNote(state)
428 sender(note)
429}
430
431// Must be called with r.mu locked.
432func (r *Room) createStateFor(playerID game.PlayerID) *protocol.State {
433 if r.state == nil || r.state.version != r.room.Version {
434 r.state = r.createStateCache()
435 }
436
437 if r.room.Players[playerID].Spymaster {
438 return r.state.spymaster
439 }
440 return r.state.guesser
441}
442
443type stateCache struct {
444 version int
445 guesser *protocol.State
446 spymaster *protocol.State
447}
448
449func (r *Room) createStateCache() *stateCache {
450 return &stateCache{
451 version: r.room.Version,
452 guesser: r.createRoomState(false),
453 spymaster: r.createRoomState(true),
454 }
455}
456
457func (r *Room) createRoomState(spymaster bool) *protocol.State {
458 room := r.room
459
460 s := &protocol.State{
461 Version: room.Version,
462 Teams: make([][]*protocol.StatePlayer, len(room.Teams)),
463 Turn: room.Turn,
464 Winner: room.Winner,
465 Board: make([][]*protocol.StateTile, room.Board.Rows),
466 WordsLeft: room.Board.WordCounts,
467 Lists: make([]*protocol.StateWordList, len(room.WordLists)),
468 }
469
470 if r.turnDeadline != nil {
471 s.Timer = &protocol.StateTimer{
472 TurnTime: r.turnSeconds,
473 TurnEnd: *r.turnDeadline,
474 }
475 }
476
477 for team, members := range room.Teams {
478 for _, id := range members {
479 p := room.Players[id]
480 s.Teams[team] = append(s.Teams[team], &protocol.StatePlayer{
481 PlayerID: id,
482 Nickname: p.Nickname,
483 Spymaster: p.Spymaster,
484 })
485 }
486
487 if s.Teams[team] == nil {
488 s.Teams[team] = []*protocol.StatePlayer{}
489 }
490 }
491
492 for row := range s.Board {
493 tiles := make([]*protocol.StateTile, room.Board.Cols)
494 for col := range tiles {
495 tile := room.Board.Get(row, col)
496 sTile := &protocol.StateTile{
497 Word: tile.Word,
498 Revealed: tile.Revealed,
499 }
500
501 if spymaster || tile.Revealed || room.Winner != nil {
502 sTile.View = &protocol.StateView{
503 Team: tile.Team,
504 Neutral: tile.Neutral,
505 Bomb: tile.Bomb,
506 }
507 }
508
509 tiles[col] = sTile
510 }
511
512 s.Board[row] = tiles
513 }
514
515 for i, wl := range room.WordLists {
516 s.Lists[i] = &protocol.StateWordList{
517 Name: wl.Name,
518 Count: wl.List.Len(),
519 Custom: wl.Custom,
520 Enabled: wl.Enabled,
521 }
522 }
523
524 return s
525}
526
527// Must be called with r.mu locked.
528func (r *Room) changeTurnMode(timed bool) {
529 if r.timed == timed {
530 return
531 }
532
533 r.timed = timed
534
535 if timed {
536 r.startTimer()
537 } else {
538 r.stopTimer()
539 }
540
541 r.room.Version++
542}
543
544// Must be called with r.mu locked.
545func (r *Room) changeTurnTime(seconds int) {
546 if seconds <= 0 || r.turnSeconds == seconds {
547 return
548 }
549
550 r.turnSeconds = seconds
551
552 if r.timed {
553 r.startTimer()
554 }
555
556 r.room.Version++
557}
558
559func (r *Room) timerEndTurn() {
560 r.mu.Lock()
561 defer r.mu.Unlock()
562
563 stopped := r.stopTimer()
564 if !stopped {
565 // Room was pruned.
566 return
567 }
568
569 r.turnTimer = nil
570 r.turnDeadline = nil
571
572 if r.room.Winner != nil || r.turnSeconds == 0 {
573 return
574 }
575
576 r.room.ForceEndTurn()
577 r.startTimer()
578 r.sendAll()
579}
580
581// Must be called with r.mu locked.
582func (r *Room) stopTimer() (stopped bool) {
583 if r.turnTimer != nil {
584 r.turnTimer.Stop()
585 stopped = true
586 }
587 r.turnTimer = nil
588 r.turnDeadline = nil
589 return stopped
590}
591
592// Must be called with r.mu locked.
593func (r *Room) startTimer() {
594 if !r.timed {
595 panic("startTimer called on non-timed room")
596 }
597
598 if r.turnTimer != nil {
599 r.turnTimer.Stop()
600 }
601
602 dur := time.Second * time.Duration(r.turnSeconds)
603 deadline := time.Now().Add(dur)
604 r.turnDeadline = &deadline
605 r.turnTimer = time.AfterFunc(dur, r.timerEndTurn)
606}