You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
446 lines
14 KiB
446 lines
14 KiB
2 years ago
|
// Copyright © 2023 OpenIM. All rights reserved.
|
||
|
//
|
||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||
|
// you may not use this file except in compliance with the License.
|
||
|
// You may obtain a copy of the License at
|
||
|
//
|
||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||
|
//
|
||
|
// Unless required by applicable law or agreed to in writing, software
|
||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
// See the License for the specific language governing permissions and
|
||
|
// limitations under the License.
|
||
|
|
||
2 years ago
|
package msggateway
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
12 months ago
|
"fmt"
|
||
8 months ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/webhook"
|
||
|
pbAuth "github.com/openimsdk/protocol/auth"
|
||
|
"github.com/openimsdk/tools/mcontext"
|
||
2 years ago
|
"net/http"
|
||
|
"sync"
|
||
|
"sync/atomic"
|
||
|
"time"
|
||
|
|
||
10 months ago
|
"github.com/go-playground/validator/v10"
|
||
1 year ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics"
|
||
8 months ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/servererrs"
|
||
1 year ago
|
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
|
||
8 months ago
|
"github.com/openimsdk/protocol/constant"
|
||
|
"github.com/openimsdk/protocol/msggateway"
|
||
|
"github.com/openimsdk/tools/discovery"
|
||
|
"github.com/openimsdk/tools/errs"
|
||
|
"github.com/openimsdk/tools/log"
|
||
|
"github.com/openimsdk/tools/utils/stringutil"
|
||
10 months ago
|
"golang.org/x/sync/errgroup"
|
||
2 years ago
|
)
|
||
|
|
||
|
type LongConnServer interface {
|
||
10 months ago
|
Run(done chan error) error
|
||
2 years ago
|
wsHandler(w http.ResponseWriter, r *http.Request)
|
||
|
GetUserAllCons(userID string) ([]*Client, bool)
|
||
|
GetUserPlatformCons(userID string, platform int) ([]*Client, bool, bool)
|
||
1 year ago
|
Validate(s any) error
|
||
8 months ago
|
SetDiscoveryRegistry(client discovery.SvcDiscoveryRegistry, config *Config)
|
||
1 year ago
|
KickUserConn(client *Client) error
|
||
2 years ago
|
UnRegister(c *Client)
|
||
1 year ago
|
SetKickHandlerInfo(i *kickHandler)
|
||
2 years ago
|
Compressor
|
||
|
Encoder
|
||
|
MessageHandler
|
||
|
}
|
||
|
|
||
|
type WsServer struct {
|
||
8 months ago
|
msgGatewayConfig *Config
|
||
2 years ago
|
port int
|
||
|
wsMaxConnNum int64
|
||
|
registerChan chan *Client
|
||
|
unregisterChan chan *Client
|
||
|
kickHandlerChan chan *kickHandler
|
||
|
clients *UserMap
|
||
|
clientPool sync.Pool
|
||
1 year ago
|
onlineUserNum atomic.Int64
|
||
|
onlineUserConnNum atomic.Int64
|
||
2 years ago
|
handshakeTimeout time.Duration
|
||
1 year ago
|
writeBufferSize int
|
||
2 years ago
|
validate *validator.Validate
|
||
1 year ago
|
userClient *rpcclient.UserRpcClient
|
||
8 months ago
|
authClient *rpcclient.Auth
|
||
|
disCov discovery.SvcDiscoveryRegistry
|
||
2 years ago
|
Compressor
|
||
|
Encoder
|
||
|
MessageHandler
|
||
8 months ago
|
webhookClient *webhook.Client
|
||
2 years ago
|
}
|
||
10 months ago
|
|
||
2 years ago
|
type kickHandler struct {
|
||
|
clientOK bool
|
||
|
oldClients []*Client
|
||
|
newClient *Client
|
||
|
}
|
||
|
|
||
8 months ago
|
func (ws *WsServer) SetDiscoveryRegistry(disCov discovery.SvcDiscoveryRegistry, config *Config) {
|
||
|
ws.MessageHandler = NewGrpcHandler(ws.validate, disCov, &config.Share.RpcRegisterName)
|
||
|
u := rpcclient.NewUserRpcClient(disCov, config.Share.RpcRegisterName.User, config.Share.IMAdminUserID)
|
||
|
ws.authClient = rpcclient.NewAuth(disCov, config.Share.RpcRegisterName.Auth)
|
||
1 year ago
|
ws.userClient = &u
|
||
1 year ago
|
ws.disCov = disCov
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
1 year ago
|
func (ws *WsServer) SetUserOnlineStatus(ctx context.Context, client *Client, status int32) {
|
||
|
err := ws.userClient.SetUserStatus(ctx, client.UserID, status, client.PlatformID)
|
||
|
if err != nil {
|
||
|
log.ZWarn(ctx, "SetUserStatus err", err)
|
||
|
}
|
||
|
switch status {
|
||
|
case constant.Online:
|
||
8 months ago
|
ws.webhookAfterUserOnline(ctx, &ws.msgGatewayConfig.WebhooksConfig.AfterUserOnline, client.UserID, client.PlatformID, client.IsBackground, client.ctx.GetConnID())
|
||
1 year ago
|
case constant.Offline:
|
||
8 months ago
|
ws.webhookAfterUserOffline(ctx, &ws.msgGatewayConfig.WebhooksConfig.AfterUserOffline, client.UserID, client.PlatformID, client.ctx.GetConnID())
|
||
1 year ago
|
}
|
||
2 years ago
|
}
|
||
1 year ago
|
|
||
2 years ago
|
func (ws *WsServer) UnRegister(c *Client) {
|
||
|
ws.unregisterChan <- c
|
||
|
}
|
||
|
|
||
8 months ago
|
func (ws *WsServer) Validate(_ any) error {
|
||
2 years ago
|
return nil
|
||
|
}
|
||
|
|
||
|
func (ws *WsServer) GetUserAllCons(userID string) ([]*Client, bool) {
|
||
|
return ws.clients.GetAll(userID)
|
||
|
}
|
||
|
|
||
|
func (ws *WsServer) GetUserPlatformCons(userID string, platform int) ([]*Client, bool, bool) {
|
||
|
return ws.clients.Get(userID, platform)
|
||
|
}
|
||
|
|
||
8 months ago
|
func NewWsServer(msgGatewayConfig *Config, opts ...Option) (*WsServer, error) {
|
||
2 years ago
|
var config configs
|
||
|
for _, o := range opts {
|
||
|
o(&config)
|
||
|
}
|
||
|
v := validator.New()
|
||
|
return &WsServer{
|
||
8 months ago
|
msgGatewayConfig: msgGatewayConfig,
|
||
2 years ago
|
port: config.port,
|
||
|
wsMaxConnNum: config.maxConnNum,
|
||
1 year ago
|
writeBufferSize: config.writeBufferSize,
|
||
2 years ago
|
handshakeTimeout: config.handshakeTimeout,
|
||
|
clientPool: sync.Pool{
|
||
1 year ago
|
New: func() any {
|
||
2 years ago
|
return new(Client)
|
||
|
},
|
||
|
},
|
||
|
registerChan: make(chan *Client, 1000),
|
||
|
unregisterChan: make(chan *Client, 1000),
|
||
|
kickHandlerChan: make(chan *kickHandler, 1000),
|
||
|
validate: v,
|
||
|
clients: newUserMap(),
|
||
|
Compressor: NewGzipCompressor(),
|
||
|
Encoder: NewGobEncoder(),
|
||
8 months ago
|
webhookClient: webhook.NewWebhookClient(msgGatewayConfig.WebhooksConfig.URL),
|
||
2 years ago
|
}, nil
|
||
|
}
|
||
1 year ago
|
|
||
10 months ago
|
func (ws *WsServer) Run(done chan error) error {
|
||
1 year ago
|
var (
|
||
10 months ago
|
client *Client
|
||
|
netErr error
|
||
|
shutdownDone = make(chan struct{}, 1)
|
||
1 year ago
|
)
|
||
|
|
||
8 months ago
|
server := http.Server{Addr: ":" + stringutil.IntToString(ws.port), Handler: nil}
|
||
1 year ago
|
|
||
10 months ago
|
go func() {
|
||
2 years ago
|
for {
|
||
|
select {
|
||
10 months ago
|
case <-shutdownDone:
|
||
|
return
|
||
2 years ago
|
case client = <-ws.registerChan:
|
||
|
ws.registerClient(client)
|
||
|
case client = <-ws.unregisterChan:
|
||
|
ws.unregisterClient(client)
|
||
|
case onlineInfo := <-ws.kickHandlerChan:
|
||
1 year ago
|
ws.multiTerminalLoginChecker(onlineInfo.clientOK, onlineInfo.oldClients, onlineInfo.newClient)
|
||
2 years ago
|
}
|
||
|
}
|
||
10 months ago
|
}()
|
||
|
netDone := make(chan struct{}, 1)
|
||
1 year ago
|
go func() {
|
||
10 months ago
|
http.HandleFunc("/", ws.wsHandler)
|
||
|
err := server.ListenAndServe()
|
||
8 months ago
|
defer close(netDone)
|
||
10 months ago
|
if err != nil && err != http.ErrServerClosed {
|
||
8 months ago
|
netErr = errs.WrapMsg(err, "ws start err", server.Addr)
|
||
10 months ago
|
}
|
||
2 years ago
|
}()
|
||
10 months ago
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||
|
defer cancel()
|
||
|
var err error
|
||
1 year ago
|
select {
|
||
10 months ago
|
case err = <-done:
|
||
|
sErr := server.Shutdown(ctx)
|
||
|
if sErr != nil {
|
||
8 months ago
|
return errs.WrapMsg(sErr, "shutdown err")
|
||
10 months ago
|
}
|
||
|
close(shutdownDone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
case <-netDone:
|
||
1 year ago
|
}
|
||
10 months ago
|
return netErr
|
||
1 year ago
|
|
||
2 years ago
|
}
|
||
|
|
||
1 year ago
|
var concurrentRequest = 3
|
||
|
|
||
1 year ago
|
func (ws *WsServer) sendUserOnlineInfoToOtherNode(ctx context.Context, client *Client) error {
|
||
8 months ago
|
conns, err := ws.disCov.GetConns(ctx, ws.msgGatewayConfig.Share.RpcRegisterName.MessageGateway)
|
||
1 year ago
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
1 year ago
|
|
||
|
wg := errgroup.Group{}
|
||
|
wg.SetLimit(concurrentRequest)
|
||
|
|
||
1 year ago
|
// Online push user online message to other node
|
||
|
for _, v := range conns {
|
||
8 months ago
|
v := v
|
||
|
log.ZDebug(ctx, " sendUserOnlineInfoToOtherNode conn ", "target", v.Target())
|
||
1 year ago
|
if v.Target() == ws.disCov.GetSelfConnTarget() {
|
||
|
log.ZDebug(ctx, "Filter out this node", "node", v.Target())
|
||
|
continue
|
||
|
}
|
||
1 year ago
|
|
||
|
wg.Go(func() error {
|
||
|
msgClient := msggateway.NewMsgGatewayClient(v)
|
||
|
_, err := msgClient.MultiTerminalLoginCheck(ctx, &msggateway.MultiTerminalLoginCheckReq{
|
||
|
UserID: client.UserID,
|
||
|
PlatformID: int32(client.PlatformID), Token: client.token,
|
||
|
})
|
||
|
if err != nil {
|
||
|
log.ZWarn(ctx, "MultiTerminalLoginCheck err", err, "node", v.Target())
|
||
|
}
|
||
|
return nil
|
||
1 year ago
|
})
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
|
_ = wg.Wait()
|
||
1 year ago
|
return nil
|
||
|
}
|
||
1 year ago
|
|
||
1 year ago
|
func (ws *WsServer) SetKickHandlerInfo(i *kickHandler) {
|
||
|
ws.kickHandlerChan <- i
|
||
|
}
|
||
|
|
||
2 years ago
|
func (ws *WsServer) registerClient(client *Client) {
|
||
|
var (
|
||
|
userOK bool
|
||
|
clientOK bool
|
||
|
oldClients []*Client
|
||
|
)
|
||
|
oldClients, userOK, clientOK = ws.clients.Get(client.UserID, client.PlatformID)
|
||
|
if !userOK {
|
||
|
ws.clients.Set(client.UserID, client)
|
||
|
log.ZDebug(client.ctx, "user not exist", "userID", client.UserID, "platformID", client.PlatformID)
|
||
1 year ago
|
prommetrics.OnlineUserGauge.Add(1)
|
||
1 year ago
|
ws.onlineUserNum.Add(1)
|
||
|
ws.onlineUserConnNum.Add(1)
|
||
2 years ago
|
} else {
|
||
1 year ago
|
ws.multiTerminalLoginChecker(clientOK, oldClients, client)
|
||
2 years ago
|
log.ZDebug(client.ctx, "user exist", "userID", client.UserID, "platformID", client.PlatformID)
|
||
|
if clientOK {
|
||
|
ws.clients.Set(client.UserID, client)
|
||
10 months ago
|
// There is already a connection to the platform
|
||
8 months ago
|
log.ZInfo(client.ctx, "repeat login", "userID", client.UserID, "platformID",
|
||
|
client.PlatformID, "old remote addr", getRemoteAdders(oldClients))
|
||
1 year ago
|
ws.onlineUserConnNum.Add(1)
|
||
2 years ago
|
} else {
|
||
|
ws.clients.Set(client.UserID, client)
|
||
1 year ago
|
ws.onlineUserConnNum.Add(1)
|
||
2 years ago
|
}
|
||
|
}
|
||
1 year ago
|
|
||
|
wg := sync.WaitGroup{}
|
||
8 months ago
|
log.ZDebug(client.ctx, "ws.msgGatewayConfig.Discovery.Enable", ws.msgGatewayConfig.Discovery.Enable)
|
||
|
|
||
|
if ws.msgGatewayConfig.Discovery.Enable != "k8s" {
|
||
1 year ago
|
wg.Add(1)
|
||
|
go func() {
|
||
|
defer wg.Done()
|
||
|
_ = ws.sendUserOnlineInfoToOtherNode(client.ctx, client)
|
||
|
}()
|
||
|
}
|
||
8 months ago
|
|
||
1 year ago
|
wg.Add(1)
|
||
|
go func() {
|
||
|
defer wg.Done()
|
||
|
ws.SetUserOnlineStatus(client.ctx, client, constant.Online)
|
||
|
}()
|
||
|
|
||
|
wg.Wait()
|
||
|
|
||
2 years ago
|
log.ZInfo(
|
||
|
client.ctx,
|
||
|
"user online",
|
||
|
"online user Num",
|
||
1 year ago
|
ws.onlineUserNum.Load(),
|
||
2 years ago
|
"online user conn Num",
|
||
1 year ago
|
ws.onlineUserConnNum.Load(),
|
||
2 years ago
|
)
|
||
2 years ago
|
}
|
||
1 year ago
|
|
||
2 years ago
|
func getRemoteAdders(client []*Client) string {
|
||
|
var ret string
|
||
|
for i, c := range client {
|
||
|
if i == 0 {
|
||
|
ret = c.ctx.GetRemoteAddr()
|
||
|
} else {
|
||
|
ret += "@" + c.ctx.GetRemoteAddr()
|
||
|
}
|
||
|
}
|
||
|
return ret
|
||
|
}
|
||
|
|
||
1 year ago
|
func (ws *WsServer) KickUserConn(client *Client) error {
|
||
|
ws.clients.deleteClients(client.UserID, []*Client{client})
|
||
|
return client.KickOnlineMessage()
|
||
|
}
|
||
|
|
||
|
func (ws *WsServer) multiTerminalLoginChecker(clientOK bool, oldClients []*Client, newClient *Client) {
|
||
8 months ago
|
switch ws.msgGatewayConfig.MsgGateway.MultiLoginPolicy {
|
||
2 years ago
|
case constant.DefalutNotKick:
|
||
|
case constant.PCAndOther:
|
||
1 year ago
|
if constant.PlatformIDToClass(newClient.PlatformID) == constant.TerminalPC {
|
||
2 years ago
|
return
|
||
|
}
|
||
|
fallthrough
|
||
|
case constant.AllLoginButSameTermKick:
|
||
1 year ago
|
if !clientOK {
|
||
|
return
|
||
|
}
|
||
12 months ago
|
ws.clients.deleteClients(newClient.UserID, oldClients)
|
||
1 year ago
|
for _, c := range oldClients {
|
||
|
err := c.KickOnlineMessage()
|
||
|
if err != nil {
|
||
|
log.ZWarn(c.ctx, "KickOnlineMessage", err)
|
||
2 years ago
|
}
|
||
1 year ago
|
}
|
||
8 months ago
|
ctx := mcontext.WithMustInfoCtx(
|
||
|
[]string{newClient.ctx.GetOperationID(), newClient.ctx.GetUserID(),
|
||
|
constant.PlatformIDToName(newClient.PlatformID), newClient.ctx.GetConnID()},
|
||
1 year ago
|
)
|
||
8 months ago
|
if _, err := ws.authClient.InvalidateToken(ctx, newClient.token, newClient.UserID, newClient.PlatformID); err != nil {
|
||
|
log.ZWarn(newClient.ctx, "InvalidateToken err", err, "userID", newClient.UserID,
|
||
|
"platformID", newClient.PlatformID)
|
||
1 year ago
|
}
|
||
2 years ago
|
}
|
||
|
}
|
||
1 year ago
|
|
||
2 years ago
|
func (ws *WsServer) unregisterClient(client *Client) {
|
||
|
defer ws.clientPool.Put(client)
|
||
|
isDeleteUser := ws.clients.delete(client.UserID, client.ctx.GetRemoteAddr())
|
||
|
if isDeleteUser {
|
||
1 year ago
|
ws.onlineUserNum.Add(-1)
|
||
1 year ago
|
prommetrics.OnlineUserGauge.Dec()
|
||
2 years ago
|
}
|
||
1 year ago
|
ws.onlineUserConnNum.Add(-1)
|
||
1 year ago
|
ws.SetUserOnlineStatus(client.ctx, client, constant.Offline)
|
||
8 months ago
|
log.ZInfo(client.ctx, "user offline", "close reason", client.closedErr, "online user Num",
|
||
|
ws.onlineUserNum.Load(), "online user conn Num",
|
||
1 year ago
|
ws.onlineUserConnNum.Load(),
|
||
2 years ago
|
)
|
||
2 years ago
|
}
|
||
|
|
||
8 months ago
|
// validateRespWithRequest checks if the response matches the expected userID and platformID.
|
||
|
func (ws *WsServer) validateRespWithRequest(ctx *UserConnContext, resp *pbAuth.ParseTokenResp) error {
|
||
|
userID := ctx.GetUserID()
|
||
|
platformID := stringutil.StringToInt32(ctx.GetPlatformID())
|
||
|
if resp.UserID != userID {
|
||
|
return servererrs.ErrTokenInvalid.WrapMsg(fmt.Sprintf("token uid %s != userID %s", resp.UserID, userID))
|
||
2 years ago
|
}
|
||
8 months ago
|
if resp.PlatformID != platformID {
|
||
|
return servererrs.ErrTokenInvalid.WrapMsg(fmt.Sprintf("token platform %d != platformID %d", resp.PlatformID, platformID))
|
||
2 years ago
|
}
|
||
8 months ago
|
return nil
|
||
|
}
|
||
|
|
||
|
func (ws *WsServer) wsHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
// Create a new connection context
|
||
|
connContext := newContext(w, r)
|
||
|
|
||
|
// Check if the current number of online user connections exceeds the maximum limit
|
||
|
if ws.onlineUserConnNum.Load() >= ws.wsMaxConnNum {
|
||
|
// If it exceeds the maximum connection number, return an error via HTTP and stop processing
|
||
|
httpError(connContext, servererrs.ErrConnOverMaxNumLimit.WrapMsg("over max conn num limit"))
|
||
|
return
|
||
2 years ago
|
}
|
||
8 months ago
|
|
||
|
// Parse essential arguments (e.g., user ID, Token)
|
||
|
err := connContext.ParseEssentialArgs()
|
||
2 years ago
|
if err != nil {
|
||
8 months ago
|
// If there's an error during parsing, return an error via HTTP and stop processing
|
||
|
|
||
|
httpError(connContext, err)
|
||
|
return
|
||
2 years ago
|
}
|
||
8 months ago
|
|
||
|
// Call the authentication client to parse the Token obtained from the context
|
||
|
resp, err := ws.authClient.ParseToken(connContext, connContext.GetToken())
|
||
2 years ago
|
if err != nil {
|
||
8 months ago
|
// If there's an error parsing the Token, decide whether to send the error message via WebSocket based on the context flag
|
||
|
shouldSendError := connContext.ShouldSendResp()
|
||
|
if shouldSendError {
|
||
|
// Create a WebSocket connection object and attempt to send the error message via WebSocket
|
||
|
wsLongConn := newGWebSocket(WebSocket, ws.handshakeTimeout, ws.writeBufferSize)
|
||
|
if err := wsLongConn.RespondWithError(err, w, r); err == nil {
|
||
|
// If the error message is successfully sent via WebSocket, stop processing
|
||
|
return
|
||
|
}
|
||
2 years ago
|
}
|
||
8 months ago
|
// If sending via WebSocket is not required or fails, return the error via HTTP and stop processing
|
||
|
httpError(connContext, err)
|
||
|
return
|
||
2 years ago
|
}
|
||
1 year ago
|
|
||
8 months ago
|
// Validate the authentication response matches the request (e.g., user ID and platform ID)
|
||
|
err = ws.validateRespWithRequest(connContext, resp)
|
||
|
if err != nil {
|
||
|
// If validation fails, return an error via HTTP and stop processing
|
||
|
httpError(connContext, err)
|
||
|
return
|
||
|
}
|
||
12 months ago
|
|
||
8 months ago
|
// Create a WebSocket long connection object
|
||
|
wsLongConn := newGWebSocket(WebSocket, ws.handshakeTimeout, ws.writeBufferSize)
|
||
|
if err := wsLongConn.GenerateLongConn(w, r); err != nil {
|
||
|
//If the creation of the long connection fails, the error is handled internally during the handshake process.
|
||
|
log.ZWarn(connContext, "long connection fails", err)
|
||
|
return
|
||
12 months ago
|
} else {
|
||
8 months ago
|
// Check if a normal response should be sent via WebSocket
|
||
|
shouldSendSuccessResp := connContext.ShouldSendResp()
|
||
|
if shouldSendSuccessResp {
|
||
|
// Attempt to send a success message through WebSocket
|
||
|
if err := wsLongConn.RespondWithSuccess(); err != nil {
|
||
|
// If the success message is successfully sent, end further processing
|
||
|
return
|
||
|
}
|
||
2 years ago
|
}
|
||
|
}
|
||
8 months ago
|
|
||
|
// Retrieve a client object from the client pool, reset its state, and associate it with the current WebSocket long connection
|
||
2 years ago
|
client := ws.clientPool.Get().(*Client)
|
||
8 months ago
|
client.ResetClient(connContext, wsLongConn, ws)
|
||
|
|
||
|
// Register the client with the server and start message processing
|
||
2 years ago
|
ws.registerChan <- client
|
||
|
go client.readMessage()
|
||
|
}
|