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

444 lines
12 KiB
Go
Raw Normal View History

2023-07-24 16:07:05 +08:00
package logic
2023-08-23 15:08:45 +08:00
//websocket连接
2023-07-24 16:07:05 +08:00
import (
2023-07-26 16:00:19 +08:00
"bytes"
2023-08-23 16:13:14 +08:00
"encoding/hex"
2023-07-26 11:53:06 +08:00
"encoding/json"
2023-08-25 12:21:02 +08:00
"errors"
2023-07-26 11:53:06 +08:00
"fusenapi/constants"
2023-07-26 17:30:35 +08:00
"fusenapi/utils/auth"
2023-08-28 11:33:25 +08:00
"fusenapi/utils/basic"
2023-08-23 16:45:01 +08:00
"fusenapi/utils/encryption_decryption"
2023-08-24 14:24:04 +08:00
"fusenapi/utils/websocket_data"
2023-07-26 11:53:06 +08:00
"net/http"
2023-08-24 12:18:04 +08:00
"strings"
2023-07-26 11:53:06 +08:00
"sync"
"time"
2023-07-24 16:07:05 +08:00
"github.com/google/uuid"
2023-08-08 14:20:57 +08:00
"github.com/gorilla/websocket"
2023-07-24 16:07:05 +08:00
"context"
"fusenapi/server/websocket/internal/svc"
2023-08-08 14:20:57 +08:00
2023-07-24 16:07:05 +08: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 11:53:06 +08:00
var (
2023-08-30 10:55:27 +08:00
//临时对象缓存池
2023-07-26 16:00:19 +08:00
buffPool = sync.Pool{
New: func() interface{} {
return bytes.Buffer{}
},
}
//升级websocket
2023-08-23 12:29:59 +08:00
upgrader = websocket.Upgrader{
2023-08-24 12:24:24 +08:00
//最大可读取大小 1M
ReadBufferSize: 1024,
//最大可写大小 1M
WriteBufferSize: 1024,
2023-07-26 16:00:19 +08:00
//握手超时时间15s
HandshakeTimeout: time.Second * 15,
2023-07-26 11:53:06 +08:00
//允许跨域
CheckOrigin: func(r *http.Request) bool {
return true
},
2023-08-28 15:50:18 +08:00
//写的缓冲队列
2023-07-27 19:30:40 +08:00
WriteBufferPool: &buffPool,
//是否支持压缩
2023-09-05 10:32:40 +08:00
EnableCompression: true,
2023-07-26 11:53:06 +08:00
}
2023-07-27 16:29:09 +08:00
//websocket连接存储
2023-07-26 11:53:06 +08:00
mapConnPool = sync.Map{}
2023-09-07 12:23:04 +08:00
//每个websocket连接入口缓冲队列长度默认值
2023-09-22 15:24:16 +08:00
websocketInChanLen = 2000
2023-09-07 12:23:04 +08:00
//每个websocket连接出口缓冲队列长度默认值
2023-09-22 15:24:16 +08:00
websocketOutChanLen = 2000
2023-09-05 10:30:59 +08:00
//是否开启debug
2023-09-06 10:48:45 +08:00
openDebug = true
2023-09-05 12:21:03 +08:00
//允许跨域的origin
mapAllowOrigin = map[string]struct{}{
"https://www.fusen.3718.cn": struct{}{},
2023-09-05 12:22:32 +08:00
"http://www.fusen.3718.cn": struct{}{},
2023-09-05 12:21:03 +08:00
}
2023-07-26 11:53:06 +08:00
)
2023-07-24 16:07:05 +08:00
2023-09-04 11:17:12 +08:00
// 用户标识的连接增删操作队列传输的值的结构
2023-09-06 17:18:52 +08:00
type userConnPoolCtlChanItem struct {
2023-10-07 16:10:51 +08:00
userId int64 //必须两个用户id任意一个不为0
guestId int64 //必须两个用户id任意一个不为0
uniqueId string //主连接池唯一标识(添加/删除时候必须)
message []byte //消息(发送消息传的,格式是经过标准输出序列化后的数据)
//messageType constants.Websocket //消息类型(发送消息传的)
option int64 //操作 2发消息 1增加 0删除
2023-09-04 11:17:12 +08:00
}
2023-07-26 17:06:53 +08:00
// 每个连接的连接基本属性
2023-07-26 11:53:06 +08:00
type wsConnectItem struct {
2023-08-24 12:04:58 +08:00
conn *websocket.Conn //websocket的连接(基本属性)
2023-08-30 11:25:20 +08:00
userAgent string //用户代理头信息(基本属性,用于重连标识验证因素之一)
2023-08-24 12:04:58 +08:00
logic *DataTransferLogic //logic(基本属性,用于获取上下文,配置或者操作数据库)
closeChan chan struct{} //ws连接关闭chan(基本属性)
isClose bool //是否已经关闭(基本属性)
uniqueId string //ws连接唯一标识(基本属性)
2023-08-28 15:50:18 +08:00
inChan chan []byte //接受消息缓冲队列(基本属性)
outChan chan []byte //要发送回客户端的消息缓冲队列(基本属性)
2023-08-24 12:04:58 +08:00
mutex sync.Mutex //互斥锁(基本属性)
userId int64 //用户id(基本属性)
guestId int64 //游客id(基本属性)
extendRenderProperty extendRenderProperty //扩展云渲染属性(扩展属性)
2023-07-26 11:53:06 +08:00
}
2023-07-24 16:07:05 +08:00
2023-08-18 16:21:45 +08:00
// 请求建立连接升级websocket协议
2023-08-16 14:16:33 +08:00
func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request) {
2023-09-05 14:05:21 +08:00
origin := r.Header.Get("Origin")
2023-09-05 14:11:21 +08:00
//判断是不是允许的跨域
2023-09-06 10:48:45 +08:00
if !openDebug {
upgrader.CheckOrigin = func(r *http.Request) bool {
if _, ok := mapAllowOrigin[origin]; !ok {
return false
}
return true
2023-09-05 12:21:03 +08:00
}
2023-09-05 14:08:55 +08:00
}
2023-08-18 16:20:45 +08:00
//把子协议携带的token设置到标准token头信息中
2023-08-18 17:52:19 +08:00
token := r.Header.Get("Sec-Websocket-Protocol")
2023-08-24 11:38:42 +08:00
//有token是正常用户无则是白板用户也可以连接
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
2023-08-24 11:43:16 +08:00
//设置Sec-Websocket-Protocol
upgrader.Subprotocols = []string{token}
2023-08-24 11:38:42 +08:00
}
2023-08-24 12:18:04 +08:00
//判断下是否火狐浏览器(获取浏览器第一条消息返回有收不到的bug需要延迟1秒)
userAgent := r.Header.Get("User-Agent")
//是否火狐浏览器
isFirefoxBrowser := false
if strings.Contains(userAgent, "Firefox") {
isFirefoxBrowser = true
}
2023-07-26 11:53:06 +08:00
//升级websocket
2023-08-23 12:29:59 +08:00
conn, err := upgrader.Upgrade(w, r, nil)
2023-07-26 11:53:06 +08:00
if err != nil {
logx.Error("http upgrade websocket err:", err)
return
}
2023-09-12 12:15:41 +08:00
//支持写压缩
conn.EnableWriteCompression(true)
2023-08-10 15:21:28 +08:00
//鉴权不成功后断开
2023-08-18 16:03:29 +08:00
var (
2023-08-07 19:13:16 +08:00
userInfo *auth.UserInfo
isAuth bool
)
2023-08-16 14:16:33 +08:00
isAuth, userInfo = l.checkAuth(r)
2023-07-27 15:46:07 +08:00
if !isAuth {
2023-08-18 17:33:42 +08:00
//未授权响应消息
2023-08-24 12:18:04 +08:00
l.unAuthResponse(conn, isFirefoxBrowser)
2023-08-23 18:34:01 +08:00
conn.Close()
2023-07-27 15:46:07 +08:00
return
2023-08-18 16:03:29 +08:00
}
2023-08-11 10:49:29 +08:00
//设置连接
2023-08-30 11:25:20 +08:00
ws, err := l.setConnPool(conn, userInfo, isFirefoxBrowser, userAgent)
2023-08-23 16:57:18 +08:00
if err != nil {
2023-08-23 18:34:01 +08:00
conn.Close()
2023-08-23 16:57:18 +08:00
return
}
2023-08-10 19:41:25 +08:00
//循环读客户端信息
2023-09-05 14:39:35 +08:00
go ws.reciveBrowserMessage()
2023-08-30 11:13:10 +08:00
//消费出口数据并发送浏览器端
go ws.consumeOutChanData()
//消费入口数据
go ws.consumeInChanData()
2023-08-16 16:20:16 +08:00
//消费渲染缓冲队列
2023-08-30 11:13:10 +08:00
go ws.consumeRenderImageData()
2023-08-10 19:41:25 +08:00
//心跳
ws.heartbeat()
}
2023-08-11 10:49:29 +08:00
// 设置连接
2023-08-30 11:25:20 +08:00
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo *auth.UserInfo, isFirefoxBrowser bool, userAgent string) (wsConnectItem, error) {
2023-08-25 12:21:02 +08:00
//生成连接唯一标识失败重试10次
2023-08-30 11:25:20 +08:00
uniqueId, err := l.getUniqueId(userInfo, userAgent, 10)
2023-08-23 16:57:18 +08:00
if err != nil {
//发送获取唯一标识失败的消息
l.sendGetUniqueIdErrResponse(conn)
return wsConnectItem{}, err
}
2023-09-27 18:35:20 +08:00
renderCtx, renderCtxCancelFunc := context.WithCancel(l.ctx)
2023-07-26 11:53:06 +08:00
ws := wsConnectItem{
2023-07-26 17:06:53 +08:00
conn: conn,
2023-08-30 11:25:20 +08:00
userAgent: userAgent,
2023-08-16 14:09:03 +08:00
logic: l,
2023-07-26 17:06:53 +08:00
closeChan: make(chan struct{}, 1),
2023-08-30 11:25:20 +08:00
isClose: false,
uniqueId: uniqueId,
2023-08-30 10:55:27 +08:00
inChan: make(chan []byte, websocketInChanLen),
outChan: make(chan []byte, websocketOutChanLen),
2023-08-30 11:25:20 +08:00
mutex: sync.Mutex{},
2023-08-09 12:28:06 +08:00
userId: userInfo.UserId,
guestId: userInfo.GuestId,
2023-08-24 12:04:58 +08:00
extendRenderProperty: extendRenderProperty{
2023-09-27 18:35:20 +08:00
renderChan: make(chan websocket_data.RenderImageReqMsg, renderChanLen),
renderCtx: renderCtx,
renderCtxCancelFunc: renderCtxCancelFunc,
2023-07-26 17:06:53 +08:00
},
2023-07-26 11:53:06 +08:00
}
//保存连接
2023-07-27 16:27:42 +08:00
mapConnPool.Store(uniqueId, ws)
2023-09-04 11:17:12 +08:00
//非白板用户需要为这个用户建立map索引便于通过用户查询
2023-09-07 16:03:56 +08:00
createUserConnPoolElement(userInfo.UserId, userInfo.GuestId, uniqueId)
2023-08-24 12:18:04 +08:00
if isFirefoxBrowser {
2023-08-18 16:23:04 +08:00
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
2023-08-24 12:18:04 +08:00
}
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId))
2023-09-07 15:54:24 +08:00
//发送累加统计连接书
increaseWebsocketConnectCount()
2023-08-23 16:57:18 +08:00
return ws, nil
2023-08-10 19:41:25 +08:00
}
2023-08-11 10:49:29 +08:00
2023-09-05 10:30:59 +08:00
// 获取websocket发送到前端使用的数据传输类型debug开启是文本否则是二进制
func getWebsocketBaseTransferDataFormat() int {
if openDebug {
return websocket.TextMessage
}
return websocket.BinaryMessage
}
2023-08-11 10:49:29 +08:00
// 获取唯一id
2023-08-30 11:25:20 +08:00
func (l *DataTransferLogic) getUniqueId(userInfo *auth.UserInfo, userAgent string, retryTimes int) (uniqueId string, err error) {
2023-08-25 12:21:02 +08:00
if retryTimes < 0 {
return "", errors.New("failed to get unique id")
}
2023-08-15 18:38:33 +08:00
//后面拼接上用户id
2023-08-30 11:25:20 +08:00
uniqueId = hex.EncodeToString([]byte(uuid.New().String())) + getUserJoinPart(userInfo.UserId, userInfo.GuestId, userAgent)
2023-08-25 12:21:02 +08:00
//存在则从新获取
2023-08-10 19:41:25 +08:00
if _, ok := mapConnPool.Load(uniqueId); ok {
2023-08-30 11:25:20 +08:00
uniqueId, err = l.getUniqueId(userInfo, userAgent, retryTimes-1)
2023-08-23 16:45:01 +08:00
if err != nil {
return "", err
}
}
//加密
uniqueId, err = encryption_decryption.CBCEncrypt(uniqueId)
if err != nil {
return "", err
2023-08-10 19:41:25 +08:00
}
2023-08-23 16:45:01 +08:00
return uniqueId, nil
2023-07-24 16:07:05 +08:00
}
2023-07-26 11:53:06 +08:00
2023-07-26 17:30:35 +08:00
// 鉴权
2023-08-16 14:16:33 +08:00
func (l *DataTransferLogic) checkAuth(r *http.Request) (isAuth bool, userInfo *auth.UserInfo) {
2023-07-26 17:30:35 +08:00
// 解析JWT token,并对空用户进行判断
2023-08-28 11:33:25 +08:00
userInfo, err := basic.ParseJwtToken(r, l.svcCtx)
2023-07-26 17:30:35 +08:00
if err != nil {
2023-07-27 12:32:03 +08:00
return false, nil
2023-07-26 17:30:35 +08:00
}
2023-09-05 10:00:01 +08:00
if userInfo.UserId > 0 {
userInfo.GuestId = 0
}
2023-08-24 11:27:53 +08:00
//白板用户
2023-08-28 11:33:25 +08:00
return true, userInfo
2023-07-26 17:30:35 +08:00
}
2023-08-18 17:33:42 +08:00
// 鉴权失败通知
2023-08-24 12:18:04 +08:00
func (l *DataTransferLogic) unAuthResponse(conn *websocket.Conn, isFirefoxBrowser bool) {
2023-08-18 17:33:42 +08:00
rsp := websocket_data.DataTransferData{
T: constants.WEBSOCKET_UNAUTH,
D: nil,
}
b, _ := json.Marshal(rsp)
2023-08-24 12:18:04 +08:00
if isFirefoxBrowser {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
}
2023-08-18 17:33:42 +08:00
//先发一条正常信息
2023-09-05 10:30:59 +08:00
_ = conn.WriteMessage(getWebsocketBaseTransferDataFormat(), b)
2023-08-18 17:33:42 +08:00
//发送关闭信息
_ = conn.WriteMessage(websocket.CloseMessage, nil)
2023-08-23 16:57:18 +08:00
}
// 获取唯一标识失败通知
func (l *DataTransferLogic) sendGetUniqueIdErrResponse(conn *websocket.Conn) {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
rsp := websocket_data.DataTransferData{
2023-09-04 11:17:12 +08:00
T: constants.WEBSOCKET_CONNECT_ERR,
2023-08-23 16:57:18 +08:00
D: "err to gen unique id ",
}
b, _ := json.Marshal(rsp)
//先发一条正常信息
2023-09-05 10:30:59 +08:00
_ = conn.WriteMessage(getWebsocketBaseTransferDataFormat(), b)
2023-08-23 16:57:18 +08:00
//发送关闭信息
_ = conn.WriteMessage(websocket.CloseMessage, nil)
2023-08-18 17:33:42 +08:00
}
2023-08-22 18:31:25 +08:00
// 心跳检测
2023-07-26 11:53:06 +08:00
func (w *wsConnectItem) heartbeat() {
2023-07-27 10:08:30 +08:00
tick := time.Tick(time.Second * 5)
2023-07-26 11:53:06 +08:00
for {
select {
case <-w.closeChan:
return
2023-07-26 18:00:46 +08:00
case <-tick:
2023-07-26 16:23:38 +08:00
//发送心跳信息
2023-07-26 17:39:56 +08:00
if err := w.conn.WriteMessage(websocket.PongMessage, nil); err != nil {
2023-07-27 16:27:42 +08:00
logx.Error("发送心跳信息异常,关闭连接:", w.uniqueId, err)
2023-08-24 11:56:10 +08:00
w.close()
2023-07-26 16:23:38 +08:00
return
}
2023-07-26 11:53:06 +08:00
}
}
}
2023-08-22 18:31:25 +08:00
// 关闭websocket连接
2023-07-26 11:53:06 +08:00
func (w *wsConnectItem) close() {
w.mutex.Lock()
defer w.mutex.Unlock()
2023-08-24 11:56:10 +08:00
logx.Info("###websocket:", w.uniqueId, " uid:", w.userId, " gid:", w.guestId, " is closing....")
2023-07-26 17:39:56 +08:00
//发送关闭信息
_ = w.conn.WriteMessage(websocket.CloseMessage, nil)
2023-07-26 11:53:06 +08:00
w.conn.Close()
2023-07-27 16:27:42 +08:00
mapConnPool.Delete(w.uniqueId)
2023-07-26 11:53:06 +08:00
if !w.isClose {
w.isClose = true
close(w.closeChan)
2023-09-04 11:17:12 +08:00
//删除用户级索引
2023-09-04 11:37:04 +08:00
deleteUserConnPoolElement(w.userId, w.guestId, w.uniqueId)
2023-09-07 15:54:24 +08:00
//减少连接数统计
decreaseWebsocketConnectCount()
2023-07-26 11:53:06 +08:00
}
2023-08-24 11:56:10 +08:00
logx.Info("###websocket:", w.uniqueId, " uid:", w.userId, " gid:", w.guestId, " is closed")
2023-07-26 11:53:06 +08:00
}
2023-08-28 15:50:18 +08:00
// 读取出口缓冲队列数据输出返回给浏览器端
2023-08-30 11:13:10 +08:00
func (w *wsConnectItem) consumeOutChanData() {
2023-08-22 18:37:49 +08:00
defer func() {
if err := recover(); err != nil {
2023-09-04 11:17:12 +08:00
logx.Error("consumeOutChanData panic:", err)
2023-08-22 18:37:49 +08:00
}
}()
2023-07-26 11:53:06 +08:00
for {
select {
case <-w.closeChan: //如果关闭了
return
case data := <-w.outChan:
2023-07-26 18:03:27 +08:00
if err := w.conn.WriteMessage(websocket.TextMessage, data); err != nil {
logx.Error("websocket write loop err:", err)
w.close()
return
}
2023-07-26 11:53:06 +08:00
}
}
}
2023-08-30 11:13:10 +08:00
// 消费websocket入口数据池中的数据
func (w *wsConnectItem) consumeInChanData() {
defer func() {
if err := recover(); err != nil {
2023-09-04 11:17:12 +08:00
logx.Error("consumeInChanData:", err)
2023-08-30 11:13:10 +08:00
}
}()
for {
select {
case <-w.closeChan:
return
case data := <-w.inChan:
2023-08-30 17:07:14 +08:00
//对不同消息类型分发处理
w.allocationProcessing(data)
2023-08-30 11:13:10 +08:00
}
}
}
// 接受浏览器端发来的消息并写入入口缓冲队列
2023-09-05 14:39:35 +08:00
func (w *wsConnectItem) reciveBrowserMessage() {
2023-08-22 18:37:49 +08:00
defer func() {
if err := recover(); err != nil {
2023-09-04 11:17:12 +08:00
logx.Error("acceptBrowserMessage panic:", err)
2023-08-22 18:37:49 +08:00
}
}()
2023-07-26 11:53:06 +08:00
for {
select {
case <-w.closeChan: //如果关闭了
return
2023-08-28 15:34:30 +08:00
default: //收取消息
2023-07-26 17:55:14 +08:00
msgType, data, err := w.conn.ReadMessage()
2023-07-26 16:23:38 +08:00
if err != nil {
logx.Error("接受信息错误:", err)
//关闭连接
w.close()
return
}
2023-09-05 14:45:15 +08:00
switch msgType {
case websocket.PingMessage, websocket.PongMessage: //心跳消息(过滤不处理)
continue
case websocket.BinaryMessage, websocket.TextMessage: //主要消息
2023-08-28 15:47:25 +08:00
w.sendToInChan(data)
2023-09-05 14:45:15 +08:00
case websocket.CloseMessage: //客户端主动关闭消息
w.close()
2023-07-26 17:55:14 +08:00
}
2023-07-26 11:53:06 +08:00
}
}
}
2023-08-28 15:50:18 +08:00
// 把要传递给客户端的数据放入出口缓冲队列
2023-07-26 16:58:14 +08:00
func (w *wsConnectItem) sendToOutChan(data []byte) {
select {
case <-w.closeChan:
return
case w.outChan <- data:
2023-08-15 17:40:27 +08:00
return
2023-08-28 15:47:25 +08:00
}
}
// 发送接受到的消息到入口缓冲队列中
func (w *wsConnectItem) sendToInChan(data []byte) {
select {
case <-w.closeChan: //关闭了
return
case w.inChan <- data:
return
2023-07-26 12:27:34 +08:00
}
}
2023-08-22 18:31:25 +08:00
// 格式化为websocket标准返回格式
2023-08-23 15:08:45 +08:00
func (w *wsConnectItem) respondDataFormat(msgType constants.Websocket, data interface{}) []byte {
2023-08-07 11:25:06 +08:00
d := websocket_data.DataTransferData{
2023-07-27 17:33:50 +08:00
T: msgType,
D: data,
}
b, _ := json.Marshal(d)
return b
}
2023-08-28 15:50:18 +08:00
// 处理入口缓冲队列中不同类型的数据(分发处理)
2023-08-30 17:07:14 +08:00
func (w *wsConnectItem) allocationProcessing(data []byte) {
2023-08-07 11:25:06 +08:00
var parseInfo websocket_data.DataTransferData
2023-07-26 15:08:43 +08:00
if err := json.Unmarshal(data, &parseInfo); err != nil {
2023-08-24 17:23:41 +08:00
w.incomeDataFormatErrResponse("invalid format of income message:" + string(data))
2023-08-15 18:14:44 +08:00
logx.Error("invalid format of websocket message:", err)
2023-07-26 15:08:43 +08:00
return
}
2023-07-26 16:47:53 +08:00
d, _ := json.Marshal(parseInfo.D)
2023-08-30 17:40:40 +08:00
//获取工厂实例
processor := w.newAllocationProcessor(parseInfo.T)
2023-08-30 18:31:20 +08:00
if processor == nil {
logx.Error("未知消息类型:", string(data))
return
}
2023-08-30 17:40:40 +08:00
//执行工厂方法
2023-08-30 18:31:20 +08:00
processor.allocationMessage(w, d)
2023-07-26 15:08:43 +08:00
}