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

355 lines
9.1 KiB
Go
Raw Normal View History

2023-07-24 08:07:05 +00:00
package logic
2023-08-23 07:08:45 +00:00
//websocket连接
2023-07-24 08:07:05 +00:00
import (
2023-07-26 08:00:19 +00:00
"bytes"
2023-08-23 08:13:14 +00:00
"encoding/hex"
2023-07-26 03:53:06 +00:00
"encoding/json"
"fusenapi/constants"
2023-08-23 07:54:02 +00:00
"fusenapi/server/websocket/internal/websocket_data"
2023-07-26 09:30:35 +00:00
"fusenapi/utils/auth"
2023-07-26 03:53:06 +00:00
"net/http"
"sync"
"time"
2023-07-24 08:07:05 +00:00
"github.com/google/uuid"
2023-08-08 06:20:57 +00:00
"github.com/gorilla/websocket"
2023-07-24 08:07:05 +00:00
"context"
"fusenapi/server/websocket/internal/svc"
2023-08-08 06:20:57 +00:00
2023-07-24 08:07:05 +00:00
"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 (
2023-07-26 09:09:04 +00:00
//临时缓存对象池
2023-07-26 08:00:19 +00:00
buffPool = sync.Pool{
New: func() interface{} {
return bytes.Buffer{}
},
}
//升级websocket
2023-08-23 04:29:59 +00:00
upgrader = websocket.Upgrader{
2023-07-27 11:30:40 +00:00
//最大可读取大小 10M
ReadBufferSize: 1024 * 10,
2023-07-26 08:00:19 +00:00
//握手超时时间15s
HandshakeTimeout: time.Second * 15,
2023-07-26 03:53:06 +00:00
//允许跨域
CheckOrigin: func(r *http.Request) bool {
return true
},
2023-07-27 11:30:40 +00:00
//写的缓存池
WriteBufferPool: &buffPool,
//是否支持压缩
2023-07-27 02:06:27 +00:00
EnableCompression: true,
2023-07-26 03:53:06 +00:00
}
2023-07-27 08:29:09 +00:00
//websocket连接存储
2023-07-26 03:53:06 +00:00
mapConnPool = sync.Map{}
2023-08-23 07:20:37 +00:00
//公共互斥锁(复用连接标识用)
2023-08-10 11:41:25 +00:00
publicMutex sync.Mutex
2023-07-26 03:53:06 +00:00
)
2023-07-24 08:07:05 +00:00
2023-07-26 09:06:53 +00:00
// 每个连接的连接基本属性
2023-07-26 03:53:06 +00:00
type wsConnectItem struct {
2023-08-23 07:20:37 +00:00
conn *websocket.Conn //websocket的连接(基本属性)
logic *DataTransferLogic //logic(基本属性,用于获取上下文,配置或者操作数据库)
closeChan chan struct{} //ws连接关闭chan(基本属性)
isClose bool //是否已经关闭(基本属性)
uniqueId string //ws连接唯一标识(基本属性)
2023-08-23 07:35:58 +00:00
inChan chan []byte //接受消息缓冲池(基本属性)
outChan chan []byte //要发送回客户端的消息缓冲池(基本属性)
2023-08-23 07:20:37 +00:00
mutex sync.Mutex //互斥锁(关闭连接方法中用)
userId int64 //用户id(基本属性)
guestId int64 //游客id(基本属性)
renderProperty renderProperty //扩展云渲染属性(扩展属性)
2023-07-26 03:53:06 +00:00
}
2023-07-24 08:07:05 +00:00
2023-08-18 08:21:45 +00:00
// 请求建立连接升级websocket协议
2023-08-16 06:16:33 +00:00
func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request) {
2023-08-18 08:20:45 +00:00
//把子协议携带的token设置到标准token头信息中
2023-08-18 09:52:19 +00:00
token := r.Header.Get("Sec-Websocket-Protocol")
r.Header.Set("Authorization", "Bearer "+token)
2023-08-18 08:03:29 +00:00
//设置Sec-Websocket-Protocol
2023-08-23 04:29:59 +00:00
upgrader.Subprotocols = []string{token}
2023-07-26 03:53:06 +00:00
//升级websocket
2023-08-23 04:29:59 +00:00
conn, err := upgrader.Upgrade(w, r, nil)
2023-07-26 03:53:06 +00:00
if err != nil {
logx.Error("http upgrade websocket err:", err)
return
}
defer conn.Close()
2023-08-10 07:21:28 +00:00
//鉴权不成功后断开
2023-08-18 08:03:29 +00:00
var (
2023-08-07 11:13:16 +00:00
userInfo *auth.UserInfo
isAuth bool
)
2023-08-16 06:16:33 +00:00
isAuth, userInfo = l.checkAuth(r)
2023-07-27 07:46:07 +00:00
if !isAuth {
2023-08-18 09:33:42 +00:00
//未授权响应消息
l.unAuthResponse(conn)
2023-07-27 07:46:07 +00:00
return
2023-08-18 08:03:29 +00:00
}
2023-08-11 02:49:29 +00:00
//设置连接
2023-08-18 08:03:29 +00:00
ws := l.setConnPool(conn, *userInfo)
2023-08-10 11:41:25 +00:00
defer ws.close()
//循环读客户端信息
go ws.readLoop()
//循环把数据发送给客户端
go ws.writeLoop()
//推消息到云渲染
go ws.sendLoop()
//操作连接中渲染任务的增加/删除
go ws.operationRenderTask()
2023-08-16 08:20:16 +00:00
//消费渲染缓冲队列
go ws.renderImage()
2023-08-10 11:41:25 +00:00
//心跳
ws.heartbeat()
}
2023-08-11 02:49:29 +00:00
// 设置连接
2023-08-10 11:41:25 +00:00
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo) wsConnectItem {
publicMutex.Lock()
defer publicMutex.Unlock()
2023-07-26 03:53:06 +00:00
//生成连接唯一标识
2023-08-15 10:38:33 +00:00
uniqueId := l.getUniqueId(userInfo)
2023-07-26 03:53:06 +00:00
ws := wsConnectItem{
2023-07-26 09:06:53 +00:00
conn: conn,
2023-08-16 06:09:03 +00:00
logic: l,
2023-07-27 08:27:42 +00:00
uniqueId: uniqueId,
2023-07-26 09:06:53 +00:00
closeChan: make(chan struct{}, 1),
2023-08-23 07:12:52 +00:00
inChan: make(chan []byte, 1000),
outChan: make(chan []byte, 1000),
2023-08-09 04:28:06 +00:00
userId: userInfo.UserId,
guestId: userInfo.GuestId,
2023-07-26 09:06:53 +00:00
renderProperty: renderProperty{
2023-08-21 08:19:30 +00:00
renderImageTask: make(map[string]*renderTask),
2023-08-23 04:29:02 +00:00
renderImageTaskCtlChan: make(chan renderImageControlChanItem, 500),
renderChan: make(chan []byte, 500),
2023-07-26 09:06:53 +00:00
},
2023-07-26 03:53:06 +00:00
}
//保存连接
2023-07-27 08:27:42 +00:00
mapConnPool.Store(uniqueId, ws)
2023-08-10 07:18:33 +00:00
go func() {
2023-08-22 10:37:49 +00:00
defer func() {
if err := recover(); err != nil {
logx.Error("set conn pool panic:", err)
}
}()
2023-08-10 07:18:33 +00:00
//把连接成功消息发回去
2023-08-18 08:23:04 +00:00
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
2023-08-15 10:14:44 +00:00
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId))
2023-08-10 07:18:33 +00:00
}()
2023-08-10 11:41:25 +00:00
return ws
}
2023-08-11 02:49:29 +00:00
// 获取唯一id
2023-08-15 10:38:33 +00:00
func (l *DataTransferLogic) getUniqueId(userInfo auth.UserInfo) string {
//后面拼接上用户id
2023-08-23 08:13:14 +00:00
uniqueId := hex.EncodeToString([]byte(uuid.New().String())) + getUserJoinPart(userInfo.UserId, userInfo.GuestId)
2023-08-10 11:41:25 +00:00
if _, ok := mapConnPool.Load(uniqueId); ok {
2023-08-15 10:38:33 +00:00
uniqueId = l.getUniqueId(userInfo)
2023-08-10 11:41:25 +00:00
}
return uniqueId
2023-07-24 08:07:05 +00:00
}
2023-07-26 03:53:06 +00:00
2023-07-26 09:30:35 +00:00
// 鉴权
2023-08-16 06:16:33 +00:00
func (l *DataTransferLogic) checkAuth(r *http.Request) (isAuth bool, userInfo *auth.UserInfo) {
2023-07-26 09:30:35 +00:00
// 解析JWT token,并对空用户进行判断
2023-08-16 06:16:33 +00:00
claims, err := l.svcCtx.ParseJwtToken(r)
2023-07-26 09:30:35 +00:00
// 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
2023-08-18 08:15:44 +00:00
logx.Error(err)
2023-07-27 04:32:03 +00:00
return false, nil
2023-07-26 09:30:35 +00:00
}
if claims != nil {
// 从token中获取对应的用户信息
2023-07-27 04:32:03 +00:00
userInfo, err = auth.GetUserInfoFormMapClaims(claims)
2023-07-26 09:30:35 +00:00
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
2023-08-18 08:15:44 +00:00
logx.Error(err)
2023-07-27 04:32:03 +00:00
return false, nil
2023-07-26 09:30:35 +00:00
}
2023-08-03 06:26:40 +00:00
//不是登录用户也不是游客
if !userInfo.IsUser() && !userInfo.IsGuest() {
return false, nil
}
return true, userInfo
2023-07-26 09:30:35 +00:00
}
2023-08-03 06:26:40 +00:00
return false, nil
2023-07-26 09:30:35 +00:00
}
2023-08-18 09:33:42 +00:00
// 鉴权失败通知
func (l *DataTransferLogic) unAuthResponse(conn *websocket.Conn) {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
rsp := websocket_data.DataTransferData{
T: constants.WEBSOCKET_UNAUTH,
D: nil,
}
b, _ := json.Marshal(rsp)
//先发一条正常信息
_ = conn.WriteMessage(websocket.TextMessage, b)
//发送关闭信息
_ = conn.WriteMessage(websocket.CloseMessage, nil)
//关闭连接
conn.Close()
}
2023-08-22 10:31:25 +00:00
// 心跳检测
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) heartbeat() {
2023-07-27 02:08:30 +00:00
tick := time.Tick(time.Second * 5)
2023-07-26 03:53:06 +00:00
for {
select {
case <-w.closeChan:
return
2023-07-26 10:00:46 +00:00
case <-tick:
2023-07-26 08:23:38 +00:00
//发送心跳信息
2023-07-26 09:39:56 +00:00
if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil {
2023-07-27 08:27:42 +00:00
logx.Error("发送心跳信息异常,关闭连接:", w.uniqueId, err)
2023-07-26 08:23:38 +00:00
w.close()
return
}
2023-07-26 03:53:06 +00:00
}
}
}
2023-08-22 10:31:25 +00:00
// 关闭websocket连接
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) close() {
w.mutex.Lock()
defer w.mutex.Unlock()
2023-07-27 08:27:42 +00:00
logx.Info("websocket:", w.uniqueId, " is closing...")
2023-07-26 09:39:56 +00:00
//发送关闭信息
_ = w.conn.WriteMessage(websocket.CloseMessage, nil)
2023-07-26 03:53:06 +00:00
w.conn.Close()
2023-07-27 08:27:42 +00:00
mapConnPool.Delete(w.uniqueId)
2023-07-26 03:53:06 +00:00
if !w.isClose {
w.isClose = true
close(w.closeChan)
}
2023-07-27 08:27:42 +00:00
logx.Info("websocket:", w.uniqueId, " is closed")
2023-07-26 03:53:06 +00:00
}
2023-08-22 10:31:25 +00:00
// 读取出口缓冲池数据输出返回给浏览器端
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) writeLoop() {
2023-08-22 10:37:49 +00:00
defer func() {
if err := recover(); err != nil {
logx.Error("write loop panic:", err)
}
}()
2023-07-26 03:53:06 +00:00
for {
select {
case <-w.closeChan: //如果关闭了
return
case data := <-w.outChan:
2023-07-26 10:03:27 +00:00
if err := w.conn.WriteMessage(websocket.TextMessage, data); err != nil {
logx.Error("websocket write loop err:", err)
w.close()
return
}
2023-07-26 03:53:06 +00:00
}
}
}
2023-08-22 10:31:25 +00:00
// 接受客户端发来的消息并写入入口缓冲池
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) readLoop() {
2023-08-22 10:37:49 +00:00
defer func() {
if err := recover(); err != nil {
logx.Error("read loop panic:", err)
}
}()
2023-07-26 03:53:06 +00:00
for {
select {
case <-w.closeChan: //如果关闭了
return
default:
2023-07-26 09:55:14 +00:00
msgType, data, err := w.conn.ReadMessage()
2023-07-26 08:23:38 +00:00
if err != nil {
logx.Error("接受信息错误:", err)
//关闭连接
w.close()
return
}
2023-07-26 09:55:14 +00:00
//ping的消息不处理
if msgType != websocket.PingMessage {
//消息传入缓冲通道
w.inChan <- data
}
2023-07-26 03:53:06 +00:00
}
}
}
2023-08-22 10:31:25 +00:00
// 消费websocket入口数据池中的数据
2023-07-26 03:53:06 +00:00
func (w *wsConnectItem) sendLoop() {
2023-08-22 10:37:49 +00:00
defer func() {
if err := recover(); err != nil {
logx.Error("send loop panic:", err)
}
}()
2023-07-26 03:53:06 +00:00
for {
select {
case <-w.closeChan:
return
case data := <-w.inChan:
w.dealwithReciveData(data)
}
}
}
2023-08-22 10:31:25 +00:00
// 把要传递给客户端的数据放入出口缓冲池
2023-07-26 08:58:14 +00:00
func (w *wsConnectItem) sendToOutChan(data []byte) {
select {
case <-w.closeChan:
return
case w.outChan <- data:
2023-08-15 09:40:27 +00:00
return
case <-time.After(time.Second * 3): //阻塞超过3秒丢弃
return
2023-07-26 04:27:34 +00:00
}
}
2023-08-22 10:31:25 +00:00
// 格式化为websocket标准返回格式
2023-08-23 07:08:45 +00:00
func (w *wsConnectItem) respondDataFormat(msgType constants.Websocket, data interface{}) []byte {
2023-08-07 03:25:06 +00:00
d := websocket_data.DataTransferData{
2023-07-27 09:33:50 +00:00
T: msgType,
D: data,
}
b, _ := json.Marshal(d)
return b
}
2023-08-22 10:31:25 +00:00
// 处理入口缓冲池中不同类型的数据(分发处理)
2023-07-26 07:08:43 +00:00
func (w *wsConnectItem) dealwithReciveData(data []byte) {
2023-08-07 03:25:06 +00:00
var parseInfo websocket_data.DataTransferData
2023-07-26 07:08:43 +00:00
if err := json.Unmarshal(data, &parseInfo); err != nil {
2023-08-15 10:14:44 +00:00
logx.Error("invalid format of websocket message:", err)
2023-08-15 07:09:53 +00:00
w.sendToOutChan(w.respondDataFormat(constants.WEBSOCKET_ERR_DATA_FORMAT, "invalid format of websocket message:"+string(data)))
2023-07-26 07:08:43 +00:00
return
}
2023-07-26 08:47:53 +00:00
d, _ := json.Marshal(parseInfo.D)
2023-07-26 07:08:43 +00:00
//分消息类型给到不同逻辑处理,可扩展
switch parseInfo.T {
2023-08-07 05:17:23 +00:00
//图片渲染
case constants.WEBSOCKET_RENDER_IMAGE:
2023-08-16 08:20:16 +00:00
w.sendToRenderChan(d)
2023-08-11 02:49:29 +00:00
//刷新重连请求恢复上次连接的标识
2023-08-15 10:14:44 +00:00
case constants.WEBSOCKET_REQUEST_REUSE_LAST_CONNECT:
w.reuseLastConnect(d)
2023-07-26 07:08:43 +00:00
default:
2023-08-23 04:29:02 +00:00
logx.Error("未知消息类型:", parseInfo.T)
2023-07-26 07:08:43 +00:00
}
}