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
1 year 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.
|
||
|
|
||
1 year ago
|
package msggateway
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
11 months ago
|
"fmt"
|
||
7 months ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/webhook"
|
||
|
pbAuth "github.com/openimsdk/protocol/auth"
|
||
|
"github.com/openimsdk/tools/mcontext"
|
||
1 year ago
|
"net/http"
|
||
|
"sync"
|
||
|
"sync/atomic"
|
||
|
"time"
|
||
|
|
||
9 months ago
|
"github.com/go-playground/validator/v10"
|
||
1 year ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/prommetrics"
|
||
7 months ago
|
"github.com/openimsdk/open-im-server/v3/pkg/common/servererrs"
|
||
1 year ago
|
"github.com/openimsdk/open-im-server/v3/pkg/rpcclient"
|
||
7 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"
|
||
9 months ago
|
"golang.org/x/sync/errgroup"
|
||
1 year ago
|
)
|
||
|
|
||
|
type LongConnServer interface {
|
||
9 months ago
|
Run(done chan error) error
|
||
1 year ago
|
wsHandler(w http.ResponseWriter, r *http.Request)
|
||
|
GetUserAllCons(userID string) ([]*Client, bool)
|
||
|
GetUserPlatformCons(userID string, platform int) ([]*Client, bool, bool)
|
||
12 months ago
|
Validate(s any) error
|
||
7 months ago
|
SetDiscoveryRegistry(client discovery.SvcDiscoveryRegistry, config *Config)
|
||
1 year ago
|
KickUserConn(client *Client) error
|
||
1 year ago
|
UnRegister(c *Client)
|
||
1 year ago
|
SetKickHandlerInfo(i *kickHandler)
|
||
1 year ago
|
Compressor
|
||
|
Encoder
|
||
|
MessageHandler
|
||
|
}
|
||
|
|
||
|
type WsServer struct {
|
||
7 months ago
|
msgGatewayConfig *Config
|
||
1 year 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
|
||
1 year ago
|
handshakeTimeout time.Duration
|
||
1 year ago
|
writeBufferSize int
|
||
1 year ago
|
validate *validator.Validate
|
||
1 year ago
|
userClient *rpcclient.UserRpcClient
|
||
7 months ago
|
authClient *rpcclient.Auth
|
||
|
disCov discovery.SvcDiscoveryRegistry
|
||
1 year ago
|
Compressor
|
||
|
Encoder
|
||
|
MessageHandler
|
||
7 months ago
|
webhookClient *webhook.Client
|
||
1 year ago
|
}
|
||
9 months ago
|
|
||
1 year ago
|
type kickHandler struct {
|
||
|
clientOK bool
|
||
|
oldClients []*Client
|
||
|
newClient *Client
|
||
|
}
|
||
|
|
||
7 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:
|
||
7 months ago
|
ws.webhookAfterUserOnline(ctx, &ws.msgGatewayConfig.WebhooksConfig.AfterUserOnline, client.UserID, client.PlatformID, client.IsBackground, client.ctx.GetConnID())
|
||
1 year ago
|
case constant.Offline:
|
||
7 months ago
|
ws.webhookAfterUserOffline(ctx, &ws.msgGatewayConfig.WebhooksConfig.AfterUserOffline, client.UserID, client.PlatformID, client.ctx.GetConnID())
|
||
1 year ago
|
}
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
1 year ago
|
func (ws *WsServer) UnRegister(c *Client) {
|
||
|
ws.unregisterChan <- c
|
||
|
}
|
||
|
|
||
7 months ago
|
func (ws *WsServer) Validate(_ any) error {
|
||
1 year 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)
|
||
|
}
|
||
|
|
||
7 months ago
|
func NewWsServer(msgGatewayConfig *Config, opts ...Option) (*WsServer, error) {
|
||
1 year ago
|
var config configs
|
||
|
for _, o := range opts {
|
||
|
o(&config)
|
||
|
}
|
||
|
v := validator.New()
|
||
|
return &WsServer{
|
||
7 months ago
|
msgGatewayConfig: msgGatewayConfig,
|
||
1 year ago
|
port: config.port,
|
||
|
wsMaxConnNum: config.maxConnNum,
|
||
1 year ago
|
writeBufferSize: config.writeBufferSize,
|
||
1 year ago
|
handshakeTimeout: config.handshakeTimeout,
|
||
|
clientPool: sync.Pool{
|
||
12 months ago
|
New: func() any {
|
||
1 year 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(),
|
||
7 months ago
|
webhookClient: webhook.NewWebhookClient(msgGatewayConfig.WebhooksConfig.URL),
|
||
1 year ago
|
}, nil
|
||
|
}
|
||
1 year ago
|
|
||
9 months ago
|
func (ws *WsServer) Run(done chan error) error {
|
||
12 months ago
|
var (
|
||
9 months ago
|
client *Client
|
||
|
netErr error
|
||
|
shutdownDone = make(chan struct{}, 1)
|
||
12 months ago
|
)
|
||
|
|
||
7 months ago
|
server := http.Server{Addr: ":" + stringutil.IntToString(ws.port), Handler: nil}
|
||
12 months ago
|
|
||
9 months ago
|
go func() {
|
||
1 year ago
|
for {
|
||
|
select {
|
||
9 months ago
|
case <-shutdownDone:
|
||
|
return
|
||
1 year 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)
|
||
1 year ago
|
}
|
||
|
}
|
||
9 months ago
|
}()
|
||
|
netDone := make(chan struct{}, 1)
|
||
12 months ago
|
go func() {
|
||
9 months ago
|
http.HandleFunc("/", ws.wsHandler)
|
||
|
err := server.ListenAndServe()
|
||
7 months ago
|
defer close(netDone)
|
||
9 months ago
|
if err != nil && err != http.ErrServerClosed {
|
||
7 months ago
|
netErr = errs.WrapMsg(err, "ws start err", server.Addr)
|
||
9 months ago
|
}
|
||
1 year ago
|
}()
|
||
9 months ago
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||
|
defer cancel()
|
||
|
var err error
|
||
12 months ago
|
select {
|
||
9 months ago
|
case err = <-done:
|
||
|
sErr := server.Shutdown(ctx)
|
||
|
if sErr != nil {
|
||
7 months ago
|
return errs.WrapMsg(sErr, "shutdown err")
|
||
9 months ago
|
}
|
||
|
close(shutdownDone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
case <-netDone:
|
||
12 months ago
|
}
|
||
9 months ago
|
return netErr
|
||
12 months ago
|
|
||
1 year ago
|
}
|
||
|
|
||
1 year ago
|
var concurrentRequest = 3
|
||
|
|
||
1 year ago
|
func (ws *WsServer) sendUserOnlineInfoToOtherNode(ctx context.Context, client *Client) error {
|
||
7 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 {
|
||
6 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
|
||
|
}
|
||
|
|
||
1 year 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)
|
||
1 year ago
|
} else {
|
||
1 year ago
|
ws.multiTerminalLoginChecker(clientOK, oldClients, client)
|
||
1 year ago
|
log.ZDebug(client.ctx, "user exist", "userID", client.UserID, "platformID", client.PlatformID)
|
||
|
if clientOK {
|
||
|
ws.clients.Set(client.UserID, client)
|
||
9 months ago
|
// There is already a connection to the platform
|
||
7 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)
|
||
1 year ago
|
} else {
|
||
|
ws.clients.Set(client.UserID, client)
|
||
1 year ago
|
ws.onlineUserConnNum.Add(1)
|
||
1 year ago
|
}
|
||
|
}
|
||
1 year ago
|
|
||
|
wg := sync.WaitGroup{}
|
||
6 months ago
|
log.ZDebug(client.ctx, "ws.msgGatewayConfig.Discovery.Enable", ws.msgGatewayConfig.Discovery.Enable)
|
||
|
|
||
|
if ws.msgGatewayConfig.Discovery.Enable != "k8s" {
|
||
11 months ago
|
wg.Add(1)
|
||
|
go func() {
|
||
|
defer wg.Done()
|
||
|
_ = ws.sendUserOnlineInfoToOtherNode(client.ctx, client)
|
||
|
}()
|
||
|
}
|
||
7 months ago
|
|
||
1 year ago
|
wg.Add(1)
|
||
|
go func() {
|
||
|
defer wg.Done()
|
||
|
ws.SetUserOnlineStatus(client.ctx, client, constant.Online)
|
||
|
}()
|
||
|
|
||
|
wg.Wait()
|
||
|
|
||
1 year ago
|
log.ZInfo(
|
||
|
client.ctx,
|
||
|
"user online",
|
||
|
"online user Num",
|
||
1 year ago
|
ws.onlineUserNum.Load(),
|
||
1 year ago
|
"online user conn Num",
|
||
1 year ago
|
ws.onlineUserConnNum.Load(),
|
||
1 year ago
|
)
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
1 year 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) {
|
||
7 months ago
|
switch ws.msgGatewayConfig.MsgGateway.MultiLoginPolicy {
|
||
1 year ago
|
case constant.DefalutNotKick:
|
||
|
case constant.PCAndOther:
|
||
1 year ago
|
if constant.PlatformIDToClass(newClient.PlatformID) == constant.TerminalPC {
|
||
1 year ago
|
return
|
||
|
}
|
||
|
fallthrough
|
||
|
case constant.AllLoginButSameTermKick:
|
||
1 year ago
|
if !clientOK {
|
||
|
return
|
||
|
}
|
||
11 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)
|
||
1 year ago
|
}
|
||
1 year ago
|
}
|
||
7 months ago
|
ctx := mcontext.WithMustInfoCtx(
|
||
|
[]string{newClient.ctx.GetOperationID(), newClient.ctx.GetUserID(),
|
||
|
constant.PlatformIDToName(newClient.PlatformID), newClient.ctx.GetConnID()},
|
||
1 year ago
|
)
|
||
7 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
|
}
|
||
1 year ago
|
}
|
||
|
}
|
||
1 year ago
|
|
||
1 year 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()
|
||
1 year ago
|
}
|
||
1 year ago
|
ws.onlineUserConnNum.Add(-1)
|
||
1 year ago
|
ws.SetUserOnlineStatus(client.ctx, client, constant.Offline)
|
||
7 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(),
|
||
1 year ago
|
)
|
||
1 year ago
|
}
|
||
|
|
||
7 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))
|
||
1 year ago
|
}
|
||
7 months ago
|
if resp.PlatformID != platformID {
|
||
|
return servererrs.ErrTokenInvalid.WrapMsg(fmt.Sprintf("token platform %d != platformID %d", resp.PlatformID, platformID))
|
||
1 year ago
|
}
|
||
7 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
|
||
1 year ago
|
}
|
||
7 months ago
|
|
||
|
// Parse essential arguments (e.g., user ID, Token)
|
||
|
err := connContext.ParseEssentialArgs()
|
||
1 year ago
|
if err != nil {
|
||
7 months ago
|
// If there's an error during parsing, return an error via HTTP and stop processing
|
||
|
|
||
|
httpError(connContext, err)
|
||
|
return
|
||
1 year ago
|
}
|
||
7 months ago
|
|
||
|
// Call the authentication client to parse the Token obtained from the context
|
||
|
resp, err := ws.authClient.ParseToken(connContext, connContext.GetToken())
|
||
1 year ago
|
if err != nil {
|
||
7 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
|
||
|
}
|
||
1 year ago
|
}
|
||
7 months ago
|
// If sending via WebSocket is not required or fails, return the error via HTTP and stop processing
|
||
|
httpError(connContext, err)
|
||
|
return
|
||
1 year ago
|
}
|
||
1 year ago
|
|
||
7 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
|
||
|
}
|
||
11 months ago
|
|
||
7 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
|
||
11 months ago
|
} else {
|
||
7 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
|
||
|
}
|
||
1 year ago
|
}
|
||
|
}
|
||
7 months ago
|
|
||
|
// Retrieve a client object from the client pool, reset its state, and associate it with the current WebSocket long connection
|
||
1 year ago
|
client := ws.clientPool.Get().(*Client)
|
||
7 months ago
|
client.ResetClient(connContext, wsLongConn, ws)
|
||
|
|
||
|
// Register the client with the server and start message processing
|
||
1 year ago
|
ws.registerChan <- client
|
||
|
go client.readMessage()
|
||
|
}
|