Files
open-im-server/internal/msgtransfer/online_history_msg_handler.go
T

254 lines
9.7 KiB
Go
Raw Normal View History

2023-02-09 20:36:34 +08:00
package msgtransfer
2021-05-26 19:24:25 +08:00
import (
2023-03-22 18:35:21 +08:00
"context"
2023-04-18 14:43:54 +08:00
"sync"
"time"
2023-03-16 10:46:06 +08:00
"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"
2023-03-21 12:28:21 +08:00
"github.com/OpenIMSDK/Open-IM-Server/pkg/common/mcontext"
2023-03-16 10:46:06 +08:00
pbMsg "github.com/OpenIMSDK/Open-IM-Server/pkg/proto/msg"
"github.com/OpenIMSDK/Open-IM-Server/pkg/utils"
2021-05-26 19:24:25 +08:00
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
)
2023-02-15 15:52:32 +08:00
const ConsumerMsgs = 3
const AggregationMessages = 4
const MongoMessages = 5
const ChannelNum = 100
2022-05-19 12:25:46 +08:00
type MsgChannelValue struct {
2022-05-28 18:10:08 +08:00
aggregationID string //maybe userID or super groupID
2023-03-22 18:35:21 +08:00
ctx context.Context
ctxMsgList []*ContextMsg
2022-05-28 18:10:08 +08:00
lastSeq uint64
2022-05-20 14:42:49 +08:00
}
2023-02-15 15:52:32 +08:00
2022-05-20 14:42:49 +08:00
type TriggerChannelValue struct {
2023-03-22 18:35:21 +08:00
ctx context.Context
cMsgList []*sarama.ConsumerMessage
2022-05-19 12:25:46 +08:00
}
2023-02-15 15:52:32 +08:00
2022-05-11 18:33:48 +08:00
type Cmd2Value struct {
2022-05-11 20:49:47 +08:00
Cmd int
2022-05-11 18:33:48 +08:00
Value interface{}
}
2023-03-22 18:35:21 +08:00
type ContextMsg struct {
message *pbMsg.MsgDataToMQ
ctx context.Context
}
2023-02-15 15:52:32 +08:00
2022-06-16 20:35:27 +08:00
type OnlineHistoryRedisConsumerHandler struct {
2023-02-15 15:52:32 +08:00
historyConsumerGroup *kafka.MConsumerGroup
2022-05-20 13:33:38 +08:00
chArrays [ChannelNum]chan Cmd2Value
2022-05-25 18:46:53 +08:00
msgDistributionCh chan Cmd2Value
2023-02-15 15:52:32 +08:00
singleMsgSuccessCount uint64
singleMsgFailedCount uint64
singleMsgSuccessCountMutex sync.Mutex
singleMsgFailedCountMutex sync.Mutex
2023-03-13 15:39:47 +08:00
//producerToPush *kafka.Producer
//producerToModify *kafka.Producer
//producerToMongo *kafka.Producer
2023-02-15 15:52:32 +08:00
2023-02-23 17:28:57 +08:00
msgDatabase controller.MsgDatabase
2021-05-26 19:24:25 +08:00
}
2023-03-03 17:42:26 +08:00
func NewOnlineHistoryRedisConsumerHandler(database controller.MsgDatabase) *OnlineHistoryRedisConsumerHandler {
var och OnlineHistoryRedisConsumerHandler
och.msgDatabase = database
2022-05-25 18:46:53 +08:00
och.msgDistributionCh = make(chan Cmd2Value) //no buffer channel
go och.MessagesDistributionHandle()
2022-05-20 15:51:37 +08:00
for i := 0; i < ChannelNum; i++ {
2022-05-25 22:42:44 +08:00
och.chArrays[i] = make(chan Cmd2Value, 50)
2022-05-20 15:51:37 +08:00
go och.Run(i)
}
2023-03-13 15:39:47 +08:00
//och.producerToPush = kafka.NewKafkaProducer(config.Config.Kafka.Ms2pschat.Addr, config.Config.Kafka.Ms2pschat.Topic)
//och.producerToModify = kafka.NewKafkaProducer(config.Config.Kafka.MsgToModify.Addr, config.Config.Kafka.MsgToModify.Topic)
//och.producerToMongo = kafka.NewKafkaProducer(config.Config.Kafka.MsgToMongo.Addr, config.Config.Kafka.MsgToMongo.Topic)
2023-02-15 15:52:32 +08:00
och.historyConsumerGroup = kafka.NewMConsumerGroup(&kafka.MConsumerGroupConfig{KafkaVersion: sarama.V2_0_0_0,
2021-05-26 19:24:25 +08:00
OffsetsInitial: sarama.OffsetNewest, IsReturnErr: false}, []string{config.Config.Kafka.Ws2mschat.Topic},
2022-06-16 20:35:27 +08:00
config.Config.Kafka.Ws2mschat.Addr, config.Config.Kafka.ConsumerGroupID.MsgToRedis)
2023-03-16 10:20:40 +08:00
//statistics.NewStatistics(&och.singleMsgSuccessCount, config.Config.ModuleName.MsgTransferName, fmt.Sprintf("%d second singleMsgCount insert to mongo", constant.StatisticsTimeInterval), constant.StatisticsTimeInterval)
2023-03-03 17:42:26 +08:00
return &och
2022-05-11 18:33:48 +08:00
}
2023-02-15 15:52:32 +08:00
2022-06-16 20:35:27 +08:00
func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
2022-05-19 12:25:46 +08:00
for {
select {
2022-05-20 13:33:38 +08:00
case cmd := <-och.chArrays[channelID]:
2022-05-19 12:25:46 +08:00
switch cmd.Cmd {
2022-05-28 18:10:08 +08:00
case AggregationMessages:
2022-05-19 12:25:46 +08:00
msgChannelValue := cmd.Value.(MsgChannelValue)
2023-03-22 18:35:21 +08:00
ctxMsgList := msgChannelValue.ctxMsgList
ctx := msgChannelValue.ctx
2022-05-20 16:07:32 +08:00
storageMsgList := make([]*pbMsg.MsgDataToMQ, 0, 80)
2023-03-22 18:35:21 +08:00
storagePushMsgList := make([]*ContextMsg, 0, 80)
notStoragePushMsgList := make([]*ContextMsg, 0, 80)
log.ZDebug(ctx, "msg arrived channel", "channel id", channelID, "msgList length", len(ctxMsgList), "aggregationID", msgChannelValue.aggregationID)
2022-12-12 19:22:50 +08:00
var modifyMsgList []*pbMsg.MsgDataToMQ
2023-03-22 18:35:21 +08:00
//ctx := mcontext.NewCtx("redis consumer")
//mcontext.SetOperationID(ctx, triggerID)
for _, v := range ctxMsgList {
2023-03-22 19:31:43 +08:00
log.ZDebug(ctx, "msg come to storage center", "message", v.message.String())
2023-03-22 18:35:21 +08:00
isHistory := utils.GetSwitchFromOptions(v.message.MsgData.Options, constant.IsHistory)
isSenderSync := utils.GetSwitchFromOptions(v.message.MsgData.Options, constant.IsSenderSync)
2022-05-20 13:33:38 +08:00
if isHistory {
2023-03-22 18:35:21 +08:00
storageMsgList = append(storageMsgList, v.message)
storagePushMsgList = append(storagePushMsgList, v)
2022-05-21 15:03:26 +08:00
} else {
2023-03-22 18:35:21 +08:00
if !(!isSenderSync && msgChannelValue.aggregationID == v.message.MsgData.SendID) {
2022-05-28 18:10:08 +08:00
notStoragePushMsgList = append(notStoragePushMsgList, v)
2022-05-21 15:03:26 +08:00
}
2022-05-20 13:33:38 +08:00
}
2023-03-22 18:35:21 +08:00
if v.message.MsgData.ContentType == constant.ReactionMessageModifier || v.message.MsgData.ContentType == constant.ReactionMessageDeleter {
modifyMsgList = append(modifyMsgList, v.message)
2022-12-12 19:22:50 +08:00
}
}
if len(modifyMsgList) > 0 {
2023-03-22 18:35:21 +08:00
och.msgDatabase.MsgToModifyMQ(ctx, msgChannelValue.aggregationID, "", modifyMsgList)
2022-05-20 13:33:38 +08:00
}
2023-03-22 19:31:43 +08:00
log.ZDebug(ctx, "msg storage length", "storageMsgList", len(storageMsgList), "push length", len(notStoragePushMsgList))
2022-07-25 12:53:49 +08:00
if len(storageMsgList) > 0 {
2023-02-23 17:28:57 +08:00
lastSeq, err := och.msgDatabase.BatchInsertChat2Cache(ctx, msgChannelValue.aggregationID, storageMsgList)
2022-07-25 12:53:49 +08:00
if err != nil {
2023-03-22 18:35:21 +08:00
log.ZError(ctx, "batch data insert to redis err", err, "storageMsgList", storageMsgList)
2023-02-15 15:52:32 +08:00
och.singleMsgFailedCountMutex.Lock()
och.singleMsgFailedCount += uint64(len(storageMsgList))
och.singleMsgFailedCountMutex.Unlock()
2022-07-25 12:53:49 +08:00
} else {
2023-02-15 15:52:32 +08:00
och.singleMsgSuccessCountMutex.Lock()
och.singleMsgSuccessCount += uint64(len(storageMsgList))
och.singleMsgSuccessCountMutex.Unlock()
2023-03-22 18:35:21 +08:00
och.msgDatabase.MsgToMongoMQ(ctx, msgChannelValue.aggregationID, "", storageMsgList, lastSeq)
for _, v := range storagePushMsgList {
och.msgDatabase.MsgToPushMQ(v.ctx, msgChannelValue.aggregationID, v.message)
}
2023-03-13 15:39:47 +08:00
for _, v := range notStoragePushMsgList {
2023-03-22 18:35:21 +08:00
och.msgDatabase.MsgToPushMQ(v.ctx, msgChannelValue.aggregationID, v.message)
}
2022-07-25 12:53:49 +08:00
}
2022-05-19 12:25:46 +08:00
} else {
2023-02-15 15:52:32 +08:00
for _, v := range notStoragePushMsgList {
2023-03-22 18:35:21 +08:00
p, o, err := och.msgDatabase.MsgToPushMQ(v.ctx, msgChannelValue.aggregationID, v.message)
if err != nil {
log.ZError(v.ctx, "kafka send failed", err, "msg", v.message.String(), "pid", p, "offset", o)
}
}
2022-05-19 12:25:46 +08:00
}
}
}
}
}
2022-06-16 20:35:27 +08:00
func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
2022-05-25 18:46:53 +08:00
for {
2023-03-22 18:35:21 +08:00
aggregationMsgs := make(map[string][]*ContextMsg, ChannelNum)
2022-05-25 18:46:53 +08:00
select {
case cmd := <-och.msgDistributionCh:
switch cmd.Cmd {
case ConsumerMsgs:
triggerChannelValue := cmd.Value.(TriggerChannelValue)
2023-03-22 18:35:21 +08:00
ctx := triggerChannelValue.ctx
2023-02-15 15:52:32 +08:00
consumerMessages := triggerChannelValue.cMsgList
2022-05-25 18:46:53 +08:00
//Aggregation map[userid]message list
2023-03-22 19:38:35 +08:00
log.ZDebug(ctx, "batch messages come to distribution center", "length", len(consumerMessages))
2022-05-25 18:46:53 +08:00
for i := 0; i < len(consumerMessages); i++ {
2023-03-22 18:35:21 +08:00
ctxMsg := &ContextMsg{}
2022-05-25 18:46:53 +08:00
msgFromMQ := pbMsg.MsgDataToMQ{}
err := proto.Unmarshal(consumerMessages[i].Value, &msgFromMQ)
if err != nil {
2023-03-22 18:35:21 +08:00
log.ZError(ctx, "msg_transfer Unmarshal msg err", err, string(consumerMessages[i].Value))
2022-05-25 18:46:53 +08:00
return
}
2023-03-22 18:35:21 +08:00
ctxMsg.ctx = kafka.GetContextWithMQHeader(consumerMessages[i].Headers)
ctxMsg.message = &msgFromMQ
log.ZDebug(ctx, "single msg come to distribution center", msgFromMQ.String(), string(consumerMessages[i].Key))
2022-05-28 18:10:08 +08:00
if oldM, ok := aggregationMsgs[string(consumerMessages[i].Key)]; ok {
2023-03-22 18:35:21 +08:00
oldM = append(oldM, ctxMsg)
2022-05-28 18:10:08 +08:00
aggregationMsgs[string(consumerMessages[i].Key)] = oldM
2022-05-25 18:46:53 +08:00
} else {
2023-03-22 18:35:21 +08:00
m := make([]*ContextMsg, 0, 100)
m = append(m, ctxMsg)
2022-05-28 18:10:08 +08:00
aggregationMsgs[string(consumerMessages[i].Key)] = m
2022-05-25 18:46:53 +08:00
}
}
2023-03-22 19:38:35 +08:00
log.ZDebug(ctx, "generate map list users len", "length", len(aggregationMsgs))
2022-05-28 18:10:08 +08:00
for aggregationID, v := range aggregationMsgs {
2022-05-25 18:46:53 +08:00
if len(v) >= 0 {
2023-02-15 15:52:32 +08:00
hashCode := utils.GetHashCode(aggregationID)
2022-05-25 18:46:53 +08:00
channelID := hashCode % ChannelNum
2023-03-22 18:35:21 +08:00
log.ZDebug(ctx, "generate channelID", "hashCode", hashCode, "channelID", channelID, "aggregationID", aggregationID)
och.chArrays[channelID] <- Cmd2Value{Cmd: AggregationMessages, Value: MsgChannelValue{aggregationID: aggregationID, ctxMsgList: v, ctx: ctx}}
2022-05-25 18:46:53 +08:00
}
}
}
}
2022-05-19 12:25:46 +08:00
}
2021-05-26 19:24:25 +08:00
}
2023-03-22 19:39:20 +08:00
func (och *OnlineHistoryRedisConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (och *OnlineHistoryRedisConsumerHandler) Cleanup(_ sarama.ConsumerGroupSession) error {
return nil
}
2022-05-20 13:33:38 +08:00
2023-02-15 15:52:32 +08:00
func (och *OnlineHistoryRedisConsumerHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error { // a instance in the consumer group
2022-05-22 21:08:57 +08:00
for {
if sess == nil {
2023-04-18 14:43:54 +08:00
log.ZWarn(context.Background(), "sess == nil, waiting", nil)
2022-05-22 21:08:57 +08:00
time.Sleep(100 * time.Millisecond)
} else {
break
}
2022-05-21 10:19:02 +08:00
}
2022-05-25 20:29:32 +08:00
rwLock := new(sync.RWMutex)
2023-03-22 18:47:29 +08:00
log.ZDebug(context.Background(), "online new session msg come", "highWaterMarkOffset",
claim.HighWaterMarkOffset(), "topic", claim.Topic(), "partition", claim.Partition())
2022-05-25 18:46:53 +08:00
cMsg := make([]*sarama.ConsumerMessage, 0, 1000)
t := time.NewTicker(time.Duration(100) * time.Millisecond)
2022-05-25 20:29:32 +08:00
go func() {
2022-05-25 21:15:17 +08:00
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
2023-03-22 18:35:21 +08:00
ctx := mcontext.WithTriggerIDContext(context.Background(), utils.OperationIDGenerator())
2023-03-22 19:38:35 +08:00
log.ZDebug(ctx, "timer trigger msg consumer start", "length", len(ccMsg))
2022-05-25 21:15:17 +08:00
for i := 0; i < len(ccMsg)/split; i++ {
//log.Debug()
och.msgDistributionCh <- Cmd2Value{Cmd: ConsumerMsgs, Value: TriggerChannelValue{
2023-03-22 18:35:21 +08:00
ctx: ctx, cMsgList: ccMsg[i*split : (i+1)*split]}}
2022-05-25 21:15:17 +08:00
}
if (len(ccMsg) % split) > 0 {
och.msgDistributionCh <- Cmd2Value{Cmd: ConsumerMsgs, Value: TriggerChannelValue{
2023-03-22 18:35:21 +08:00
ctx: ctx, cMsgList: ccMsg[split*(len(ccMsg)/split):]}}
2022-05-25 21:15:17 +08:00
}
2023-03-22 19:38:35 +08:00
log.ZDebug(ctx, "timer trigger msg consumer end", "length", len(ccMsg))
2022-05-25 21:03:48 +08:00
}
2022-05-25 18:46:53 +08:00
}
}
2022-05-25 20:29:32 +08:00
}()
2022-05-25 21:23:10 +08:00
for msg := range claim.Messages() {
rwLock.Lock()
2022-06-08 17:11:17 +08:00
if len(msg.Value) != 0 {
cMsg = append(cMsg, msg)
}
2022-05-25 21:23:10 +08:00
rwLock.Unlock()
sess.MarkMessage(msg, "")
}
2021-05-26 19:24:25 +08:00
return nil
}