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

272 lines
11 KiB

2 years ago
package msgtransfer
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
2 years ago
"Open_IM/pkg/common/db/cache"
"Open_IM/pkg/common/db/controller"
"Open_IM/pkg/common/kafka"
"Open_IM/pkg/common/log"
2 years ago
"Open_IM/pkg/common/tracelog"
2 years ago
pbMsg "Open_IM/pkg/proto/msg"
pbPush "Open_IM/pkg/proto/push"
2 years ago
"Open_IM/pkg/statistics"
"Open_IM/pkg/utils"
"context"
2 years ago
"fmt"
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
3 years ago
"sync"
3 years ago
"time"
)
2 years ago
const ConsumerMsgs = 3
const AggregationMessages = 4
const MongoMessages = 5
const ChannelNum = 100
type MsgChannelValue struct {
3 years ago
aggregationID string //maybe userID or super groupID
triggerID string
msgList []*pbMsg.MsgDataToMQ
lastSeq uint64
}
2 years ago
type TriggerChannelValue struct {
triggerID string
2 years ago
cMsgList []*sarama.ConsumerMessage
}
2 years ago
type Cmd2Value struct {
3 years ago
Cmd int
Value interface{}
}
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
producerToPush *kafka.Producer
producerToModify *kafka.Producer
producerToMongo *kafka.Producer
msgInterface controller.MsgInterface
cache cache.Cache
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) Init() {
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.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)
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)
3 years ago
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
func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
for {
select {
case cmd := <-och.chArrays[channelID]:
switch cmd.Cmd {
3 years ago
case AggregationMessages:
msgChannelValue := cmd.Value.(MsgChannelValue)
msgList := msgChannelValue.msgList
triggerID := msgChannelValue.triggerID
storageMsgList := make([]*pbMsg.MsgDataToMQ, 0, 80)
3 years ago
notStoragePushMsgList := make([]*pbMsg.MsgDataToMQ, 0, 80)
log.Debug(triggerID, "msg arrived channel", "channel id", channelID, msgList, msgChannelValue.aggregationID, len(msgList))
2 years ago
var modifyMsgList []*pbMsg.MsgDataToMQ
2 years ago
ctx := context.Background()
tracelog.SetOperationID(ctx, triggerID)
for _, v := range msgList {
log.Debug(triggerID, "msg come to storage center", v.String())
isHistory := utils.GetSwitchFromOptions(v.MsgData.Options, constant.IsHistory)
isSenderSync := utils.GetSwitchFromOptions(v.MsgData.Options, constant.IsSenderSync)
if isHistory {
storageMsgList = append(storageMsgList, v)
3 years ago
//log.NewWarn(triggerID, "storageMsgList to mongodb client msgID: ", v.MsgData.ClientMsgID)
3 years ago
} else {
3 years ago
if !(!isSenderSync && msgChannelValue.aggregationID == v.MsgData.SendID) {
notStoragePushMsgList = append(notStoragePushMsgList, v)
3 years ago
}
}
2 years ago
if v.MsgData.ContentType == constant.ReactionMessageModifier || v.MsgData.ContentType == constant.ReactionMessageDeleter {
modifyMsgList = append(modifyMsgList, v)
}
}
if len(modifyMsgList) > 0 {
2 years ago
och.sendMessageToModifyMQ(ctx, msgChannelValue.aggregationID, triggerID, modifyMsgList)
}
3 years ago
log.Debug(triggerID, "msg storage length", len(storageMsgList), "push length", len(notStoragePushMsgList))
if len(storageMsgList) > 0 {
2 years ago
lastSeq, err := och.msgInterface.BatchInsertChat2Cache(ctx, msgChannelValue.aggregationID, storageMsgList)
if err != nil {
2 years ago
och.singleMsgFailedCountMutex.Lock()
och.singleMsgFailedCount += uint64(len(storageMsgList))
och.singleMsgFailedCountMutex.Unlock()
log.NewError(triggerID, "single data insert to redis err", err.Error(), storageMsgList)
} else {
2 years ago
och.singleMsgSuccessCountMutex.Lock()
och.singleMsgSuccessCount += uint64(len(storageMsgList))
och.singleMsgSuccessCountMutex.Unlock()
och.SendMessageToMongoCH(ctx, msgChannelValue.aggregationID, triggerID, storageMsgList, lastSeq)
for _, v := range storageMsgList {
2 years ago
och.sendMessageToPushMQ(ctx, v, msgChannelValue.aggregationID)
}
for _, x := range notStoragePushMsgList {
2 years ago
och.sendMessageToPushMQ(ctx, x, msgChannelValue.aggregationID)
}
}
} else {
2 years ago
for _, v := range notStoragePushMsgList {
och.sendMessageToPushMQ(ctx, v, msgChannelValue.aggregationID)
}
}
}
}
}
}
func (och *OnlineHistoryRedisConsumerHandler) MessagesDistributionHandle() {
3 years ago
for {
3 years ago
aggregationMsgs := make(map[string][]*pbMsg.MsgDataToMQ, ChannelNum)
3 years ago
select {
case cmd := <-och.msgDistributionCh:
switch cmd.Cmd {
case ConsumerMsgs:
triggerChannelValue := cmd.Value.(TriggerChannelValue)
triggerID := triggerChannelValue.triggerID
2 years ago
consumerMessages := triggerChannelValue.cMsgList
3 years ago
//Aggregation map[userid]message list
log.Debug(triggerID, "batch messages come to distribution center", len(consumerMessages))
for i := 0; i < len(consumerMessages); i++ {
msgFromMQ := pbMsg.MsgDataToMQ{}
err := proto.Unmarshal(consumerMessages[i].Value, &msgFromMQ)
if err != nil {
log.Error(triggerID, "msg_transfer Unmarshal msg err", "msg", string(consumerMessages[i].Value), "err", err.Error())
return
}
log.Debug(triggerID, "single msg come to distribution center", msgFromMQ.String(), string(consumerMessages[i].Key))
3 years ago
if oldM, ok := aggregationMsgs[string(consumerMessages[i].Key)]; ok {
3 years ago
oldM = append(oldM, &msgFromMQ)
3 years ago
aggregationMsgs[string(consumerMessages[i].Key)] = oldM
3 years ago
} else {
m := make([]*pbMsg.MsgDataToMQ, 0, 100)
m = append(m, &msgFromMQ)
3 years ago
aggregationMsgs[string(consumerMessages[i].Key)] = m
3 years ago
}
}
3 years ago
log.Debug(triggerID, "generate map list users len", len(aggregationMsgs))
for aggregationID, v := range aggregationMsgs {
3 years ago
if len(v) >= 0 {
2 years ago
hashCode := utils.GetHashCode(aggregationID)
3 years ago
channelID := hashCode % ChannelNum
3 years ago
log.Debug(triggerID, "generate channelID", hashCode, channelID, aggregationID)
och.chArrays[channelID] <- Cmd2Value{Cmd: AggregationMessages, Value: MsgChannelValue{aggregationID: aggregationID, msgList: v, triggerID: triggerID}}
3 years ago
}
}
}
}
}
}
func (OnlineHistoryRedisConsumerHandler) Setup(_ sarama.ConsumerGroupSession) error { return nil }
func (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 {
log.NewWarn("", " sess == nil, waiting ")
time.Sleep(100 * time.Millisecond)
} else {
break
}
3 years ago
}
3 years ago
rwLock := new(sync.RWMutex)
3 years ago
log.NewDebug("", "online new session msg come", claim.HighWaterMarkOffset(), claim.Topic(), claim.Partition())
3 years ago
cMsg := make([]*sarama.ConsumerMessage, 0, 1000)
t := time.NewTicker(time.Duration(100) * time.Millisecond)
var triggerID string
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
triggerID = utils.OperationIDGenerator()
2 years ago
log.Debug(triggerID, "timer trigger msg consumer start", 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
triggerID: triggerID, 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
triggerID: triggerID, cMsgList: ccMsg[split*(len(ccMsg)/split):]}}
3 years ago
}
2 years ago
log.Debug(triggerID, "timer trigger msg consumer end", len(cMsg))
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
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) sendMessageToPushMQ(ctx context.Context, message *pbMsg.MsgDataToMQ, pushToUserID string) {
log.Info(message.OperationID, utils.GetSelfFuncName(), "msg ", message.String(), pushToUserID)
rpcPushMsg := pbPush.PushMsgReq{OperationID: message.OperationID, MsgData: message.MsgData, PushToUserID: pushToUserID}
mqPushMsg := pbMsg.PushMsgDataToMQ{OperationID: message.OperationID, MsgData: message.MsgData, PushToUserID: pushToUserID}
2 years ago
pid, offset, err := och.producerToPush.SendMessage(&mqPushMsg, mqPushMsg.PushToUserID, rpcPushMsg.OperationID)
if err != nil {
log.Error(mqPushMsg.OperationID, "kafka send failed", "send data", message.String(), "pid", pid, "offset", offset, "err", err.Error())
}
return
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) sendMessageToModifyMQ(ctx context.Context, aggregationID string, triggerID string, messages []*pbMsg.MsgDataToMQ) {
2 years ago
if len(messages) > 0 {
2 years ago
pid, offset, err := och.producerToModify.SendMessage(&pbMsg.MsgDataToModifyByMQ{AggregationID: aggregationID, MessageList: messages, TriggerID: triggerID}, aggregationID, triggerID)
2 years ago
if err != nil {
log.Error(triggerID, "kafka send failed", "send data", len(messages), "pid", pid, "offset", offset, "err", err.Error(), "key", aggregationID)
}
}
}
2 years ago
func (och *OnlineHistoryRedisConsumerHandler) SendMessageToMongoCH(ctx context.Context, aggregationID string, triggerID string, messages []*pbMsg.MsgDataToMQ, lastSeq int64) {
2 years ago
if len(messages) > 0 {
pid, offset, err := och.producerToMongo.SendMessage(&pbMsg.MsgDataToMongoByMQ{LastSeq: lastSeq, AggregationID: aggregationID, MessageList: messages, TriggerID: triggerID}, aggregationID, triggerID)
if err != nil {
log.Error(triggerID, "kafka send failed", "send data", len(messages), "pid", pid, "offset", offset, "err", err.Error(), "key", aggregationID)
}
}
}