witty/term_conn/reg.go

82 lines
1.6 KiB
Go
Raw Normal View History

2022-01-10 23:16:22 +01:00
package term_conn
2022-01-10 04:04:23 +01:00
import (
"errors"
"log"
"sync"
"github.com/gorilla/websocket"
)
// a simple registry for actors and their channels. It is possible to
// design this using channels, but it is simple enough with mutex
type Registry struct {
2022-01-10 15:35:05 +01:00
mtx sync.Mutex
players map[string]*TermConn
2022-01-10 04:04:23 +01:00
}
var registry Registry
func (reg *Registry) init() {
2022-01-10 15:35:05 +01:00
reg.players = make(map[string]*TermConn)
2022-01-10 04:04:23 +01:00
}
2022-01-12 03:18:19 +01:00
func (d *Registry) addPlayer(tc *TermConn) {
2022-01-10 04:04:23 +01:00
d.mtx.Lock()
2022-01-12 03:18:19 +01:00
if _, ok := d.players[tc.Name]; ok {
log.Println(tc.Name, "Already exist in the dispatcher, skip registration")
2022-01-10 15:35:05 +01:00
} else {
2022-01-12 03:18:19 +01:00
d.players[tc.Name] = tc
log.Println("Add interactive session to registry", tc.Name)
2022-01-10 04:04:23 +01:00
}
d.mtx.Unlock()
}
2022-01-10 15:35:05 +01:00
func (d *Registry) removePlayer(name string) error {
2022-01-10 04:04:23 +01:00
d.mtx.Lock()
var err error = errors.New("not found")
2022-01-10 15:35:05 +01:00
if _, ok := d.players[name]; ok {
delete(d.players, name)
2022-01-10 04:04:23 +01:00
err = nil
2022-01-12 03:18:19 +01:00
log.Println("Removed interactive session to registry", name)
2022-01-10 04:04:23 +01:00
}
d.mtx.Unlock()
return err
}
// we do not want to return the channel to viewer so it won't be used out of the critical section
2022-01-10 15:35:05 +01:00
func (d *Registry) sendToPlayer(name string, ws *websocket.Conn) bool {
2022-01-10 04:04:23 +01:00
d.mtx.Lock()
2022-01-10 15:35:05 +01:00
tc, ok := d.players[name]
2022-01-10 04:04:23 +01:00
if ok {
2022-01-14 19:35:10 +01:00
tc.viewChan <- ws
}
d.mtx.Unlock()
return ok
}
// Send a command to the session to start, stop recording
func (d *Registry) recordSession(id string, cmd int) bool {
d.mtx.Lock()
tc, ok := d.players[id]
if ok {
tc.recordChan <- cmd
2022-01-10 04:04:23 +01:00
}
d.mtx.Unlock()
return ok
}
2022-01-12 03:18:19 +01:00
func ForEachSession(fp func(tc *TermConn)) {
registry.mtx.Lock()
for _, v := range registry.players {
fp(v)
}
registry.mtx.Unlock()
}