fusenapi/server/websocket/internal/logic/datatransferlogic.go

275 lines
6.5 KiB
Go
Raw Normal View History

2023-07-24 08:07:05 +00:00
package logic
import (
2023-07-26 03:53:06 +00:00
"encoding/json"
"fmt"
"fusenapi/constants"
"fusenapi/server/websocket/internal/types"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"net/http"
"sync"
"time"
2023-07-24 08:07:05 +00:00
"context"
"fusenapi/server/websocket/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type DataTransferLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDataTransferLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DataTransferLogic {
return &DataTransferLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
2023-07-26 03:53:06 +00:00
var (
//升级
upgrade = websocket.Upgrader{
//允许跨域
CheckOrigin: func(r *http.Request) bool {
return true
},
}
//连接map池
mapConnPool = sync.Map{}
)
2023-07-24 08:07:05 +00:00
2023-07-26 03:53:06 +00:00
// 每个连接的连接属性
type wsConnectItem struct {
2023-07-26 07:01:59 +00:00
conn *websocket.Conn //websocket的连接
closeChan chan struct{} //关闭chan
isClose bool //是否已经关闭
flag string
inChan chan []byte //接受消息缓冲通道
outChan chan []byte //发送回客户端的消息
mutex sync.Mutex
2023-07-26 07:06:29 +00:00
renderImageTask map[string]struct{} //需要渲染的图片
renderImageTaskCtlChan chan renderImageControlChanItem //渲染任务新增移除的控制通道
2023-07-26 07:01:59 +00:00
}
type renderImageControlChanItem struct {
Option int // 0删除 1添加
Key string //map的key
2023-07-26 03:53:06 +00:00
}
2023-07-24 08:07:05 +00:00
2023-07-26 06:35:29 +00:00
func (l *DataTransferLogic) DataTransfer(svcCtx *svc.ServiceContext, w http.ResponseWriter, r *http.Request) {
2023-07-26 03:53:06 +00:00
//升级websocket
conn, err := upgrade.Upgrade(w, r, nil)
if err != nil {
logx.Error("http upgrade websocket err:", err)
return
}
defer conn.Close()
rsp := types.DataTransferData{}
/*isAuth := true
// 解析JWT token,并对空用户进行判断
claims, err := svcCtx.ParseJwtToken(r)
// 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
rsp.T = constants.WEBSOCKET_UNAUTH
rsp.D = "unAuth"
b, _ := json.Marshal(rsp)
_ = conn.WriteMessage(websocket.TextMessage, b)
isAuth = false
}
if claims != nil {
// 从token中获取对应的用户信息
_, err = auth.GetUserInfoFormMapClaims(claims)
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
rsp.T = constants.WEBSOCKET_UNAUTH
rsp.D = "unAuth!!"
b, _ := json.Marshal(rsp)
_ = conn.WriteMessage(websocket.TextMessage, b)
isAuth = false
}
} else {
// 如果claims为nil,则认为用户身份为白板用户
rsp.T = constants.WEBSOCKET_UNAUTH
rsp.D = "unAuth!!!"
b, _ := json.Marshal(rsp)
_ = conn.WriteMessage(websocket.TextMessage, b)
isAuth = false
}
//不是授权的连接(10秒后关闭)
if !isAuth {
select {
case <-time.After(time.Second * 10):
conn.Close()
return
}
}*/
//生成连接唯一标识
flag := uuid.New().String() + time.Now().Format("20060102150405")
ws := wsConnectItem{
2023-07-26 07:01:59 +00:00
conn: conn,
flag: flag,
closeChan: make(chan struct{}, 1),
inChan: make(chan []byte, 100),
outChan: make(chan []byte, 100),
2023-07-26 07:05:53 +00:00
renderImageTask: make(map[string]struct{}),
renderImageTaskCtlChan: make(chan renderImageControlChanItem, 100),
2023-07-26 07:01:59 +00:00
isClose: false,
2023-07-26 03:53:06 +00:00
}
//保存连接
mapConnPool.Store(flag, ws)
defer ws.close()
//把连接成功消息发回去
rsp.T = constants.WEBSOCKET_CONNECT_SUCCESS
rsp.D = flag
b, _ := json.Marshal(rsp)
conn.WriteMessage(websocket.TextMessage, b)
//循环读客户端信息
go ws.readLoop()
//循环把数据发送给客户端
go ws.writeLoop()
//推消息到云渲染
go ws.sendLoop()
2023-07-26 07:01:59 +00:00
//操作连接中渲染任务的增加/删除
go ws.operationRenderTask()
2023-07-26 03:53:06 +00:00
//心跳
ws.heartbeat()
2023-07-24 08:07:05 +00:00
}
2023-07-26 03:53:06 +00:00
// 心跳
func (w *wsConnectItem) heartbeat() {
rsp := types.DataTransferData{
T: constants.WEBSOCKET_HEARTBEAT,
D: "",
}
b, _ := json.Marshal(rsp)
for {
time.Sleep(time.Second * 10)
select {
case <-w.closeChan:
return
default:
}
//发送心跳信息
if err := w.conn.WriteMessage(websocket.TextMessage, b); err != nil {
logx.Error("发送心跳信息异常,关闭连接:", w.flag, err)
w.close()
return
}
}
}
// 关闭连接
func (w *wsConnectItem) close() {
w.mutex.Lock()
defer w.mutex.Unlock()
logx.Info("websocket:", w.flag, " is closing...")
w.conn.Close()
mapConnPool.Delete(w.flag)
if !w.isClose {
w.isClose = true
close(w.closeChan)
}
logx.Info("websocket:", w.flag, " is closed")
}
2023-07-26 07:01:59 +00:00
// 操作连接中渲染任务的增加/删除
func (w *wsConnectItem) operationRenderTask() {
for {
select {
case <-w.closeChan:
return
2023-07-26 07:05:53 +00:00
case data := <-w.renderImageTaskCtlChan:
2023-07-26 07:01:59 +00:00
switch data.Option {
case 0: //删除
2023-07-26 07:05:53 +00:00
delete(w.renderImageTask, data.Key)
2023-07-26 07:01:59 +00:00
case 1: //新增
2023-07-26 07:05:53 +00:00
w.renderImageTask[data.Key] = struct{}{}
2023-07-26 07:01:59 +00:00
default:
}
}
}
}
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) writeLoop() {
for {
select {
case <-w.closeChan: //如果关闭了
return
case data := <-w.outChan:
w.conn.WriteMessage(websocket.TextMessage, data)
}
}
}
// 接受客户端发来的消息
func (w *wsConnectItem) readLoop() {
for {
select {
case <-w.closeChan: //如果关闭了
return
default:
}
_, data, err := w.conn.ReadMessage()
if err != nil {
logx.Error("接受信息错误:", err)
//关闭连接
w.close()
return
}
//消息传入缓冲通道
w.inChan <- data
}
}
// 把收到的消息发往不同的地方处理
func (w *wsConnectItem) sendLoop() {
for {
select {
case <-w.closeChan:
return
case data := <-w.inChan:
w.dealwithReciveData(data)
}
}
}
2023-07-26 04:27:34 +00:00
// 把要传递给客户端的数据放入outchan
func (w *wsConnectItem) sendToOutChan(data [][]byte) {
for _, v := range data {
2023-07-26 03:53:06 +00:00
select {
case <-w.closeChan:
return
2023-07-26 04:27:34 +00:00
case w.outChan <- v:
2023-07-26 03:53:06 +00:00
logx.Info("notify send render result to out chan")
}
2023-07-26 04:27:34 +00:00
}
}
2023-07-26 03:53:06 +00:00
// 获取需要渲染图片的map key
func (w *wsConnectItem) getRenderImageMapKey(productId, sizeId, templateId int64) string {
return fmt.Sprintf("%d-%d-%d", productId, sizeId, templateId)
}
2023-07-26 07:08:43 +00:00
// 处理接受到的数据
func (w *wsConnectItem) dealwithReciveData(data []byte) {
var parseInfo types.DataTransferData
if err := json.Unmarshal(data, &parseInfo); err != nil {
logx.Error("invalid format of websocket message")
return
}
//分消息类型给到不同逻辑处理,可扩展
switch parseInfo.T {
//图片渲染
case constants.WEBSOCKET_RENDER_IMAGE:
w.SendToCloudRender([]byte(parseInfo.D))
default:
}
}