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.
Open-IM-Server/internal/msgtransfer/online_history_msg_handler.go

338 lines
14 KiB

2 years ago
package msgtransfer
import (
2 years ago
"context"
2 years ago
"strconv"
"strings"
2 years ago
"sync"
"time"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/errs"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/config"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/constant"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/db/controller"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/kafka"
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/log"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/proto/sdkws"
"github.com/OpenIMSDK/Open-IM-Server/pkg/rpcclient"
2 years ago
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
"github.com/Shopify/sarama"
2 years ago
"github.com/go-redis/redis"
2 years ago
"google.golang.org/protobuf/proto"
)
2 years ago
const ConsumerMsgs = 3
2 years ago
const SourceMessages = 4
2 years ago
const MongoMessages = 5
const ChannelNum = 100
type MsgChannelValue struct {
2 years ago
uniqueKey string
ctx context.Context
ctxMsgList []*ContextMsg
}
2 years ago
type TriggerChannelValue struct {
2 years ago
ctx context.Context
cMsgList []*sarama.ConsumerMessage
}
2 years ago
type Cmd2Value struct {
3 years ago
Cmd int
Value interface{}
}
2 years ago
type ContextMsg struct {
2 years ago
message *sdkws.MsgData
2 years ago
ctx context.Context
}
2 years ago
type OnlineHistoryRedisConsumerHandler struct {
2 years ago
historyConsumerGroup *kafka.MConsumerGroup
chArrays [ChannelNum]chan Cmd2Value
3 years ago
msgDistributionCh chan Cmd2Value
2 years ago
singleMsgSuccessCount uint64
singleMsgFailedCount uint64
singleMsgSuccessCountMutex sync.Mutex
singleMsgFailedCountMutex sync.Mutex
2 years ago
msgDatabase controller.CommonMsgDatabase
2 years ago
conversationRpcClient *rpcclient.ConversationClient
groupRpcClient *rpcclient.GroupClient
}
2 years ago
func NewOnlineHistoryRedisConsumerHandler(database controller.CommonMsgDatabase, conversationRpcClient *rpcclient.ConversationClient, groupRpcClient *rpcclient.GroupClient) *OnlineHistoryRedisConsumerHandler {
2 years ago
var och OnlineHistoryRedisConsumerHandler
och.msgDatabase = database
3 years ago
och.msgDistributionCh = make(chan Cmd2Value) //no buffer channel
go och.MessagesDistributionHandle()
for i := 0; i < ChannelNum; i++ {
3 years ago
och.chArrays[i] = make(chan Cmd2Value, 50)
go och.Run(i)
}
2 years ago
och.conversationRpcClient = conversationRpcClient
2 years ago
och.groupRpcClient = groupRpcClient
2 years ago
och.historyConsumerGroup = kafka.NewMConsumerGroup(&kafka.MConsumerGroupConfig{KafkaVersion: sarama.V2_0_0_0,
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschat.Topic},
config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.ConsumerGroupID.MsgToRedis)
2 years ago
//statistics.NewStatistics(&och.singleMsgSuccessCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d second singleMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
2 years ago
return &och
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
for {
select {
case cmd := <-och.chArrays[channelID]:
switch cmd.Cmd {
2 years ago
case SourceMessages:
msgChannelValue := cmd.Value.(MsgChannelValue)
2 years ago
ctxMsgList := msgChannelValue.ctxMsgList
ctx := msgChannelValue.ctx
log.ZDebug(withAggregationCtx(ctx, ctxMsgList), "msg arrived channel", "channel id", channelID, "msgList length", len(ctxMsgList), "uniqueKey", msgChannelValue.uniqueKey)
2 years ago
storageMsgList, notStorageMsgList, storageNotificationList, notStorageNotificationList, modifyMsgList := och.getPushStorageMsgList(ctxMsgList)
2 years ago
log.ZDebug(ctx, "msg lens", "storageMsgList", len(storageMsgList), "notStorageMsgList", len(notStorageMsgList),
"storageNotificationList", len(storageNotificationList), "notStorageNotificationList", len(notStorageNotificationList), "modifyMsgList", len(modifyMsgList))
2 years ago
conversationIDMsg := utils.GetChatConversationIDByMsg(ctxMsgList[0].message)
conversationIDNotification := utils.GetNotificationConversationID(ctxMsgList[0].message)
och.handleMsg(ctx, msgChannelValue.uniqueKey, conversationIDMsg, storageMsgList, notStorageMsgList)
och.handleNotification(ctx, msgChannelValue.uniqueKey, conversationIDNotification, storageNotificationList, notStorageNotificationList)
if err := och.msgDatabase.MsgToModifyMQ(ctx, msgChannelValue.uniqueKey, conversationIDNotification, modifyMsgList); err != nil {
log.ZError(ctx, "msg to modify mq error", err, "uniqueKey", msgChannelValue.uniqueKey, "modifyMsgList", modifyMsgList)
}
}
}
}
}
// 获取消息/通知 存储的消息列表, 不存储并且推送的消息列表,
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) getPushStorageMsgList(totalMsgs []*ContextMsg) (storageMsgList, notStorageMsgList, storageNotificatoinList, notStorageNotificationList, modifyMsgList []*sdkws.MsgData) {
2 years ago
isStorage := func(msg *sdkws.MsgData) bool {
options2 := utils.Options(msg.Options)
if options2.IsHistory() {
return true
} else {
// if !(!options2.IsSenderSync() && conversationID == msg.MsgData.SendID) {
// return false
// }
return false
}
}
for _, v := range totalMsgs {
2 years ago
options := utils.Options(v.message.Options)
2 years ago
if !options.IsNotNotification() {
2 years ago
// clone msg from notificationMsg
if options.IsSendMsg() {
2 years ago
msg := proto.Clone(v.message).(*sdkws.MsgData)
// 消息
2 years ago
if v.message.Options != nil {
2 years ago
msg.Options = utils.NewMsgOptions()
2 years ago
}
2 years ago
if options.IsOfflinePush() {
v.message.Options = utils.WithOptions(utils.Options(v.message.Options), utils.WithOfflinePush(false))
msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithOfflinePush(true))
}
if options.IsUnreadCount() {
v.message.Options = utils.WithOptions(utils.Options(v.message.Options), utils.WithUnreadCount(false))
msg.Options = utils.WithOptions(utils.Options(msg.Options), utils.WithUnreadCount(true))
}
storageMsgList = append(storageMsgList, msg)
}
2 years ago
if isStorage(v.message) {
storageNotificatoinList = append(storageNotificatoinList, v.message)
} else {
2 years ago
notStorageNotificationList = append(notStorageNotificationList, v.message)
}
} else {
if isStorage(v.message) {
storageMsgList = append(storageMsgList, v.message)
} else {
notStorageMsgList = append(notStorageMsgList, v.message)
}
}
2 years ago
if v.message.ContentType == constant.ReactionMessageModifier || v.message.ContentType == constant.ReactionMessageDeleter {
modifyMsgList = append(modifyMsgList, v.message)
}
}
return
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) handleNotification(ctx context.Context, key, conversationID string, storageList, notStorageList []*sdkws.MsgData) {
och.toPushTopic(ctx, key, conversationID, notStorageList)
2 years ago
if len(storageList) > 0 {
2 years ago
lastSeq, _, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
2 years ago
if err != nil {
log.ZError(ctx, "notification batch insert to redis error", err, "conversationID", conversationID, "storageList", storageList)
2 years ago
return
}
2 years ago
log.ZDebug(ctx, "success to next topic", "conversationID", conversationID)
2 years ago
och.msgDatabase.MsgToMongoMQ(ctx, key, conversationID, storageList, lastSeq)
och.toPushTopic(ctx, key, conversationID, storageList)
2 years ago
}
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) toPushTopic(ctx context.Context, key, conversationID string, msgs []*sdkws.MsgData) {
2 years ago
for _, v := range msgs {
2 years ago
och.msgDatabase.MsgToPushMQ(ctx, key, conversationID, v)
2 years ago
}
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) handleMsg(ctx context.Context, key, conversationID string, storageList, notStorageList []*sdkws.MsgData) {
och.toPushTopic(ctx, key, conversationID, notStorageList)
if len(storageList) > 0 {
2 years ago
lastSeq, isNewConversation, err := och.msgDatabase.BatchInsertChat2Cache(ctx, conversationID, storageList)
2 years ago
if err != nil && errs.Unwrap(err) != redis.Nil {
2 years ago
log.ZError(ctx, "batch data insert to redis err", err, "storageMsgList", storageList)
och.singleMsgFailedCountMutex.Lock()
och.singleMsgFailedCount += uint64(len(storageList))
och.singleMsgFailedCountMutex.Unlock()
return
}
if isNewConversation {
2 years ago
if storageList[0].SessionType == constant.SuperGroupChatType {
log.ZInfo(ctx, "group chat first create conversation", "conversationID", conversationID)
userIDs, err := och.groupRpcClient.GetGroupMemberIDs(ctx, storageList[0].GroupID)
if err != nil {
2 years ago
log.ZWarn(ctx, "get group member ids error", err, "conversationID", conversationID)
} else {
if err := och.conversationRpcClient.GroupChatFirstCreateConversation(ctx, storageList[0].GroupID, userIDs); err != nil {
2 years ago
log.ZWarn(ctx, "single chat first create conversation error", err, "conversationID", conversationID)
}
2 years ago
}
2 years ago
} else {
if err := och.conversationRpcClient.SingleChatFirstCreateConversation(ctx, storageList[0].RecvID, storageList[0].SendID); err != nil {
2 years ago
log.ZWarn(ctx, "single chat first create conversation error", err, "conversationID", conversationID)
2 years ago
}
}
}
2 years ago
log.ZDebug(ctx, "success incr to next topic")
2 years ago
och.singleMsgSuccessCountMutex.Lock()
och.singleMsgSuccessCount += uint64(len(storageList))
och.singleMsgSuccessCountMutex.Unlock()
2 years ago
och.msgDatabase.MsgToMongoMQ(ctx, key, conversationID, storageList, lastSeq)
och.toPushTopic(ctx, key, conversationID, storageList)
}
2 years ago
}
func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
3 years ago
for {
2 years ago
aggregationMsgs := make(map[string][]*ContextMsg, ChannelNum)
3 years ago
select {
case cmd := <-och.msgDistributionCh:
switch cmd.Cmd {
case ConsumerMsgs:
triggerChannelValue := cmd.Value.(TriggerChannelValue)
2 years ago
ctx := triggerChannelValue.ctx
2 years ago
consumerMessages := triggerChannelValue.cMsgList
3 years ago
//Aggregation map[userid]message list
2 years ago
log.ZDebug(ctx, "batch messages come to distribution center", "length", len(consumerMessages))
3 years ago
for i := 0; i < len(consumerMessages); i++ {
2 years ago
ctxMsg := &ContextMsg{}
2 years ago
msgFromMQ := &sdkws.MsgData{}
err := proto.Unmarshal(consumerMessages[i].Value, msgFromMQ)
3 years ago
if err != nil {
2 years ago
log.ZError(ctx, "msg_transfer Unmarshal msg err", err, string(consumerMessages[i].Value))
continue
3 years ago
}
2 years ago
var arr []string
for i, header := range consumerMessages[i].Headers {
arr = append(arr, strconv.Itoa(i), string(header.Key), string(header.Value))
}
log.ZInfo(ctx, "consumer.kafka.GetContextWithMQHeader", "len", len(consumerMessages[i].Headers), "header", strings.Join(arr, ", "))
2 years ago
ctxMsg.ctx = kafka.GetContextWithMQHeader(consumerMessages[i].Headers)
2 years ago
ctxMsg.message = msgFromMQ
log.ZDebug(ctx, "single msg come to distribution center", "message", msgFromMQ, "key", string(consumerMessages[i].Key))
2 years ago
//aggregationMsgs[string(consumerMessages[i].Key)] = append(aggregationMsgs[string(consumerMessages[i].Key)], ctxMsg)
3 years ago
if oldM, ok := aggregationMsgs[string(consumerMessages[i].Key)]; ok {
2 years ago
oldM = append(oldM, ctxMsg)
3 years ago
aggregationMsgs[string(consumerMessages[i].Key)] = oldM
3 years ago
} else {
2 years ago
m := make([]*ContextMsg, 0, 100)
m = append(m, ctxMsg)
3 years ago
aggregationMsgs[string(consumerMessages[i].Key)] = m
3 years ago
}
}
2 years ago
log.ZDebug(ctx, "generate map list users len", "length", len(aggregationMsgs))
2 years ago
for uniqueKey, v := range aggregationMsgs {
3 years ago
if len(v) >= 0 {
2 years ago
hashCode := utils.GetHashCode(uniqueKey)
3 years ago
channelID := hashCode % ChannelNum
log.ZDebug(withAggregationCtx(ctx, v), "generate channelID", "hashCode", hashCode, "channelID", channelID, "uniqueKey", uniqueKey)
2 years ago
och.chArrays[channelID] <- Cmd2Value{Cmd: SourceMessages, Value: MsgChannelValue{uniqueKey: uniqueKey, ctxMsgList: v, ctx: ctx}}
3 years ago
}
}
}
}
}
}
func withAggregationCtx(ctx context.Context, values []*ContextMsg) context.Context {
var allMessageOperationID string
for _, v := range values {
if opid := mcontext.GetOperationID(v.ctx); opid != "" {
allMessageOperationID += "$" + opid
}
}
return mcontext.SetOperationID(ctx, allMessageOperationID)
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (och *OnlineHistoryRedisConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error {
return nil
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group
3 years ago
for {
if sess == nil {
2 years ago
log.ZWarn(context.Background(), "sess == nil, waiting", nil)
3 years ago
time.Sleep(100 * time.Millisecond)
} else {
break
}
3 years ago
}
3 years ago
rwLock := new(sync.RWMutex)
2 years ago
log.ZDebug(context.Background(), "online new session msg come", "highWaterMarkOffset",
claim.HighWaterMarkOffset(), "topic", claim.Topic(), "partition", claim.Partition())
3 years ago
cMsg := make([]*sarama.ConsumerMessage, 0, 1000)
2 years ago
t := time.NewTicker(time.Millisecond * 100)
3 years ago
go func() {
3 years ago
for {
select {
case <-t.C:
if len(cMsg) > 0 {
rwLock.Lock()
ccMsg := make([]*sarama.ConsumerMessage, 0, 1000)
for _, v := range cMsg {
ccMsg = append(ccMsg, v)
}
cMsg = make([]*sarama.ConsumerMessage, 0, 1000)
rwLock.Unlock()
split := 1000
ctx := mcontext.WithTriggerIDContext(context.Background(), utils.OperationIDGenerator())
2 years ago
log.ZDebug(ctx, "timer trigger msg consumer start", "length", len(ccMsg))
3 years ago
for i := 0; i < len(ccMsg)/split; i++ {
//log.Debug()
och.msgDistributionCh <- Cmd2Value{Cmd: ConsumerMsgs, Value: TriggerChannelValue{
2 years ago
ctx: ctx, cMsgList: ccMsg[i*split : (i+1)*split]}}
3 years ago
}
if (len(ccMsg) % split) > 0 {
och.msgDistributionCh <- Cmd2Value{Cmd: ConsumerMsgs, Value: TriggerChannelValue{
2 years ago
ctx: ctx, cMsgList: ccMsg[split*(len(ccMsg)/split):]}}
3 years ago
}
2 years ago
log.ZDebug(ctx, "timer trigger msg consumer end", "length", len(ccMsg))
3 years ago
}
3 years ago
}
}
3 years ago
}()
3 years ago
for msg := range claim.Messages() {
rwLock.Lock()
2 years ago
if len(msg.Value) != 0 {
cMsg = append(cMsg, msg)
}
3 years ago
rwLock.Unlock()
sess.MarkMessage(msg, "")
}
return nil
}