2024-08-04 00:55:28 -04:00
|
|
|
package nexus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
2024-08-04 08:41:35 -04:00
|
|
|
|
|
|
|
"dynatron.me/x/stillbox/pkg/gordio/calls"
|
|
|
|
"dynatron.me/x/stillbox/pkg/pb"
|
2024-08-04 00:55:28 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Nexus struct {
|
|
|
|
sync.RWMutex
|
|
|
|
|
|
|
|
clients map[*client]struct{}
|
|
|
|
|
|
|
|
*wsManager
|
2024-08-04 08:41:35 -04:00
|
|
|
|
|
|
|
callCh chan *calls.Call
|
2024-08-04 00:55:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
type Registry interface {
|
|
|
|
NewClient(Connection) Client
|
|
|
|
Register(Client)
|
|
|
|
Unregister(Client)
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() *Nexus {
|
|
|
|
n := &Nexus{
|
|
|
|
clients: make(map[*client]struct{}),
|
2024-08-04 08:41:35 -04:00
|
|
|
callCh: make(chan *calls.Call, 256),
|
2024-08-04 00:55:28 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
n.wsManager = newWsManager(n)
|
|
|
|
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
2024-08-04 08:41:35 -04:00
|
|
|
func (n *Nexus) Go(wg *sync.WaitGroup) {
|
|
|
|
defer wg.Done()
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case call, ok := <-n.callCh:
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
go n.emitCall(call)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Nexus) emitCall(call *calls.Call) {
|
|
|
|
message := &pb.Message{
|
|
|
|
ToClientMessage: &pb.Message_Call{Call: call.ToPB()},
|
|
|
|
}
|
|
|
|
n.RLock()
|
|
|
|
defer n.RUnlock()
|
|
|
|
|
|
|
|
for cl, _ := range n.clients {
|
|
|
|
cl.Send(message)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-04 00:55:28 -04:00
|
|
|
func (n *Nexus) Register(c Client) {
|
|
|
|
n.Lock()
|
|
|
|
defer n.Unlock()
|
|
|
|
|
|
|
|
n.clients[c.(*client)] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Nexus) Unregister(c Client) {
|
|
|
|
n.Lock()
|
|
|
|
defer n.Unlock()
|
|
|
|
|
2024-08-04 08:41:35 -04:00
|
|
|
cl := c.(*client)
|
|
|
|
delete(n.clients, cl)
|
2024-08-04 00:55:28 -04:00
|
|
|
}
|