Broadcast event

This commit is contained in:
2024-10-21 00:05:40 +08:00
parent 799bfcc263
commit 80ad9399a3
28 changed files with 1330 additions and 48 deletions

View File

@ -0,0 +1,106 @@
package ws
import (
"git.solsynth.dev/hypernet/nexus/pkg/internal/directory"
"math/rand"
"sync"
"git.solsynth.dev/hypernet/nexus/pkg/internal/models"
"github.com/gofiber/contrib/websocket"
)
var (
wsMutex sync.Mutex
wsConn = make(map[uint]map[uint64]*websocket.Conn)
)
func ClientRegister(user models.Account, conn *websocket.Conn) uint64 {
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[uint64]*websocket.Conn)
}
clientId := rand.Uint64()
wsConn[user.ID][clientId] = conn
wsMutex.Unlock()
directory.BroadcastEvent("ws.client.register", map[string]any{
"user": user.ID,
"id": clientId,
})
return clientId
}
func ClientUnregister(user models.Account, id uint64) {
wsMutex.Lock()
if wsConn[user.ID] == nil {
wsConn[user.ID] = make(map[uint64]*websocket.Conn)
}
delete(wsConn[user.ID], id)
wsMutex.Unlock()
directory.BroadcastEvent("ws.client.unregister", map[string]any{
"user": user.ID,
"id": id,
})
}
func ClientCount(uid uint) int {
return len(wsConn[uid])
}
func WebsocketPush(uid uint, body []byte) (count int, success int, errs []error) {
for _, conn := range wsConn[uid] {
if err := conn.WriteMessage(1, body); err != nil {
errs = append(errs, err)
} else {
success++
}
count++
}
return
}
func WebsocketPushDirect(clientId uint64, body []byte) (count int, success int, errs []error) {
for _, m := range wsConn {
if conn, ok := m[clientId]; ok {
if err := conn.WriteMessage(1, body); err != nil {
errs = append(errs, err)
} else {
success++
}
count++
}
}
return
}
func WebsocketPushBatch(uidList []uint, body []byte) (count int, success int, errs []error) {
for _, uid := range uidList {
for _, conn := range wsConn[uid] {
if err := conn.WriteMessage(1, body); err != nil {
errs = append(errs, err)
} else {
success++
}
count++
}
}
return
}
func WebsocketPushBatchDirect(clientIdList []uint64, body []byte) (count int, success int, errs []error) {
for _, clientId := range clientIdList {
for _, m := range wsConn {
if conn, ok := m[clientId]; ok {
if err := conn.WriteMessage(1, body); err != nil {
errs = append(errs, err)
} else {
success++
}
count++
}
}
}
return
}

View File

@ -0,0 +1,85 @@
package ws
import (
"git.solsynth.dev/hypernet/nexus/pkg/internal/models"
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"github.com/gofiber/contrib/websocket"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
func Listen(c *websocket.Conn) {
user := c.Locals("user").(models.Account)
// Push connection
clientId := ClientRegister(user, c)
log.Debug().
Uint("user", user.ID).
Uint64("clientId", clientId).
Msg("New websocket connection established...")
// Event loop
var mt int
var data []byte
var err error
var packet nex.WebSocketPackage
for {
if mt, data, err = c.ReadMessage(); err != nil {
break
} else if err := jsoniter.Unmarshal(data, &packet); err != nil {
_ = c.WriteMessage(mt, nex.WebSocketPackage{
Action: "error",
Message: "unable to unmarshal your command, requires json request",
}.Marshal())
continue
}
aliasingMap := viper.GetStringMapString("services.aliases")
if val, ok := aliasingMap[packet.Endpoint]; ok {
packet.Endpoint = val
}
/*
service := directory.GetServiceInstanceByType(packet.Endpoint)
if service == nil {
_ = c.WriteMessage(mt, nex.NetworkPackage{
Action: "error",
Message: "service not found",
}.Marshal())
continue
}
pc, err := service.GetGrpcConn()
if err != nil {
_ = c.WriteMessage(mt, nex.NetworkPackage{
Action: "error",
Message: fmt.Sprintf("unable to connect to service: %v", err.Error()),
}.Marshal())
continue
}
sc := proto.NewStreamControllerClient(pc)
_, err = sc.EmitStreamEvent(context.Background(), &proto.StreamEventRequest{
Event: packet.Action,
UserId: uint64(user.ID),
ClientId: uint64(clientId),
Payload: packet.RawPayload(),
})
if err != nil {
_ = c.WriteMessage(mt, nex.NetworkPackage{
Action: "error",
Message: fmt.Sprintf("unable send message to service: %v", err.Error()),
}.Marshal())
continue
}*/
}
// Pop connection
ClientUnregister(user, clientId)
log.Debug().
Uint("user", user.ID).
Uint64("clientId", clientId).
Msg("A websocket connection disconnected...")
}