Initial commit

This commit is contained in:
Vojtěch Káně
2020-12-03 23:07:44 +01:00
commit 28e22e3422
24 changed files with 1526 additions and 0 deletions

63
pkg/rtcomm/rtcomm.go Normal file
View File

@@ -0,0 +1,63 @@
package rtcomm
import (
"github.com/google/uuid"
"sync"
)
// TODO associate lock with individual clients to prevent global locking
type Clients struct {
sync.RWMutex
clients map[uuid.UUID][]chan StateUpdate
}
func NewClients() *Clients {
return &Clients{
clients: make(map[uuid.UUID][]chan StateUpdate),
}
}
func (c *Clients) AddClient(id uuid.UUID, client chan StateUpdate) {
c.Lock()
defer c.Unlock()
c.clients[id] = append(c.clients[id], client)
}
//TODO remove debug
func (c *Clients) Count() (sessions, clients uint) {
c.RLock()
defer c.RUnlock()
for _, s := range c.clients {
sessions++
clients += uint(len(s))
}
return
}
// TODO optimize
func (c *Clients) RemoveClient(id uuid.UUID, client chan StateUpdate) {
c.Lock()
defer c.Unlock()
var newClients = make([]chan StateUpdate, 0, len(c.clients[id]) - 1)
for i := 0; i < len(c.clients[id]); i++ {
if c.clients[id][i] != client {
newClients = append(newClients, c.clients[id][i])
}
}
c.clients[id] = newClients
}
func (c *Clients) SendToAll(id uuid.UUID, su StateUpdate) (sent, dropped uint) {
c.RLock()
defer c.RUnlock()
for i := 0; i < len(c.clients[id]); i++ {
select {
case c.clients[id][i] <- su:
sent++
default:
dropped++
}
}
return
}

21
pkg/rtcomm/stateUpdate.go Normal file
View File

@@ -0,0 +1,21 @@
package rtcomm
type StateUpdate struct {
Players []Player `json:"players"`
Question *QuestionUpdate `json:"question,omitempty"`
}
type Player struct {
Organiser bool `json:"organiser"`
Name string `json:"name"`
}
type QuestionUpdate struct {
Title string `json:"title"`
Answers []Answer `json:"answers"`
}
type Answer struct{
ID string `json:"id"`
Title string `json:"title"`
}