Nexus/pkg/internal/http/ws/ws.go

89 lines
2.2 KiB
Go
Raw Normal View History

2024-10-20 11:04:41 +00:00
package ws
2024-10-19 14:36:33 +00:00
import (
2024-11-02 05:09:52 +00:00
"context"
"fmt"
"git.solsynth.dev/hypernet/nexus/pkg/internal/directory"
2024-10-19 14:36:33 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/nex"
"git.solsynth.dev/hypernet/nexus/pkg/nex/sec"
2024-11-02 05:09:52 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/proto"
2024-10-19 14:36:33 +00:00
"github.com/gofiber/contrib/websocket"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog/log"
2024-11-02 05:09:52 +00:00
"github.com/samber/lo"
2024-10-19 14:36:33 +00:00
"github.com/spf13/viper"
)
2024-10-20 11:04:41 +00:00
func Listen(c *websocket.Conn) {
user := c.Locals("nex_user").(sec.UserInfo)
2024-10-19 14:36:33 +00:00
// Push connection
2024-10-20 11:04:41 +00:00
clientId := ClientRegister(user, c)
2024-10-19 14:36:33 +00:00
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
}
2024-11-02 05:09:52 +00:00
service := directory.GetServiceInstanceByType(packet.Endpoint)
if service == nil {
_ = c.WriteMessage(mt, nex.WebSocketPackage{
Action: "error",
Message: "service not found",
}.Marshal())
continue
}
pc, err := service.GetGrpcConn()
if err != nil {
_ = c.WriteMessage(mt, nex.WebSocketPackage{
Action: "error",
Message: fmt.Sprintf("unable to connect to service: %v", err.Error()),
}.Marshal())
continue
}
2024-10-19 14:36:33 +00:00
2024-11-02 05:09:52 +00:00
sc := proto.NewStreamServiceClient(pc)
_, err = sc.PushStream(context.Background(), &proto.PushStreamRequest{
UserId: lo.ToPtr(uint64(user.ID)),
ClientId: lo.ToPtr(clientId),
Body: packet.Marshal(),
})
if err != nil {
_ = c.WriteMessage(mt, nex.WebSocketPackage{
Action: "error",
Message: fmt.Sprintf("unable send message to service: %v", err.Error()),
}.Marshal())
continue
}
2024-10-19 14:36:33 +00:00
}
// Pop connection
2024-10-20 11:04:41 +00:00
ClientUnregister(user, clientId)
2024-10-19 14:36:33 +00:00
log.Debug().
Uint("user", user.ID).
Uint64("clientId", clientId).
Msg("A websocket connection disconnected...")
}