Merge remote-tracking branch 'origin/errcode' into errcode

# Conflicts:
#	pkg/common/db/controller/storage.go
This commit is contained in:
withchao 2023-03-14 19:39:34 +08:00
commit 188dc6d322
40 changed files with 250 additions and 861 deletions

View File

@ -6,7 +6,6 @@ import (
"OpenIM/pkg/common/config" "OpenIM/pkg/common/config"
"OpenIM/pkg/common/log" "OpenIM/pkg/common/log"
"context" "context"
"errors"
"fmt" "fmt"
"github.com/OpenIMSDK/openKeeper" "github.com/OpenIMSDK/openKeeper"
"net" "net"
@ -42,9 +41,6 @@ func run(port int) error {
} }
fmt.Println("start api server, address: ", address, ", OpenIM version: ", config.Version) fmt.Println("start api server, address: ", address, ", OpenIM version: ", config.Version)
log.ZInfo(context.Background(), "start server success", "address", address, "version", config.Version) log.ZInfo(context.Background(), "start server success", "address", address, "version", config.Version)
log.ZDebug(context.Background(), "start server success", "address", address, "version", config.Version)
log.ZError(context.Background(), "start server success", errors.New("ss"), "address", address)
log.ZWarn(context.Background(), "start server success", errors.New("ss"), "address", address)
err = router.Run(address) err = router.Run(address)
if err != nil { if err != nil {
log.Error("", "api run failed ", address, err.Error()) log.Error("", "api run failed ", address, err.Error())

View File

@ -27,13 +27,13 @@ func Call[A, B, C any](
} }
cli, err := client() cli, err := client()
if err != nil { if err != nil {
log.ZError(c, "get rpc client conn failed", err)
apiresp.GinError(c, errs.ErrInternalServer.Wrap(err.Error())) // 获取RPC连接失败 apiresp.GinError(c, errs.ErrInternalServer.Wrap(err.Error())) // 获取RPC连接失败
log.Error("0", "get rpc client conn err:", err.Error())
return return
} }
data, err := rpc(cli, c, &req) data, err := rpc(cli, c, &req)
if err != nil { if err != nil {
log.Error("0", "rpc call err:", err.Error()) log.ZError(c, "rpc call failed", err)
apiresp.GinError(c, err) // RPC调用失败 apiresp.GinError(c, err) // RPC调用失败
return return
} }

View File

@ -4,11 +4,9 @@ import (
"OpenIM/internal/common/check" "OpenIM/internal/common/check"
"OpenIM/pkg/common/config" "OpenIM/pkg/common/config"
"OpenIM/pkg/common/constant" "OpenIM/pkg/common/constant"
"OpenIM/pkg/common/tracelog"
discoveryRegistry "OpenIM/pkg/discoveryregistry" discoveryRegistry "OpenIM/pkg/discoveryregistry"
"OpenIM/pkg/proto/msg" "OpenIM/pkg/proto/msg"
"OpenIM/pkg/proto/sdkws" "OpenIM/pkg/proto/sdkws"
utils2 "OpenIM/pkg/utils"
"context" "context"
utils "github.com/OpenIMSDK/open_utils" utils "github.com/OpenIMSDK/open_utils"
) )
@ -44,10 +42,6 @@ type NotificationMsg struct {
func (c *Check) Notification(ctx context.Context, notificationMsg *NotificationMsg) error { func (c *Check) Notification(ctx context.Context, notificationMsg *NotificationMsg) error {
var err error var err error
defer func() {
tracelog.SetCtxDebug(ctx, utils2.GetFuncName(1), err, "notificationMsg", notificationMsg)
}()
var req msg.SendMsgReq var req msg.SendMsgReq
var msg sdkws.MsgData var msg sdkws.MsgData
var offlineInfo sdkws.OfflinePushInfo var offlineInfo sdkws.OfflinePushInfo

View File

@ -53,12 +53,7 @@ func (c *Check) ExtendMessageDeleteNotification(ctx context.Context, sendID stri
c.messageReactionSender(ctx, sendID, sourceID, sessionType, constant.ReactionMessageDeleter, utils.StructToJsonString(m), isHistory, isReactionFromCache) c.messageReactionSender(ctx, sendID, sourceID, sessionType, constant.ReactionMessageDeleter, utils.StructToJsonString(m), isHistory, isReactionFromCache)
} }
func (c *Check) messageReactionSender(ctx context.Context, sendID string, sourceID string, sessionType, contentType int32, content string, isHistory bool, isReactionFromCache bool) { func (c *Check) messageReactionSender(ctx context.Context, sendID string, sourceID string, sessionType, contentType int32, content string, isHistory bool, isReactionFromCache bool) error {
var err error
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "sendID", sendID, "sourceID", sourceID, "sessionType", sessionType)
}()
options := make(map[string]bool, 5) options := make(map[string]bool, 5)
utils.SetSwitchFromOptions(options, constant.IsOfflinePush, false) utils.SetSwitchFromOptions(options, constant.IsOfflinePush, false)
utils.SetSwitchFromOptions(options, constant.IsConversationUpdate, false) utils.SetSwitchFromOptions(options, constant.IsConversationUpdate, false)
@ -87,5 +82,6 @@ func (c *Check) messageReactionSender(ctx context.Context, sendID string, source
case constant.GroupChatType, constant.SuperGroupChatType: case constant.GroupChatType, constant.SuperGroupChatType:
pbData.MsgData.GroupID = sourceID pbData.MsgData.GroupID = sourceID
} }
_, err = c.Msg.SendMsg(ctx, &pbData) _, err := c.Msg.SendMsg(ctx, &pbData)
return err
} }

View File

@ -88,7 +88,7 @@ func (och *OnlineHistoryRedisConsumerHandler) Run(channelID int) {
notStoragePushMsgList := make([]*pbMsg.MsgDataToMQ, 0, 80) notStoragePushMsgList := make([]*pbMsg.MsgDataToMQ, 0, 80)
log.Debug(triggerID, "msg arrived channel", "channel id", channelID, msgList, msgChannelValue.aggregationID, len(msgList)) log.Debug(triggerID, "msg arrived channel", "channel id", channelID, msgList, msgChannelValue.aggregationID, len(msgList))
var modifyMsgList []*pbMsg.MsgDataToMQ var modifyMsgList []*pbMsg.MsgDataToMQ
ctx := tracelog.NewCtx("redis consumer", triggerID) ctx := tracelog.NewCtx("redis consumer")
tracelog.SetOperationID(ctx, triggerID) tracelog.SetOperationID(ctx, triggerID)
for _, v := range msgList { for _, v := range msgList {
log.Debug(triggerID, "msg come to storage center", v.String()) log.Debug(triggerID, "msg come to storage center", v.String())

View File

@ -60,7 +60,7 @@ func (c *Controller) ApplyPut(ctx context.Context, args *FragmentPutArgs) (*PutA
Name: args.Name, Name: args.Name,
} }
// 直接拷贝一份 // 直接拷贝一份
err := c.i.CopyObjetInfo(ctx, &src, dst) err := c.i.CopyObjectInfo(ctx, &src, dst)
if err == nil { if err == nil {
info, err := c.i.GetObjectInfo(ctx, dst) info, err := c.i.GetObjectInfo(ctx, dst)
if err != nil { if err != nil {
@ -195,7 +195,7 @@ func (c *Controller) ConfirmPut(ctx context.Context, putID string) (*ObjectInfo,
log.Println("del key:", err) log.Println("del key:", err)
} }
for _, b := range src { for _, b := range src {
err = c.i.DeleteObjetInfo(ctx, &b) err = c.i.DeleteObjectInfo(ctx, &b)
if err != nil { if err != nil {
log.Println("del obj:", err) log.Println("del obj:", err)
} }

View File

@ -19,9 +19,6 @@ func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (
if !config.Config.Callback.CallbackBeforeCreateGroup.Enable { if !config.Config.Callback.CallbackBeforeCreateGroup.Enable {
return nil return nil
} }
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", req)
}()
cbReq := &callbackstruct.CallbackBeforeCreateGroupReq{ cbReq := &callbackstruct.CallbackBeforeCreateGroupReq{
CallbackCommand: constant.CallbackBeforeCreateGroupCommand, CallbackCommand: constant.CallbackBeforeCreateGroupCommand,
OperationID: tracelog.GetOperationID(ctx), OperationID: tracelog.GetOperationID(ctx),
@ -67,9 +64,6 @@ func CallbackBeforeMemberJoinGroup(ctx context.Context, groupMember *relation.Gr
if !config.Config.Callback.CallbackBeforeMemberJoinGroup.Enable { if !config.Config.Callback.CallbackBeforeMemberJoinGroup.Enable {
return nil return nil
} }
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "groupMember", *groupMember, "groupEx", groupEx)
}()
callbackReq := &callbackstruct.CallbackBeforeMemberJoinGroupReq{ callbackReq := &callbackstruct.CallbackBeforeMemberJoinGroupReq{
CallbackCommand: constant.CallbackBeforeMemberJoinGroupCommand, CallbackCommand: constant.CallbackBeforeMemberJoinGroupCommand,
OperationID: tracelog.GetOperationID(ctx), OperationID: tracelog.GetOperationID(ctx),
@ -97,9 +91,6 @@ func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *group.SetGroupMe
if !config.Config.Callback.CallbackBeforeSetGroupMemberInfo.Enable { if !config.Config.Callback.CallbackBeforeSetGroupMemberInfo.Enable {
return nil return nil
} }
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", *req)
}()
callbackReq := callbackstruct.CallbackBeforeSetGroupMemberInfoReq{ callbackReq := callbackstruct.CallbackBeforeSetGroupMemberInfoReq{
CallbackCommand: constant.CallbackBeforeSetGroupMemberInfoCommand, CallbackCommand: constant.CallbackBeforeSetGroupMemberInfoCommand,
OperationID: tracelog.GetOperationID(ctx), OperationID: tracelog.GetOperationID(ctx),

View File

@ -9,6 +9,7 @@ import (
"OpenIM/pkg/common/db/relation" "OpenIM/pkg/common/db/relation"
relationTb "OpenIM/pkg/common/db/table/relation" relationTb "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/db/unrelation" "OpenIM/pkg/common/db/unrelation"
"OpenIM/pkg/common/log"
"OpenIM/pkg/common/tokenverify" "OpenIM/pkg/common/tokenverify"
"OpenIM/pkg/common/tracelog" "OpenIM/pkg/common/tracelog"
"OpenIM/pkg/discoveryregistry" "OpenIM/pkg/discoveryregistry"
@ -727,7 +728,7 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
UserIDList: userIDs, UserIDList: userIDs,
} }
if err := s.ConversationChecker.ModifyConversationField(ctx, &args); err != nil { if err := s.ConversationChecker.ModifyConversationField(ctx, &args); err != nil {
tracelog.SetCtxWarn(ctx, "ModifyConversationField", err, args) log.ZWarn(ctx, "modifyConversationField failed", err, "args", args)
} }
} }
return resp, nil return resp, nil

View File

@ -59,7 +59,7 @@ func (c *MsgTool) getCronTaskOperationID() string {
func (c *MsgTool) AllUserClearMsgAndFixSeq() { func (c *MsgTool) AllUserClearMsgAndFixSeq() {
operationID := "AllUserAndGroupClearMsgAndFixSeq" operationID := "AllUserAndGroupClearMsgAndFixSeq"
ctx := tracelog.NewCtx(utils.GetSelfFuncName(), "") ctx := tracelog.NewCtx(utils.GetSelfFuncName())
log.NewInfo(operationID, "============================ start del cron task ============================") log.NewInfo(operationID, "============================ start del cron task ============================")
var err error var err error
userIDList, err := c.userDatabase.GetAllUserID(ctx) userIDList, err := c.userDatabase.GetAllUserID(ctx)

View File

@ -2,8 +2,6 @@ package cache
import ( import (
"OpenIM/pkg/common/db/relation" "OpenIM/pkg/common/db/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils"
"context" "context"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
"github.com/go-redis/redis/v8" "github.com/go-redis/redis/v8"
@ -47,8 +45,5 @@ func (b *BlackCacheRedis) GetBlackIDs(ctx context.Context, userID string) (black
} }
func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) (err error) { func (b *BlackCacheRedis) DelBlackIDs(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return b.rcClient.TagAsDeleted(b.getBlackIDsKey(userID)) return b.rcClient.TagAsDeleted(b.getBlackIDsKey(userID))
} }

View File

@ -3,7 +3,6 @@ package cache
import ( import (
"OpenIM/pkg/common/db/relation" "OpenIM/pkg/common/db/relation"
relationTb "OpenIM/pkg/common/db/table/relation" relationTb "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
@ -60,8 +59,7 @@ type ConversationRedis struct {
} }
func (c *ConversationRedis) GetUserConversationIDs(ctx context.Context, userID string, fn FuncDB) ([]string, error) { func (c *ConversationRedis) GetUserConversationIDs(ctx context.Context, userID string, fn FuncDB) ([]string, error) {
//TODO implement me return nil, nil
panic("implement me")
} }
func (c *ConversationRedis) GetConversation(ctx context.Context, ownerUserID, conversationID string, fn FuncDB) (*relationTb.ConversationModel, error) { func (c *ConversationRedis) GetConversation(ctx context.Context, ownerUserID, conversationID string, fn FuncDB) (*relationTb.ConversationModel, error) {
@ -200,9 +198,6 @@ func (c *ConversationRedis) GetUserConversationIDs1(ctx context.Context, ownerUs
//} //}
func (c *ConversationRedis) DelUserConversationIDs(ctx context.Context, ownerUserID string) (err error) { func (c *ConversationRedis) DelUserConversationIDs(ctx context.Context, ownerUserID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID)
}()
return utils.Wrap(c.rcClient.TagAsDeleted(c.getConversationIDsKey(ownerUserID)), "DelUserConversationIDs err") return utils.Wrap(c.rcClient.TagAsDeleted(c.getConversationIDsKey(ownerUserID)), "DelUserConversationIDs err")
} }
@ -213,9 +208,6 @@ func (c *ConversationRedis) DelUserConversationIDs(ctx context.Context, ownerUse
//} //}
func (c *ConversationRedis) DelConversation(ctx context.Context, ownerUserID, conversationID string) (err error) { func (c *ConversationRedis) DelConversation(ctx context.Context, ownerUserID, conversationID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "conversationID", conversationID)
}()
return utils.Wrap(c.rcClient.TagAsDeleted(c.getConversationKey(ownerUserID, conversationID)), "DelConversation err") return utils.Wrap(c.rcClient.TagAsDeleted(c.getConversationKey(ownerUserID, conversationID)), "DelConversation err")
} }

View File

@ -2,7 +2,6 @@ package cache
import ( import (
"OpenIM/pkg/common/db/table/unrelation" "OpenIM/pkg/common/db/table/unrelation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
@ -53,8 +52,5 @@ func (e *ExtendMsgSetCache) GetExtendMsg(ctx context.Context, sourceID string, s
} }
func (e *ExtendMsgSetCache) DelExtendMsg(ctx context.Context, clientMsgID string) (err error) { func (e *ExtendMsgSetCache) DelExtendMsg(ctx context.Context, clientMsgID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "clientMsgID", clientMsgID)
}()
return utils.Wrap(e.rcClient.TagAsDeleted(e.getKey(clientMsgID)), "DelExtendMsg err") return utils.Wrap(e.rcClient.TagAsDeleted(e.getKey(clientMsgID)), "DelExtendMsg err")
} }

View File

@ -3,7 +3,6 @@ package cache
import ( import (
"OpenIM/pkg/common/db/relation" "OpenIM/pkg/common/db/relation"
relationTb "OpenIM/pkg/common/db/table/relation" relationTb "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"encoding/json" "encoding/json"
@ -63,9 +62,6 @@ func (f *FriendCacheRedis) GetFriendIDs(ctx context.Context, ownerUserID string)
} }
func (f *FriendCacheRedis) DelFriendIDs(ctx context.Context, ownerUserID string) (err error) { func (f *FriendCacheRedis) DelFriendIDs(ctx context.Context, ownerUserID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID)
}()
return f.rcClient.TagAsDeleted(f.getFriendIDsKey(ownerUserID)) return f.rcClient.TagAsDeleted(f.getFriendIDsKey(ownerUserID))
} }
@ -87,9 +83,6 @@ func (f *FriendCacheRedis) GetTwoWayFriendIDs(ctx context.Context, ownerUserID s
} }
func (f *FriendCacheRedis) DelTwoWayFriendIDs(ctx context.Context, ownerUserID string) (err error) { func (f *FriendCacheRedis) DelTwoWayFriendIDs(ctx context.Context, ownerUserID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID)
}()
return f.rcClient.TagAsDeleted(f.getTwoWayFriendsIDsKey(ownerUserID)) return f.rcClient.TagAsDeleted(f.getTwoWayFriendsIDsKey(ownerUserID))
} }
@ -115,8 +108,5 @@ func (f *FriendCacheRedis) GetFriend(ctx context.Context, ownerUserID, friendUse
} }
func (f *FriendCacheRedis) DelFriend(ctx context.Context, ownerUserID, friendUserID string) (err error) { func (f *FriendCacheRedis) DelFriend(ctx context.Context, ownerUserID, friendUserID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserID", friendUserID)
}()
return f.rcClient.TagAsDeleted(f.getFriendKey(ownerUserID, friendUserID)) return f.rcClient.TagAsDeleted(f.getFriendKey(ownerUserID, friendUserID))
} }

View File

@ -3,7 +3,6 @@ package cache
import ( import (
relationTb "OpenIM/pkg/common/db/table/relation" relationTb "OpenIM/pkg/common/db/table/relation"
unrelation2 "OpenIM/pkg/common/db/table/unrelation" unrelation2 "OpenIM/pkg/common/db/table/unrelation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"github.com/dtm-labs/rockscache" "github.com/dtm-labs/rockscache"
@ -111,9 +110,6 @@ func (g *GroupCacheRedis) BatchDelJoinedSuperGroupIDs(ctx context.Context, userI
} }
func (g *GroupCacheRedis) DelJoinedSuperGroupIDs(ctx context.Context, userID string) (err error) { func (g *GroupCacheRedis) DelJoinedSuperGroupIDs(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return g.rcClient.TagAsDeleted(g.getJoinedSuperGroupsIDKey(userID)) return g.rcClient.TagAsDeleted(g.getJoinedSuperGroupsIDKey(userID))
} }
@ -163,9 +159,6 @@ func (g *GroupCacheRedis) GetGroupMemberHash1(ctx context.Context, groupIDs []st
} }
func (g *GroupCacheRedis) DelGroupMembersHash(ctx context.Context, groupID string) (err error) { func (g *GroupCacheRedis) DelGroupMembersHash(ctx context.Context, groupID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
}()
return g.rcClient.TagAsDeleted(g.getGroupMembersHashKey(groupID)) return g.rcClient.TagAsDeleted(g.getGroupMembersHashKey(groupID))
} }
@ -177,9 +170,6 @@ func (g *GroupCacheRedis) GetGroupMemberIDs(ctx context.Context, groupID string)
} }
func (g *GroupCacheRedis) DelGroupMemberIDs(ctx context.Context, groupID string) (err error) { func (g *GroupCacheRedis) DelGroupMemberIDs(ctx context.Context, groupID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
}()
return g.rcClient.TagAsDeleted(g.getGroupMemberIDsKey(groupID)) return g.rcClient.TagAsDeleted(g.getGroupMemberIDsKey(groupID))
} }
@ -208,9 +198,6 @@ func (g *GroupCacheRedis) DelGroupMemberIDs(ctx context.Context, groupID string)
//} //}
func (g *GroupCacheRedis) DelJoinedGroupID(ctx context.Context, userID string) (err error) { func (g *GroupCacheRedis) DelJoinedGroupID(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return g.rcClient.TagAsDeleted(g.getJoinedGroupsKey(userID)) return g.rcClient.TagAsDeleted(g.getJoinedGroupsKey(userID))
} }
@ -283,9 +270,6 @@ func (g *GroupCacheRedis) GetGroupMemberInfo(ctx context.Context, groupID, userI
//} //}
func (g *GroupCacheRedis) DelGroupMemberInfo(ctx context.Context, groupID, userID string) (err error) { func (g *GroupCacheRedis) DelGroupMemberInfo(ctx context.Context, groupID, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID)
}()
return g.rcClient.TagAsDeleted(g.getGroupMemberInfoKey(groupID, userID)) return g.rcClient.TagAsDeleted(g.getGroupMemberInfoKey(groupID, userID))
} }
@ -309,16 +293,10 @@ func (g *GroupCacheRedis) DelGroupMemberInfo(ctx context.Context, groupID, userI
//} //}
func (g *GroupCacheRedis) DelGroupMemberNum(ctx context.Context, groupID string) (err error) { func (g *GroupCacheRedis) DelGroupMemberNum(ctx context.Context, groupID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
}()
return g.rcClient.TagAsDeleted(g.getGroupMemberNumKey(groupID)) return g.rcClient.TagAsDeleted(g.getGroupMemberNumKey(groupID))
} }
func (g *GroupCacheRedis) DelGroupInfo(ctx context.Context, groupID string) (err error) { func (g *GroupCacheRedis) DelGroupInfo(ctx context.Context, groupID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
}()
return g.rcClient.TagAsDeleted(g.getGroupInfoKey(groupID)) return g.rcClient.TagAsDeleted(g.getGroupInfoKey(groupID))
} }

View File

@ -3,7 +3,6 @@ package cache
import ( import (
"OpenIM/pkg/common/db/relation" "OpenIM/pkg/common/db/relation"
relationTb "OpenIM/pkg/common/db/table/relation" relationTb "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"encoding/json" "encoding/json"
@ -58,9 +57,6 @@ func (u *UserCacheRedis) GetUserInfo(ctx context.Context, userID string) (userIn
} }
return string(bytes), nil return string(bytes), nil
} }
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "userInfo", *userInfo)
}()
userInfoStr, err := u.rcClient.Fetch(u.getUserInfoKey(userID), u.expireTime, getUserInfo) userInfoStr, err := u.rcClient.Fetch(u.getUserInfoKey(userID), u.expireTime, getUserInfo)
if err != nil { if err != nil {
return nil, err return nil, err
@ -83,9 +79,6 @@ func (u *UserCacheRedis) GetUsersInfo(ctx context.Context, userIDs []string) ([]
} }
func (u *UserCacheRedis) DelUserInfo(ctx context.Context, userID string) (err error) { func (u *UserCacheRedis) DelUserInfo(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return u.rcClient.TagAsDeleted(u.getUserInfoKey(userID)) return u.rcClient.TagAsDeleted(u.getUserInfoKey(userID))
} }
@ -106,9 +99,6 @@ func (u *UserCacheRedis) GetUserGlobalRecvMsgOpt(ctx context.Context, userID str
} }
return strconv.Itoa(int(userInfo.GlobalRecvMsgOpt)), nil return strconv.Itoa(int(userInfo.GlobalRecvMsgOpt)), nil
} }
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "opt", opt)
}()
optStr, err := u.rcClient.Fetch(u.getUserInfoKey(userID), u.expireTime, getUserGlobalRecvMsgOpt) optStr, err := u.rcClient.Fetch(u.getUserInfoKey(userID), u.expireTime, getUserGlobalRecvMsgOpt)
if err != nil { if err != nil {
return 0, err return 0, err
@ -117,8 +107,5 @@ func (u *UserCacheRedis) GetUserGlobalRecvMsgOpt(ctx context.Context, userID str
} }
func (u *UserCacheRedis) DelUserGlobalRecvMsgOpt(ctx context.Context, userID string) (err error) { func (u *UserCacheRedis) DelUserGlobalRecvMsgOpt(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return u.rcClient.TagAsDeleted(u.getUserGlobalRecvMsgOptKey(userID)) return u.rcClient.TagAsDeleted(u.getUserGlobalRecvMsgOptKey(userID))
} }

View File

@ -2,10 +2,11 @@ package controller
import "C" import "C"
import ( import (
"OpenIM/pkg/common/config"
"OpenIM/pkg/common/config" "OpenIM/pkg/common/config"
"OpenIM/pkg/common/db/obj" "OpenIM/pkg/common/db/obj"
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog" "OpenIM/pkg/common/log"
"OpenIM/pkg/errs" "OpenIM/pkg/errs"
"OpenIM/pkg/proto/third" "OpenIM/pkg/proto/third"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
@ -90,7 +91,7 @@ func (c *s3Database) urlName(name string) string {
//} //}
//config.Config.Credential.ObjectURL + name //config.Config.Credential.ObjectURL + name
//return "http://127.0.0.1:8080" + name //return "http://127.0.0.1:8080" + name
return config.Config.Credential.ObjectURL + name return config.Config.Object.ApiURL + name
} }
func (c *s3Database) UUID() string { func (c *s3Database) UUID() string {
@ -219,9 +220,9 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
defer func() { defer func() {
if _err == nil { if _err == nil {
// 清理上传的碎片 // 清理上传的碎片
err := c.obj.DeleteObjet(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: put.Path}) err := c.obj.DeleteObject(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: put.Path})
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DeleteObjet", err, "Bucket", c.obj.TempBucket(), "Path", put.Path) log.ZError(ctx, "deleteObject failed", err, "Bucket", c.obj.TempBucket(), "Path", put.Path)
} }
} }
}() }()
@ -246,12 +247,12 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
return nil, err return nil, err
} }
defer func() { defer func() {
err := c.obj.DeleteObjet(ctx, &obj.BucketObject{ err := c.obj.DeleteObject(ctx, &obj.BucketObject{
Bucket: c.obj.TempBucket(), Bucket: c.obj.TempBucket(),
Name: put.Path, Name: put.Path,
}) })
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DeleteObjet", err, "Bucket", c.obj.TempBucket(), "Path", put.Path) log.ZError(ctx, "DeleteObject", err, "Bucket", c.obj.TempBucket(), "Path", put.Path)
} }
}() }()
// 服务端已存在 // 服务端已存在
@ -302,7 +303,7 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
if put.Hash != o.Hash { if put.Hash != o.Hash {
return nil, fmt.Errorf("hash mismatching should %s reality %s", put.Hash, o.Hash) return nil, fmt.Errorf("hash mismatching should %s reality %s", put.Hash, o.Hash)
} }
if err := c.obj.CopyObjet(ctx, &src[0], dst); err != nil { if err := c.obj.CopyObject(ctx, &src[0], dst); err != nil {
return nil, err return nil, err
} }
} else { } else {
@ -311,8 +312,8 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
Name: path.Join(put.Path, "merge_"+c.UUID()), Name: path.Join(put.Path, "merge_"+c.UUID()),
} }
defer func() { // 清理合成的文件 defer func() { // 清理合成的文件
if err := c.obj.DeleteObjet(ctx, tempBucket); err != nil { if err := c.obj.DeleteObject(ctx, tempBucket); err != nil {
tracelog.SetCtxWarn(ctx, "DeleteObjet", err, "Bucket", tempBucket.Bucket, "Path", tempBucket.Name) log.ZError(ctx, "DeleteObject", err, "Bucket", tempBucket.Bucket, "Path", tempBucket.Name)
} }
}() }()
err := c.obj.ComposeObject(ctx, src, tempBucket) err := c.obj.ComposeObject(ctx, src, tempBucket)
@ -329,7 +330,7 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
if put.Hash != info.Hash { if put.Hash != info.Hash {
return nil, fmt.Errorf("hash mismatch should %s reality %s", put.Hash, info.Hash) return nil, fmt.Errorf("hash mismatch should %s reality %s", put.Hash, info.Hash)
} }
if err := c.obj.CopyObjet(ctx, tempBucket, dst); err != nil { if err := c.obj.CopyObject(ctx, tempBucket, dst); err != nil {
return nil, err return nil, err
} }
} }
@ -354,7 +355,7 @@ func (c *s3Database) ConfirmPut(ctx context.Context, req *third.ConfirmPutReq) (
return nil, err return nil, err
} }
if err := c.put.SetCompleted(ctx, put.PutID); err != nil { if err := c.put.SetCompleted(ctx, put.PutID); err != nil {
tracelog.SetCtxWarn(ctx, "SetCompleted", err, "PutID", put.PutID) log.ZError(ctx, "SetCompleted", err, "PutID", put.PutID)
} }
return &third.ConfirmPutResp{ return &third.ConfirmPutResp{
Url: c.urlName(o.Name), Url: c.urlName(o.Name),
@ -393,23 +394,23 @@ func (c *s3Database) cleanPutTemp(ctx context.Context, t time.Time, num int) {
for { for {
puts, err := c.put.FindExpirationPut(ctx, t, num) puts, err := c.put.FindExpirationPut(ctx, t, num)
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "FindExpirationPut", err, "Time", t, "Num", num) log.ZError(ctx, "FindExpirationPut", err, "Time", t, "Num", num)
return return
} }
if len(puts) == 0 { if len(puts) == 0 {
return return
} }
for _, put := range puts { for _, put := range puts {
err := c.obj.DeleteObjet(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: put.Path}) err := c.obj.DeleteObject(ctx, &obj.BucketObject{Bucket: c.obj.TempBucket(), Name: put.Path})
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DeleteObjet", err, "Bucket", c.obj.TempBucket(), "Path", put.Path) log.ZError(ctx, "DeleteObject", err, "Bucket", c.obj.TempBucket(), "Path", put.Path)
return return
} }
} }
ids := utils.Slice(puts, func(e *relation.ObjectPutModel) string { return e.PutID }) ids := utils.Slice(puts, func(e *relation.ObjectPutModel) string { return e.PutID })
err = c.put.DelPut(ctx, ids) err = c.put.DelPut(ctx, ids)
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DelPut", err, "PutID", ids) log.ZError(ctx, "DelPut", err, "PutID", ids)
return return
} }
} }
@ -418,7 +419,7 @@ func (c *s3Database) cleanPutTemp(ctx context.Context, t time.Time, num int) {
func (c *s3Database) cleanExpirationObject(ctx context.Context, t time.Time) { func (c *s3Database) cleanExpirationObject(ctx context.Context, t time.Time) {
err := c.info.DeleteExpiration(ctx, t) err := c.info.DeleteExpiration(ctx, t)
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DeleteExpiration", err, "Time", t) log.ZError(ctx, "DeleteExpiration", err, "Time", t)
} }
} }
@ -426,7 +427,7 @@ func (c *s3Database) clearNoCitation(ctx context.Context, engine string, limit i
for { for {
list, err := c.hash.DeleteNoCitation(ctx, engine, limit) list, err := c.hash.DeleteNoCitation(ctx, engine, limit)
if err != nil { if err != nil {
tracelog.SetCtxWarn(ctx, "DeleteNoCitation", err, "Engine", engine, "Limit", limit) log.ZError(ctx, "DeleteNoCitation", err, "Engine", engine, "Limit", limit)
return return
} }
if len(list) == 0 { if len(list) == 0 {
@ -434,10 +435,10 @@ func (c *s3Database) clearNoCitation(ctx context.Context, engine string, limit i
} }
var hasErr bool var hasErr bool
for _, h := range list { for _, h := range list {
err := c.obj.DeleteObjet(ctx, &obj.BucketObject{Bucket: h.Bucket, Name: h.Name}) err := c.obj.DeleteObject(ctx, &obj.BucketObject{Bucket: h.Bucket, Name: h.Name})
if err != nil { if err != nil {
hasErr = true hasErr = true
tracelog.SetCtxWarn(ctx, "DeleteObjet", err, "Bucket", h.Bucket, "Path", h.Name) log.ZError(ctx, "DeleteObject", err, "Bucket", h.Bucket, "Path", h.Name)
continue continue
} }
} }

View File

@ -54,7 +54,6 @@ func (u *userDatabase) InitOnce(ctx context.Context, users []*relation.UserModel
// 获取指定用户的信息 如有userID未找到 也返回错误 // 获取指定用户的信息 如有userID未找到 也返回错误
func (u *userDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relation.UserModel, err error) { func (u *userDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relation.UserModel, err error) {
users, err = u.userDB.Find(ctx, userIDs) users, err = u.userDB.Find(ctx, userIDs)
if err != nil { if err != nil {
return return

View File

@ -137,7 +137,7 @@ func (m *minioImpl) GetObjectInfo(ctx context.Context, args *BucketObject) (*Obj
}, nil }, nil
} }
func (m *minioImpl) CopyObjet(ctx context.Context, src *BucketObject, dst *BucketObject) error { func (m *minioImpl) CopyObject(ctx context.Context, src *BucketObject, dst *BucketObject) error {
_, err := m.client.CopyObject(ctx, minio.CopyDestOptions{ _, err := m.client.CopyObject(ctx, minio.CopyDestOptions{
Bucket: dst.Bucket, Bucket: dst.Bucket,
Object: dst.Name, Object: dst.Name,
@ -148,15 +148,15 @@ func (m *minioImpl) CopyObjet(ctx context.Context, src *BucketObject, dst *Bucke
return err return err
} }
func (m *minioImpl) DeleteObjet(ctx context.Context, info *BucketObject) error { func (m *minioImpl) DeleteObject(ctx context.Context, info *BucketObject) error {
return m.client.RemoveObject(ctx, info.Bucket, info.Name, minio.RemoveObjectOptions{}) return m.client.RemoveObject(ctx, info.Bucket, info.Name, minio.RemoveObjectOptions{})
} }
func (m *minioImpl) MoveObjetInfo(ctx context.Context, src *BucketObject, dst *BucketObject) error { func (m *minioImpl) MoveObjectInfo(ctx context.Context, src *BucketObject, dst *BucketObject) error {
if err := m.CopyObjet(ctx, src, dst); err != nil { if err := m.CopyObject(ctx, src, dst); err != nil {
return err return err
} }
return m.DeleteObjet(ctx, src) return m.DeleteObject(ctx, src)
} }
func (m *minioImpl) ComposeObject(ctx context.Context, src []BucketObject, dst *BucketObject) error { func (m *minioImpl) ComposeObject(ctx context.Context, src []BucketObject, dst *BucketObject) error {
@ -175,7 +175,7 @@ func (m *minioImpl) ComposeObject(ctx context.Context, src []BucketObject, dst *
if err != nil { if err != nil {
return err return err
} }
return m.MoveObjetInfo(ctx, &BucketObject{ return m.MoveObjectInfo(ctx, &BucketObject{
Bucket: destOptions.Bucket, Bucket: destOptions.Bucket,
Name: destOptions.Object, Name: destOptions.Object,
}, &BucketObject{ }, &BucketObject{

View File

@ -45,10 +45,10 @@ type Interface interface {
PresignedPutURL(ctx context.Context, args *ApplyPutArgs) (string, error) PresignedPutURL(ctx context.Context, args *ApplyPutArgs) (string, error)
// GetObjectInfo 获取对象信息 // GetObjectInfo 获取对象信息
GetObjectInfo(ctx context.Context, args *BucketObject) (*ObjectInfo, error) GetObjectInfo(ctx context.Context, args *BucketObject) (*ObjectInfo, error)
// CopyObjet 复制对象 // CopyObject 复制对象
CopyObjet(ctx context.Context, src *BucketObject, dst *BucketObject) error CopyObject(ctx context.Context, src *BucketObject, dst *BucketObject) error
// DeleteObjet 删除对象(不存在返回nil) // DeleteObject 删除对象(不存在返回nil)
DeleteObjet(ctx context.Context, info *BucketObject) error DeleteObject(ctx context.Context, info *BucketObject) error
// ComposeObject 合并对象 // ComposeObject 合并对象
ComposeObject(ctx context.Context, src []BucketObject, dst *BucketObject) error ComposeObject(ctx context.Context, src []BucketObject, dst *BucketObject) error
// IsNotFound 判断是不是不存在导致的错误 // IsNotFound 判断是不是不存在导致的错误

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -17,37 +16,22 @@ func NewBlackGorm(db *gorm.DB) relation.BlackModelInterface {
} }
func (b *BlackGorm) Create(ctx context.Context, blacks []*relation.BlackModel) (err error) { func (b *BlackGorm) Create(ctx context.Context, blacks []*relation.BlackModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "blacks", blacks)
}()
return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Create(&blacks).Error, "") return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Create(&blacks).Error, "")
} }
func (b *BlackGorm) Delete(ctx context.Context, blacks []*relation.BlackModel) (err error) { func (b *BlackGorm) Delete(ctx context.Context, blacks []*relation.BlackModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "blacks", blacks)
}()
return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Delete(blacks).Error, "") return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Delete(blacks).Error, "")
} }
func (b *BlackGorm) UpdateByMap(ctx context.Context, ownerUserID, blockUserID string, args map[string]interface{}) (err error) { func (b *BlackGorm) UpdateByMap(ctx context.Context, ownerUserID, blockUserID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "blockUserID", blockUserID, "args", args)
}()
return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("block_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Updates(args).Error, "") return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("block_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Updates(args).Error, "")
} }
func (b *BlackGorm) Update(ctx context.Context, blacks []*relation.BlackModel) (err error) { func (b *BlackGorm) Update(ctx context.Context, blacks []*relation.BlackModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "blacks", blacks)
}()
return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Updates(&blacks).Error, "") return utils.Wrap(b.DB.Model(&relation.BlackModel{}).Updates(&blacks).Error, "")
} }
func (b *BlackGorm) Find(ctx context.Context, blacks []*relation.BlackModel) (blackList []*relation.BlackModel, err error) { func (b *BlackGorm) Find(ctx context.Context, blacks []*relation.BlackModel) (blackList []*relation.BlackModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "blacks", blacks, "blackList", blackList)
}()
var where [][]interface{} var where [][]interface{}
for _, black := range blacks { for _, black := range blacks {
where = append(where, []interface{}{black.OwnerUserID, black.BlockUserID}) where = append(where, []interface{}{black.OwnerUserID, black.BlockUserID})
@ -57,16 +41,10 @@ func (b *BlackGorm) Find(ctx context.Context, blacks []*relation.BlackModel) (bl
func (b *BlackGorm) Take(ctx context.Context, ownerUserID, blockUserID string) (black *relation.BlackModel, err error) { func (b *BlackGorm) Take(ctx context.Context, ownerUserID, blockUserID string) (black *relation.BlackModel, err error) {
black = &relation.BlackModel{} black = &relation.BlackModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "blockUserID", blockUserID, "black", *black)
}()
return black, utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("owner_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Take(black).Error, "") return black, utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("owner_user_id = ? and block_user_id = ?", ownerUserID, blockUserID).Take(black).Error, "")
} }
func (b *BlackGorm) FindOwnerBlacks(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (blacks []*relation.BlackModel, total int64, err error) { func (b *BlackGorm) FindOwnerBlacks(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (blacks []*relation.BlackModel, total int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "blacks", blacks)
}()
err = b.DB.Model(&relation.BlackModel{}).Model(b).Count(&total).Error err = b.DB.Model(&relation.BlackModel{}).Model(b).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
@ -76,8 +54,5 @@ func (b *BlackGorm) FindOwnerBlacks(ctx context.Context, ownerUserID string, pag
} }
func (b *BlackGorm) FindBlackUserIDs(ctx context.Context, ownerUserID string) (blackUserIDs []string, err error) { func (b *BlackGorm) FindBlackUserIDs(ctx context.Context, ownerUserID string) (blackUserIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "blackUserIDs", blackUserIDs)
}()
return blackUserIDs, utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("owner_user_id = ?", blackUserIDs).Pluck("block_user_id", &blackUserIDs).Error, "") return blackUserIDs, utils.Wrap(b.DB.Model(&relation.BlackModel{}).Where("owner_user_id = ?", blackUserIDs).Pluck("block_user_id", &blackUserIDs).Error, "")
} }

View File

@ -3,7 +3,6 @@ package relation
import ( import (
"OpenIM/pkg/common/constant" "OpenIM/pkg/common/constant"
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -35,70 +34,43 @@ func (c *ConversationGorm) NewTx(tx any) Conversation {
} }
func (c *ConversationGorm) Create(ctx context.Context, conversations []*relation.ConversationModel) (err error) { func (c *ConversationGorm) Create(ctx context.Context, conversations []*relation.ConversationModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "conversations", conversations)
}()
return utils.Wrap(c.DB.Create(&conversations).Error, "") return utils.Wrap(c.DB.Create(&conversations).Error, "")
} }
func (c *ConversationGorm) Delete(ctx context.Context, groupIDs []string) (err error) { func (c *ConversationGorm) Delete(ctx context.Context, groupIDs []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs)
}()
return utils.Wrap(c.DB.Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "") return utils.Wrap(c.DB.Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "")
} }
func (c *ConversationGorm) UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}) (err error) { func (c *ConversationGorm) UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userIDList", userIDList, "conversationID", conversationID)
}()
return utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args).Error, "") return utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args).Error, "")
} }
func (c *ConversationGorm) Update(ctx context.Context, conversations []*relation.ConversationModel) (err error) { func (c *ConversationGorm) Update(ctx context.Context, conversations []*relation.ConversationModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "conversations", conversations)
}()
return utils.Wrap(c.DB.Updates(&conversations).Error, "") return utils.Wrap(c.DB.Updates(&conversations).Error, "")
} }
func (c *ConversationGorm) Find(ctx context.Context, ownerUserID string, conversationIDs []string) (conversations []*relation.ConversationModel, err error) { func (c *ConversationGorm) Find(ctx context.Context, ownerUserID string, conversationIDs []string) (conversations []*relation.ConversationModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "groups", conversations)
}()
err = utils.Wrap(c.DB.Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).Find(&conversations).Error, "") err = utils.Wrap(c.DB.Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).Find(&conversations).Error, "")
return conversations, err return conversations, err
} }
func (c *ConversationGorm) Take(ctx context.Context, userID, conversationID string) (conversation *relation.ConversationModel, err error) { func (c *ConversationGorm) Take(ctx context.Context, userID, conversationID string) (conversation *relation.ConversationModel, err error) {
cc := &relation.ConversationModel{} cc := &relation.ConversationModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "conversation", *conversation)
}()
return cc, utils.Wrap(c.DB.Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error, "") return cc, utils.Wrap(c.DB.Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error, "")
} }
func (c *ConversationGorm) FindUserID(ctx context.Context, userIDList []string, conversationID string) (existUserID []string, err error) { func (c *ConversationGorm) FindUserID(ctx context.Context, userIDList []string, conversationID string) (existUserID []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userIDList, "existUserID", existUserID)
}()
return existUserID, utils.Wrap(c.DB.Where(" owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Pluck("owner_user_id", &existUserID).Error, "") return existUserID, utils.Wrap(c.DB.Where(" owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Pluck("owner_user_id", &existUserID).Error, "")
} }
func (c *ConversationGorm) FindConversationID(ctx context.Context, userID string, conversationIDList []string) (existConversationID []string, err error) { func (c *ConversationGorm) FindConversationID(ctx context.Context, userID string, conversationIDList []string) (existConversationID []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "existConversationIDList", existConversationID)
}()
return existConversationID, utils.Wrap(c.DB.Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).Pluck("conversation_id", &existConversationID).Error, "") return existConversationID, utils.Wrap(c.DB.Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).Pluck("conversation_id", &existConversationID).Error, "")
} }
func (c *ConversationGorm) FindUserIDAllConversationID(ctx context.Context, userID string) (conversationIDList []string, err error) { func (c *ConversationGorm) FindUserIDAllConversationID(ctx context.Context, userID string) (conversationIDList []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "conversationIDList", conversationIDList)
}()
return conversationIDList, utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error, "") return conversationIDList, utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error, "")
} }
func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) { func (c *ConversationGorm) FindRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string) (userIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userIDs", userIDs)
}()
return userIDs, utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).Pluck("user_id", &userIDs).Error, "") return userIDs, utils.Wrap(c.DB.Model(&relation.ConversationModel{}).Where("group_id = ? and recv_msg_opt = ?", groupID, constant.ReceiveNotNotifyMessage).Pluck("user_id", &userIDs).Error, "")
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -22,42 +21,27 @@ func (f *FriendGorm) NewTx(tx any) relation.FriendModelInterface {
// 插入多条记录 // 插入多条记录
func (f *FriendGorm) Create(ctx context.Context, friends []*relation.FriendModel) (err error) { func (f *FriendGorm) Create(ctx context.Context, friends []*relation.FriendModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friends", friends)
}()
return utils.Wrap(f.DB.Create(&friends).Error, "") return utils.Wrap(f.DB.Create(&friends).Error, "")
} }
// 删除ownerUserID指定的好友 // 删除ownerUserID指定的好友
func (f *FriendGorm) Delete(ctx context.Context, ownerUserID string, friendUserIDs []string) (err error) { func (f *FriendGorm) Delete(ctx context.Context, ownerUserID string, friendUserIDs []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserIDs", friendUserIDs)
}()
err = utils.Wrap(f.DB.Where("owner_user_id = ? AND friend_user_id in ( ?)", ownerUserID, friendUserIDs).Delete(&relation.FriendModel{}).Error, "") err = utils.Wrap(f.DB.Where("owner_user_id = ? AND friend_user_id in ( ?)", ownerUserID, friendUserIDs).Delete(&relation.FriendModel{}).Error, "")
return err return err
} }
// 更新ownerUserID单个好友信息 更新零值 // 更新ownerUserID单个好友信息 更新零值
func (f *FriendGorm) UpdateByMap(ctx context.Context, ownerUserID string, friendUserID string, args map[string]interface{}) (err error) { func (f *FriendGorm) UpdateByMap(ctx context.Context, ownerUserID string, friendUserID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserID", friendUserID, "args", args)
}()
return utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? AND friend_user_id = ? ", ownerUserID, friendUserID).Updates(args).Error, "") return utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? AND friend_user_id = ? ", ownerUserID, friendUserID).Updates(args).Error, "")
} }
// 更新好友信息的非零值 // 更新好友信息的非零值
func (f *FriendGorm) Update(ctx context.Context, friends []*relation.FriendModel) (err error) { func (f *FriendGorm) Update(ctx context.Context, friends []*relation.FriendModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friends", friends)
}()
return utils.Wrap(f.DB.Updates(&friends).Error, "") return utils.Wrap(f.DB.Updates(&friends).Error, "")
} }
// 更新好友备注(也支持零值 // 更新好友备注(也支持零值
func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error) { func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID, remark string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserID", friendUserID, "remark", remark)
}()
if remark != "" { if remark != "" {
return utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? and friend_user_id = ?", ownerUserID, friendUserID).Update("remark", remark).Error, "") return utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? and friend_user_id = ?", ownerUserID, friendUserID).Update("remark", remark).Error, "")
} }
@ -70,39 +54,26 @@ func (f *FriendGorm) UpdateRemark(ctx context.Context, ownerUserID, friendUserID
// 获取单个好友信息,如没找到 返回错误 // 获取单个好友信息,如没找到 返回错误
func (f *FriendGorm) Take(ctx context.Context, ownerUserID, friendUserID string) (friend *relation.FriendModel, err error) { func (f *FriendGorm) Take(ctx context.Context, ownerUserID, friendUserID string) (friend *relation.FriendModel, err error) {
friend = &relation.FriendModel{} friend = &relation.FriendModel{}
defer tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserID", friendUserID, "friend", *friend)
return friend, utils.Wrap(f.DB.Where("owner_user_id = ? and friend_user_id", ownerUserID, friendUserID).Take(friend).Error, "") return friend, utils.Wrap(f.DB.Where("owner_user_id = ? and friend_user_id", ownerUserID, friendUserID).Take(friend).Error, "")
} }
// 查找好友关系,如果是双向关系,则都返回 // 查找好友关系,如果是双向关系,则都返回
func (f *FriendGorm) FindUserState(ctx context.Context, userID1, userID2 string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindUserState(ctx context.Context, userID1, userID2 string) (friends []*relation.FriendModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID1", userID1, "userID2", userID2, "friends", friends)
}()
return friends, utils.Wrap(f.DB.Where("(owner_user_id = ? and friend_user_id = ?) or (owner_user_id = ? and friend_user_id = ?)", userID1, userID2, userID2, userID1).Find(&friends).Error, "") return friends, utils.Wrap(f.DB.Where("(owner_user_id = ? and friend_user_id = ?) or (owner_user_id = ? and friend_user_id = ?)", userID1, userID2, userID2, userID1).Find(&friends).Error, "")
} }
// 获取 owner指定的好友列表 如果有friendUserIDs不存在也不返回错误 // 获取 owner指定的好友列表 如果有friendUserIDs不存在也不返回错误
func (f *FriendGorm) FindFriends(ctx context.Context, ownerUserID string, friendUserIDs []string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindFriends(ctx context.Context, ownerUserID string, friendUserIDs []string) (friends []*relation.FriendModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserIDs", friendUserIDs, "friends", friends)
}()
return friends, utils.Wrap(f.DB.Where("owner_user_id = ? AND friend_user_id in (?)", ownerUserID, friendUserIDs).Find(&friends).Error, "") return friends, utils.Wrap(f.DB.Where("owner_user_id = ? AND friend_user_id in (?)", ownerUserID, friendUserIDs).Find(&friends).Error, "")
} }
// 获取哪些人添加了friendUserID 如果有ownerUserIDs不存在也不返回错误 // 获取哪些人添加了friendUserID 如果有ownerUserIDs不存在也不返回错误
func (f *FriendGorm) FindReversalFriends(ctx context.Context, friendUserID string, ownerUserIDs []string) (friends []*relation.FriendModel, err error) { func (f *FriendGorm) FindReversalFriends(ctx context.Context, friendUserID string, ownerUserIDs []string) (friends []*relation.FriendModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friendUserID", friendUserID, "ownerUserIDs", ownerUserIDs, "friends", friends)
}()
return friends, utils.Wrap(f.DB.Where("friend_user_id = ? AND owner_user_id in (?)", friendUserID, ownerUserIDs).Find(&friends).Error, "") return friends, utils.Wrap(f.DB.Where("friend_user_id = ? AND owner_user_id in (?)", friendUserID, ownerUserIDs).Find(&friends).Error, "")
} }
// 获取ownerUserID好友列表 支持翻页 // 获取ownerUserID好友列表 支持翻页
func (f *FriendGorm) FindOwnerFriends(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *FriendGorm) FindOwnerFriends(ctx context.Context, ownerUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "pageNumber", pageNumber, "showNumber", showNumber, "friends", friends, "total", total)
}()
err = f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Count(&total).Error err = f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
@ -113,9 +84,6 @@ func (f *FriendGorm) FindOwnerFriends(ctx context.Context, ownerUserID string, p
// 获取哪些人添加了friendUserID 支持翻页 // 获取哪些人添加了friendUserID 支持翻页
func (f *FriendGorm) FindInWhoseFriends(ctx context.Context, friendUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) { func (f *FriendGorm) FindInWhoseFriends(ctx context.Context, friendUserID string, pageNumber, showNumber int32) (friends []*relation.FriendModel, total int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friendUserID", friendUserID, "pageNumber", pageNumber, "showNumber", showNumber, "friends", friends, "total", total)
}()
err = f.DB.Model(&relation.FriendModel{}).Where("friend_user_id = ? ", friendUserID).Count(&total).Error err = f.DB.Model(&relation.FriendModel{}).Where("friend_user_id = ? ", friendUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
@ -125,8 +93,5 @@ func (f *FriendGorm) FindInWhoseFriends(ctx context.Context, friendUserID string
} }
func (f *FriendGorm) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) { func (f *FriendGorm) FindFriendUserIDs(ctx context.Context, ownerUserID string) (friendUserIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "friendUserIDs", friendUserIDs)
}()
return friendUserIDs, utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Pluck("friend_user_id", &friendUserIDs).Error, "") return friendUserIDs, utils.Wrap(f.DB.Model(&relation.FriendModel{}).Where("owner_user_id = ? ", ownerUserID).Pluck("friend_user_id", &friendUserIDs).Error, "")
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -22,61 +21,39 @@ func (f *FriendRequestGorm) NewTx(tx any) relation.FriendRequestModelInterface {
// 插入多条记录 // 插入多条记录
func (f *FriendRequestGorm) Create(ctx context.Context, friendRequests []*relation.FriendRequestModel) (err error) { func (f *FriendRequestGorm) Create(ctx context.Context, friendRequests []*relation.FriendRequestModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friendRequests", friendRequests)
}()
return utils.Wrap(f.DB.Create(&friendRequests).Error, "") return utils.Wrap(f.DB.Create(&friendRequests).Error, "")
} }
// 删除记录 // 删除记录
func (f *FriendRequestGorm) Delete(ctx context.Context, fromUserID, toUserID string) (err error) { func (f *FriendRequestGorm) Delete(ctx context.Context, fromUserID, toUserID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "fromUserID", fromUserID, "toUserID", toUserID)
}()
return utils.Wrap(f.DB.Where("from_user_id = ? AND to_user_id = ?", fromUserID, toUserID).Delete(&relation.FriendRequestModel{}).Error, "") return utils.Wrap(f.DB.Where("from_user_id = ? AND to_user_id = ?", fromUserID, toUserID).Delete(&relation.FriendRequestModel{}).Error, "")
} }
// 更新零值 // 更新零值
func (f *FriendRequestGorm) UpdateByMap(ctx context.Context, formUserID string, toUserID string, args map[string]interface{}) (err error) { func (f *FriendRequestGorm) UpdateByMap(ctx context.Context, formUserID string, toUserID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "formUserID", formUserID, "toUserID", toUserID, "args", args)
}()
return utils.Wrap(f.DB.Model(&relation.FriendRequestModel{}).Where("from_user_id = ? AND to_user_id ", formUserID, toUserID).Updates(args).Error, "") return utils.Wrap(f.DB.Model(&relation.FriendRequestModel{}).Where("from_user_id = ? AND to_user_id ", formUserID, toUserID).Updates(args).Error, "")
} }
// 更新多条记录 (非零值) // 更新多条记录 (非零值)
func (f *FriendRequestGorm) Update(ctx context.Context, friendRequests []*relation.FriendRequestModel) (err error) { func (f *FriendRequestGorm) Update(ctx context.Context, friendRequests []*relation.FriendRequestModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "friendRequests", friendRequests)
}()
return utils.Wrap(f.DB.Updates(&friendRequests).Error, "") return utils.Wrap(f.DB.Updates(&friendRequests).Error, "")
} }
// 获取来指定用户的好友申请 未找到 不返回错误 // 获取来指定用户的好友申请 未找到 不返回错误
func (f *FriendRequestGorm) Find(ctx context.Context, fromUserID, toUserID string) (friendRequest *relation.FriendRequestModel, err error) { func (f *FriendRequestGorm) Find(ctx context.Context, fromUserID, toUserID string) (friendRequest *relation.FriendRequestModel, err error) {
friendRequest = &relation.FriendRequestModel{} friendRequest = &relation.FriendRequestModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "fromUserID", fromUserID, "toUserID", toUserID, "friendRequest", *friendRequest)
}()
utils.Wrap(f.DB.Where("from_user_id = ? and to_user_id", fromUserID, toUserID).Find(friendRequest).Error, "") utils.Wrap(f.DB.Where("from_user_id = ? and to_user_id", fromUserID, toUserID).Find(friendRequest).Error, "")
return return
} }
func (f *FriendRequestGorm) Take(ctx context.Context, fromUserID, toUserID string) (friendRequest *relation.FriendRequestModel, err error) { func (f *FriendRequestGorm) Take(ctx context.Context, fromUserID, toUserID string) (friendRequest *relation.FriendRequestModel, err error) {
friendRequest = &relation.FriendRequestModel{} friendRequest = &relation.FriendRequestModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "fromUserID", fromUserID, "toUserID", toUserID, "friendRequest", *friendRequest)
}()
utils.Wrap(f.DB.Where("from_user_id = ? and to_user_id", fromUserID, toUserID).Take(friendRequest).Error, "") utils.Wrap(f.DB.Where("from_user_id = ? and to_user_id", fromUserID, toUserID).Take(friendRequest).Error, "")
return return
} }
// 获取toUserID收到的好友申请列表 // 获取toUserID收到的好友申请列表
func (f *FriendRequestGorm) FindToUserID(ctx context.Context, toUserID string, pageNumber, showNumber int32) (friendRequests []*relation.FriendRequestModel, total int64, err error) { func (f *FriendRequestGorm) FindToUserID(ctx context.Context, toUserID string, pageNumber, showNumber int32) (friendRequests []*relation.FriendRequestModel, total int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "toUserID", toUserID, "friendRequests", friendRequests)
}()
err = f.DB.Model(&relation.FriendRequestModel{}).Where("to_user_id = ? ", toUserID).Count(&total).Error err = f.DB.Model(&relation.FriendRequestModel{}).Where("to_user_id = ? ", toUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")
@ -87,9 +64,6 @@ func (f *FriendRequestGorm) FindToUserID(ctx context.Context, toUserID string, p
// 获取fromUserID发出去的好友申请列表 // 获取fromUserID发出去的好友申请列表
func (f *FriendRequestGorm) FindFromUserID(ctx context.Context, fromUserID string, pageNumber, showNumber int32) (friendRequests []*relation.FriendRequestModel, total int64, err error) { func (f *FriendRequestGorm) FindFromUserID(ctx context.Context, fromUserID string, pageNumber, showNumber int32) (friendRequests []*relation.FriendRequestModel, total int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "fromUserID", fromUserID, "friendRequests", friendRequests)
}()
err = f.DB.Model(&relation.FriendRequestModel{}).Where("from_user_id = ? ", fromUserID).Count(&total).Error err = f.DB.Model(&relation.FriendRequestModel{}).Where("from_user_id = ? ", fromUserID).Count(&total).Error
if err != nil { if err != nil {
return nil, 0, utils.Wrap(err, "") return nil, 0, utils.Wrap(err, "")

View File

@ -3,7 +3,6 @@ package relation
import ( import (
"OpenIM/pkg/common/constant" "OpenIM/pkg/common/constant"
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -24,37 +23,22 @@ func (g *GroupMemberGorm) NewTx(tx any) relation.GroupMemberModelInterface {
} }
func (g *GroupMemberGorm) Create(ctx context.Context, groupMemberList []*relation.GroupMemberModel) (err error) { func (g *GroupMemberGorm) Create(ctx context.Context, groupMemberList []*relation.GroupMemberModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupMemberList", groupMemberList)
}()
return utils.Wrap(g.DB.Create(&groupMemberList).Error, "") return utils.Wrap(g.DB.Create(&groupMemberList).Error, "")
} }
func (g *GroupMemberGorm) Delete(ctx context.Context, groupID string, userIDs []string) (err error) { func (g *GroupMemberGorm) Delete(ctx context.Context, groupID string, userIDs []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userIDs", userIDs)
}()
return utils.Wrap(g.DB.Where("group_id = ? and user_id in (?)", groupID, userIDs).Delete(&relation.GroupMemberModel{}).Error, "") return utils.Wrap(g.DB.Where("group_id = ? and user_id in (?)", groupID, userIDs).Delete(&relation.GroupMemberModel{}).Error, "")
} }
func (g *GroupMemberGorm) DeleteGroup(ctx context.Context, groupIDs []string) (err error) { func (g *GroupMemberGorm) DeleteGroup(ctx context.Context, groupIDs []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs)
}()
return utils.Wrap(g.DB.Where("group_id in (?)", groupIDs).Delete(&relation.GroupMemberModel{}).Error, "") return utils.Wrap(g.DB.Where("group_id in (?)", groupIDs).Delete(&relation.GroupMemberModel{}).Error, "")
} }
func (g *GroupMemberGorm) Update(ctx context.Context, groupID string, userID string, data map[string]any) (err error) { func (g *GroupMemberGorm) Update(ctx context.Context, groupID string, userID string, data map[string]any) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "data", data)
}()
return utils.Wrap(g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ? and user_id = ?", groupID, userID).Updates(data).Error, "") return utils.Wrap(g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ? and user_id = ?", groupID, userID).Updates(data).Error, "")
} }
func (g *GroupMemberGorm) UpdateRoleLevel(ctx context.Context, groupID string, userID string, roleLevel int32) (rowsAffected int64, err error) { func (g *GroupMemberGorm) UpdateRoleLevel(ctx context.Context, groupID string, userID string, roleLevel int32) (rowsAffected int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "roleLevel", roleLevel)
}()
db := g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ? and user_id = ?", groupID, userID).Updates(map[string]any{ db := g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ? and user_id = ?", groupID, userID).Updates(map[string]any{
"role_level": roleLevel, "role_level": roleLevel,
}) })
@ -62,9 +46,6 @@ func (g *GroupMemberGorm) UpdateRoleLevel(ctx context.Context, groupID string, u
} }
func (g *GroupMemberGorm) Find(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) (groupList []*relation.GroupMemberModel, err error) { func (g *GroupMemberGorm) Find(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) (groupList []*relation.GroupMemberModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs, "userIDs", userIDs, "groupList", groupList)
}()
db := g.DB db := g.DB
if len(groupIDs) > 0 { if len(groupIDs) > 0 {
db = db.Where("group_id in (?)", groupIDs) db = db.Where("group_id in (?)", groupIDs)
@ -79,25 +60,16 @@ func (g *GroupMemberGorm) Find(ctx context.Context, groupIDs []string, userIDs [
} }
func (g *GroupMemberGorm) Take(ctx context.Context, groupID string, userID string) (groupMember *relation.GroupMemberModel, err error) { func (g *GroupMemberGorm) Take(ctx context.Context, groupID string, userID string) (groupMember *relation.GroupMemberModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "groupMember", *groupMember)
}()
groupMember = &relation.GroupMemberModel{} groupMember = &relation.GroupMemberModel{}
return groupMember, utils.Wrap(g.DB.Where("group_id = ? and user_id = ?", groupID, userID).Take(groupMember).Error, "") return groupMember, utils.Wrap(g.DB.Where("group_id = ? and user_id = ?", groupID, userID).Take(groupMember).Error, "")
} }
func (g *GroupMemberGorm) TakeOwner(ctx context.Context, groupID string) (groupMember *relation.GroupMemberModel, err error) { func (g *GroupMemberGorm) TakeOwner(ctx context.Context, groupID string) (groupMember *relation.GroupMemberModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "groupMember", *groupMember)
}()
groupMember = &relation.GroupMemberModel{} groupMember = &relation.GroupMemberModel{}
return groupMember, utils.Wrap(g.DB.Where("group_id = ? and role_level = ?", groupID, constant.GroupOwner).Take(groupMember).Error, "") return groupMember, utils.Wrap(g.DB.Where("group_id = ? and role_level = ?", groupID, constant.GroupOwner).Take(groupMember).Error, "")
} }
func (g *GroupMemberGorm) SearchMember(ctx context.Context, keyword string, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (total uint32, groupList []*relation.GroupMemberModel, err error) { func (g *GroupMemberGorm) SearchMember(ctx context.Context, keyword string, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (total uint32, groupList []*relation.GroupMemberModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "keyword", keyword, "groupIDs", groupIDs, "userIDs", userIDs, "roleLevels", roleLevels, "pageNumber", pageNumber, "showNumber", showNumber, "total", total, "groupList", groupList)
}()
db := g.DB db := g.DB
gormIn(&db, "group_id", groupIDs) gormIn(&db, "group_id", groupIDs)
gormIn(&db, "user_id", userIDs) gormIn(&db, "user_id", userIDs)
@ -106,16 +78,10 @@ func (g *GroupMemberGorm) SearchMember(ctx context.Context, keyword string, grou
} }
func (g *GroupMemberGorm) MapGroupMemberNum(ctx context.Context, groupIDs []string) (count map[string]uint32, err error) { func (g *GroupMemberGorm) MapGroupMemberNum(ctx context.Context, groupIDs []string) (count map[string]uint32, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs, "count", count)
}()
return mapCount(g.DB.Where("group_id in (?)", groupIDs), "group_id") return mapCount(g.DB.Where("group_id in (?)", groupIDs), "group_id")
} }
func (g *GroupMemberGorm) FindJoinUserID(ctx context.Context, groupIDs []string) (groupUsers map[string][]string, err error) { func (g *GroupMemberGorm) FindJoinUserID(ctx context.Context, groupIDs []string) (groupUsers map[string][]string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs, "groupUsers", groupUsers)
}()
var items []struct { var items []struct {
GroupID string `gorm:"group_id"` GroupID string `gorm:"group_id"`
UserID string `gorm:"user_id"` UserID string `gorm:"user_id"`
@ -131,8 +97,5 @@ func (g *GroupMemberGorm) FindJoinUserID(ctx context.Context, groupIDs []string)
} }
func (g *GroupMemberGorm) FindMemberUserID(ctx context.Context, groupID string) (userIDs []string, err error) { func (g *GroupMemberGorm) FindMemberUserID(ctx context.Context, groupID string) (userIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userIDs", userIDs)
}()
return userIDs, utils.Wrap(g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ?", groupID).Pluck("user_id", &userIDs).Error, "") return userIDs, utils.Wrap(g.DB.Model(&relation.GroupMemberModel{}).Where("group_id = ?", groupID).Pluck("user_id", &userIDs).Error, "")
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -23,51 +22,30 @@ func (g *GroupGorm) NewTx(tx any) relation.GroupModelInterface {
} }
func (g *GroupGorm) Create(ctx context.Context, groups []*relation.GroupModel) (err error) { func (g *GroupGorm) Create(ctx context.Context, groups []*relation.GroupModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groups", groups)
}()
return utils.Wrap(g.DB.Create(&groups).Error, "") return utils.Wrap(g.DB.Create(&groups).Error, "")
} }
func (g *GroupGorm) UpdateMap(ctx context.Context, groupID string, args map[string]interface{}) (err error) { func (g *GroupGorm) UpdateMap(ctx context.Context, groupID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "args", args)
}()
return utils.Wrap(g.DB.Where("group_id = ?", groupID).Model(&relation.GroupModel{}).Updates(args).Error, "") return utils.Wrap(g.DB.Where("group_id = ?", groupID).Model(&relation.GroupModel{}).Updates(args).Error, "")
} }
func (g *GroupGorm) UpdateStatus(ctx context.Context, groupID string, status int32) (err error) { func (g *GroupGorm) UpdateStatus(ctx context.Context, groupID string, status int32) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "status", status)
}()
return utils.Wrap(g.DB.Where("group_id = ?", groupID).Model(&relation.GroupModel{}).Updates(map[string]any{"status": status}).Error, "") return utils.Wrap(g.DB.Where("group_id = ?", groupID).Model(&relation.GroupModel{}).Updates(map[string]any{"status": status}).Error, "")
} }
func (g *GroupGorm) Find(ctx context.Context, groupIDs []string) (groups []*relation.GroupModel, err error) { func (g *GroupGorm) Find(ctx context.Context, groupIDs []string) (groups []*relation.GroupModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs, "groups", groups)
}()
return groups, utils.Wrap(g.DB.Where("group_id in (?)", groupIDs).Find(&groups).Error, "") return groups, utils.Wrap(g.DB.Where("group_id in (?)", groupIDs).Find(&groups).Error, "")
} }
func (g *GroupGorm) Take(ctx context.Context, groupID string) (group *relation.GroupModel, err error) { func (g *GroupGorm) Take(ctx context.Context, groupID string) (group *relation.GroupModel, err error) {
group = &relation.GroupModel{} group = &relation.GroupModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "group", group)
}()
return group, utils.Wrap(g.DB.Where("group_id = ?", groupID).Take(group).Error, "") return group, utils.Wrap(g.DB.Where("group_id = ?", groupID).Take(group).Error, "")
} }
func (g *GroupGorm) Search(ctx context.Context, keyword string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupModel, err error) { func (g *GroupGorm) Search(ctx context.Context, keyword string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "keyword", keyword, "pageNumber", pageNumber, "showNumber", showNumber, "total", total, "groups", groups)
}()
return gormSearch[relation.GroupModel](g.DB, []string{"name"}, keyword, pageNumber, showNumber) return gormSearch[relation.GroupModel](g.DB, []string{"name"}, keyword, pageNumber, showNumber)
} }
func (g *GroupGorm) GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error) { func (g *GroupGorm) GetGroupIDsByGroupType(ctx context.Context, groupType int) (groupIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupType", groupType, "groupIDs", groupIDs)
}()
return groupIDs, utils.Wrap(g.DB.Model(&relation.GroupModel{}).Where("group_type = ? ", groupType).Pluck("group_id", &groupIDs).Error, "") return groupIDs, utils.Wrap(g.DB.Model(&relation.GroupModel{}).Where("group_type = ? ", groupType).Pluck("group_id", &groupIDs).Error, "")
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -25,16 +24,10 @@ func NewGroupRequest(db *gorm.DB) relation.GroupRequestModelInterface {
} }
func (g *GroupRequestGorm) Create(ctx context.Context, groupRequests []*relation.GroupRequestModel) (err error) { func (g *GroupRequestGorm) Create(ctx context.Context, groupRequests []*relation.GroupRequestModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupRequests", groupRequests)
}()
return utils.Wrap(g.DB.Create(&groupRequests).Error, utils.GetSelfFuncName()) return utils.Wrap(g.DB.Create(&groupRequests).Error, utils.GetSelfFuncName())
} }
func (g *GroupRequestGorm) UpdateHandler(ctx context.Context, groupID string, userID string, handledMsg string, handleResult int32) (err error) { func (g *GroupRequestGorm) UpdateHandler(ctx context.Context, groupID string, userID string, handledMsg string, handleResult int32) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "handledMsg", handledMsg, "handleResult", handleResult)
}()
return utils.Wrap(g.DB.Model(&relation.GroupRequestModel{}).Where("group_id = ? and user_id = ? ", groupID, userID).Updates(map[string]any{ return utils.Wrap(g.DB.Model(&relation.GroupRequestModel{}).Where("group_id = ? and user_id = ? ", groupID, userID).Updates(map[string]any{
"handle_msg": handledMsg, "handle_msg": handledMsg,
"handle_result": handleResult, "handle_result": handleResult,
@ -43,15 +36,9 @@ func (g *GroupRequestGorm) UpdateHandler(ctx context.Context, groupID string, us
func (g *GroupRequestGorm) Take(ctx context.Context, groupID string, userID string) (groupRequest *relation.GroupRequestModel, err error) { func (g *GroupRequestGorm) Take(ctx context.Context, groupID string, userID string) (groupRequest *relation.GroupRequestModel, err error) {
groupRequest = &relation.GroupRequestModel{} groupRequest = &relation.GroupRequestModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "groupRequest", *groupRequest)
}()
return groupRequest, utils.Wrap(g.DB.Where("group_id = ? and user_id = ? ", groupID, userID).Take(groupRequest).Error, utils.GetSelfFuncName()) return groupRequest, utils.Wrap(g.DB.Where("group_id = ? and user_id = ? ", groupID, userID).Take(groupRequest).Error, utils.GetSelfFuncName())
} }
func (g *GroupRequestGorm) Page(ctx context.Context, userID string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupRequestModel, err error) { func (g *GroupRequestGorm) Page(ctx context.Context, userID string, pageNumber, showNumber int32) (total uint32, groups []*relation.GroupRequestModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "pageNumber", pageNumber, "showNumber", showNumber, "total", total, "groups", groups)
}()
return gormSearch[relation.GroupRequestModel](g.DB.Where("user_id = ?", userID), nil, "", pageNumber, showNumber) return gormSearch[relation.GroupRequestModel](g.DB.Where("user_id = ?", userID), nil, "", pageNumber, showNumber)
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -25,24 +24,15 @@ func (o *ObjectHashGorm) NewTx(tx any) relation.ObjectHashModelInterface {
} }
func (o *ObjectHashGorm) Take(ctx context.Context, hash string, engine string) (oh *relation.ObjectHashModel, err error) { func (o *ObjectHashGorm) Take(ctx context.Context, hash string, engine string) (oh *relation.ObjectHashModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "hash", hash, "engine", engine, "objectHash", oh)
}()
oh = &relation.ObjectHashModel{} oh = &relation.ObjectHashModel{}
return oh, utils.Wrap1(o.DB.Where("hash = ? and engine = ?", hash, engine).Take(oh).Error) return oh, utils.Wrap1(o.DB.Where("hash = ? and engine = ?", hash, engine).Take(oh).Error)
} }
func (o *ObjectHashGorm) Create(ctx context.Context, h []*relation.ObjectHashModel) (err error) { func (o *ObjectHashGorm) Create(ctx context.Context, h []*relation.ObjectHashModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "objectHash", h)
}()
return utils.Wrap1(o.DB.Create(h).Error) return utils.Wrap1(o.DB.Create(h).Error)
} }
func (o *ObjectHashGorm) DeleteNoCitation(ctx context.Context, engine string, num int) (list []*relation.ObjectHashModel, err error) { func (o *ObjectHashGorm) DeleteNoCitation(ctx context.Context, engine string, num int) (list []*relation.ObjectHashModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "engine", engine, "num", num, "objectHash", list)
}()
err = o.DB.Table(relation.ObjectHashModelTableName, "as h").Select("h.*"). err = o.DB.Table(relation.ObjectHashModelTableName, "as h").Select("h.*").
Joins("LEFT JOIN "+relation.ObjectInfoModelTableName+" as i ON h.hash = i.hash"). Joins("LEFT JOIN "+relation.ObjectInfoModelTableName+" as i ON h.hash = i.hash").
Where("h.engine = ? AND i.hash IS NULL", engine). Where("h.engine = ? AND i.hash IS NULL", engine).

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -26,9 +25,6 @@ func (o *ObjectInfoGorm) NewTx(tx any) relation.ObjectInfoModelInterface {
} }
func (o *ObjectInfoGorm) SetObject(ctx context.Context, obj *relation.ObjectInfoModel) (err error) { func (o *ObjectInfoGorm) SetObject(ctx context.Context, obj *relation.ObjectInfoModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "objectInfo", obj)
}()
return utils.Wrap1(o.DB.Transaction(func(tx *gorm.DB) error { return utils.Wrap1(o.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("name = ?", obj.Name).Delete(&relation.ObjectInfoModel{}).Error; err != nil { if err := tx.Where("name = ?", obj.Name).Delete(&relation.ObjectInfoModel{}).Error; err != nil {
return err return err
@ -38,16 +34,10 @@ func (o *ObjectInfoGorm) SetObject(ctx context.Context, obj *relation.ObjectInfo
} }
func (o *ObjectInfoGorm) Take(ctx context.Context, name string) (info *relation.ObjectInfoModel, err error) { func (o *ObjectInfoGorm) Take(ctx context.Context, name string) (info *relation.ObjectInfoModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "name", name, "info", info)
}()
info = &relation.ObjectInfoModel{} info = &relation.ObjectInfoModel{}
return info, utils.Wrap1(o.DB.Where("name = ?", name).Take(info).Error) return info, utils.Wrap1(o.DB.Where("name = ?", name).Take(info).Error)
} }
func (o *ObjectInfoGorm) DeleteExpiration(ctx context.Context, expiration time.Time) (err error) { func (o *ObjectInfoGorm) DeleteExpiration(ctx context.Context, expiration time.Time) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "expiration", expiration)
}()
return utils.Wrap1(o.DB.Where("expiration_time IS NOT NULL AND expiration_time <= ?", expiration).Delete(&relation.ObjectInfoModel{}).Error) return utils.Wrap1(o.DB.Where("expiration_time IS NOT NULL AND expiration_time <= ?", expiration).Delete(&relation.ObjectInfoModel{}).Error)
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -26,38 +25,23 @@ func (o *ObjectPutGorm) NewTx(tx any) relation.ObjectPutModelInterface {
} }
func (o *ObjectPutGorm) Create(ctx context.Context, m []*relation.ObjectPutModel) (err error) { func (o *ObjectPutGorm) Create(ctx context.Context, m []*relation.ObjectPutModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "objectPut", m)
}()
return utils.Wrap1(o.DB.Create(m).Error) return utils.Wrap1(o.DB.Create(m).Error)
} }
func (o *ObjectPutGorm) Take(ctx context.Context, putID string) (put *relation.ObjectPutModel, err error) { func (o *ObjectPutGorm) Take(ctx context.Context, putID string) (put *relation.ObjectPutModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "putID", putID, "put", put)
}()
put = &relation.ObjectPutModel{} put = &relation.ObjectPutModel{}
return put, utils.Wrap1(o.DB.Where("put_id = ?", putID).Take(put).Error) return put, utils.Wrap1(o.DB.Where("put_id = ?", putID).Take(put).Error)
} }
func (o *ObjectPutGorm) SetCompleted(ctx context.Context, putID string) (err error) { func (o *ObjectPutGorm) SetCompleted(ctx context.Context, putID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "putID", putID)
}()
return utils.Wrap1(o.DB.Model(&relation.ObjectPutModel{}).Where("put_id = ?", putID).Update("complete", true).Error) return utils.Wrap1(o.DB.Model(&relation.ObjectPutModel{}).Where("put_id = ?", putID).Update("complete", true).Error)
} }
func (o *ObjectPutGorm) FindExpirationPut(ctx context.Context, expirationTime time.Time, num int) (list []*relation.ObjectPutModel, err error) { func (o *ObjectPutGorm) FindExpirationPut(ctx context.Context, expirationTime time.Time, num int) (list []*relation.ObjectPutModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "expirationTime", expirationTime, "num", num, "list", list)
}()
err = o.DB.Where("effective_time <= ?", expirationTime).Limit(num).Find(&list).Error err = o.DB.Where("effective_time <= ?", expirationTime).Limit(num).Find(&list).Error
return list, utils.Wrap1(err) return list, utils.Wrap1(err)
} }
func (o *ObjectPutGorm) DelPut(ctx context.Context, ids []string) (err error) { func (o *ObjectPutGorm) DelPut(ctx context.Context, ids []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ids", ids)
}()
return utils.Wrap1(o.DB.Where("put_id IN ?", ids).Delete(&relation.ObjectPutModel{}).Error) return utils.Wrap1(o.DB.Where("put_id IN ?", ids).Delete(&relation.ObjectPutModel{}).Error)
} }

View File

@ -2,7 +2,6 @@ package relation
import ( import (
"OpenIM/pkg/common/db/table/relation" "OpenIM/pkg/common/db/table/relation"
"OpenIM/pkg/common/tracelog"
"OpenIM/pkg/utils" "OpenIM/pkg/utils"
"context" "context"
"gorm.io/gorm" "gorm.io/gorm"
@ -18,33 +17,21 @@ func NewUserGorm(DB *gorm.DB) relation.UserModelInterface {
// 插入多条 // 插入多条
func (u *UserGorm) Create(ctx context.Context, users []*relation.UserModel) (err error) { func (u *UserGorm) Create(ctx context.Context, users []*relation.UserModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "users", users)
}()
return utils.Wrap(u.DB.Create(&users).Error, "") return utils.Wrap(u.DB.Create(&users).Error, "")
} }
// 更新用户信息 零值 // 更新用户信息 零值
func (u *UserGorm) UpdateByMap(ctx context.Context, userID string, args map[string]interface{}) (err error) { func (u *UserGorm) UpdateByMap(ctx context.Context, userID string, args map[string]interface{}) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "args", args)
}()
return utils.Wrap(u.DB.Where("user_id = ?", userID).Updates(args).Error, "") return utils.Wrap(u.DB.Where("user_id = ?", userID).Updates(args).Error, "")
} }
// 更新多个用户信息 非零值 // 更新多个用户信息 非零值
func (u *UserGorm) Update(ctx context.Context, users []*relation.UserModel) (err error) { func (u *UserGorm) Update(ctx context.Context, users []*relation.UserModel) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "users", users)
}()
return utils.Wrap(u.DB.Updates(&users).Error, "") return utils.Wrap(u.DB.Updates(&users).Error, "")
} }
// 获取指定用户信息 不存在,也不返回错误 // 获取指定用户信息 不存在,也不返回错误
func (u *UserGorm) Find(ctx context.Context, userIDs []string) (users []*relation.UserModel, err error) { func (u *UserGorm) Find(ctx context.Context, userIDs []string) (users []*relation.UserModel, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userIDs", userIDs, "users", users)
}()
err = utils.Wrap(u.DB.Debug().Where("user_id in ?", userIDs).Find(&users).Error, "") err = utils.Wrap(u.DB.Debug().Where("user_id in ?", userIDs).Find(&users).Error, "")
return users, err return users, err
} }
@ -52,18 +39,12 @@ func (u *UserGorm) Find(ctx context.Context, userIDs []string) (users []*relatio
// 获取某个用户信息 不存在,则返回错误 // 获取某个用户信息 不存在,则返回错误
func (u *UserGorm) Take(ctx context.Context, userID string) (user *relation.UserModel, err error) { func (u *UserGorm) Take(ctx context.Context, userID string) (user *relation.UserModel, err error) {
user = &relation.UserModel{} user = &relation.UserModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "user", *user)
}()
err = utils.Wrap(u.DB.Where("user_id = ?", userID).Take(&user).Error, "") err = utils.Wrap(u.DB.Where("user_id = ?", userID).Take(&user).Error, "")
return user, err return user, err
} }
// 获取用户信息 不存在,不返回错误 // 获取用户信息 不存在,不返回错误
func (u *UserGorm) Page(ctx context.Context, pageNumber, showNumber int32) (users []*relation.UserModel, count int64, err error) { func (u *UserGorm) Page(ctx context.Context, pageNumber, showNumber int32) (users []*relation.UserModel, count int64, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "pageNumber", pageNumber, "showNumber", showNumber, "users", users, "count", count)
}()
err = utils.Wrap(u.DB.Count(&count).Error, "") err = utils.Wrap(u.DB.Count(&count).Error, "")
if err != nil { if err != nil {
return return
@ -74,9 +55,6 @@ func (u *UserGorm) Page(ctx context.Context, pageNumber, showNumber int32) (user
// 获取所有用户ID // 获取所有用户ID
func (u *UserGorm) GetAllUserID(ctx context.Context) (userIDs []string, err error) { func (u *UserGorm) GetAllUserID(ctx context.Context) (userIDs []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userIDs", userIDs)
}()
err = u.DB.Pluck("user_id", &userIDs).Error err = u.DB.Pluck("user_id", &userIDs).Error
return userIDs, err return userIDs, err
} }

View File

@ -43,7 +43,7 @@ func NewMConsumerGroup(consumerConfig *MConsumerGroupConfig, topics, addrs []str
} }
func (mc *MConsumerGroup) GetContextFromMsg(cMsg *sarama.ConsumerMessage, rootFuncName string) context.Context { func (mc *MConsumerGroup) GetContextFromMsg(cMsg *sarama.ConsumerMessage, rootFuncName string) context.Context {
ctx := tracelog.NewCtx(rootFuncName, "") ctx := tracelog.NewCtx(rootFuncName)
var operationID string var operationID string
for _, v := range cMsg.Headers { for _, v := range cMsg.Headers {
if string(v.Key) == constant.OperationID { if string(v.Key) == constant.OperationID {

View File

@ -1,88 +0,0 @@
package log
import (
"OpenIM/pkg/common/tracelog"
"context"
"github.com/sirupsen/logrus"
)
func ShowLog(ctx context.Context) {
t := ctx.Value(tracelog.TraceLogKey).(*tracelog.FuncInfos)
OperationID := tracelog.GetOperationID(ctx)
for _, v := range *t.Funcs {
if v.Err != nil {
ctxLogger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": ctxLogger.Pid,
"FilePath": v.File,
}).Errorln("func: ", v.FuncName, " args: ", v.Args, v.Err.Error())
} else {
switch v.LogLevel {
case logrus.InfoLevel:
ctxLogger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": ctxLogger.Pid,
"FilePath": v.File,
}).Infoln("func: ", v.FuncName, " args: ", v.Args)
case logrus.DebugLevel:
ctxLogger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": ctxLogger.Pid,
"FilePath": v.File,
}).Debugln("func: ", v.FuncName, " args: ", v.Args)
case logrus.WarnLevel:
ctxLogger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": ctxLogger.Pid,
"FilePath": v.File,
}).Warnln("func: ", v.FuncName, " args: ", v.Args)
}
}
}
}
func InfoWithCtx(ctx context.Context, args ...interface{}) {
t := ctx.Value(tracelog.TraceLogKey).(*tracelog.FuncInfos)
OperationID := tracelog.GetOperationID(ctx)
for _, v := range *t.Funcs {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Infoln(v.Args, args)
}
}
func DebugWithCtx(ctx context.Context, args ...interface{}) {
t := ctx.Value(tracelog.TraceLogKey).(*tracelog.FuncInfos)
OperationID := tracelog.GetOperationID(ctx)
for _, v := range *t.Funcs {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Debugln(v.Args, args)
}
}
func ErrorWithCtx(ctx context.Context, args ...interface{}) {
t := ctx.Value(tracelog.TraceLogKey).(*tracelog.FuncInfos)
OperationID := tracelog.GetOperationID(ctx)
for _, v := range *t.Funcs {
if v.Err != nil {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Errorln(v.Err, v.Args, args)
}
}
}
func WarnWithCtx(ctx context.Context, args ...interface{}) {
t := ctx.Value(tracelog.TraceLogKey).(*tracelog.FuncInfos)
OperationID := tracelog.GetOperationID(ctx)
for _, v := range *t.Funcs {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Warnln(v.Args, args)
}
}

View File

@ -1,57 +0,0 @@
/*
** description("").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/2/22 11:52).
*/
package log
import (
"strconv"
"time"
)
const (
TimeOffset = 8 * 3600 //8 hour offset
HalfOffset = 12 * 3600 //Half-day hourly offset
)
//Get the current timestamp
func GetCurrentTimestamp() int64 {
return time.Now().Unix()
}
//Get the current 0 o'clock timestamp
func GetCurDayZeroTimestamp() int64 {
timeStr := time.Now().Format("2006-01-02")
t, _ := time.Parse("2006-01-02", timeStr)
return t.Unix() - TimeOffset
}
//Get the timestamp at 12 o'clock on the day
func GetCurDayHalfTimestamp() int64 {
return GetCurDayZeroTimestamp() + HalfOffset
}
//Get the formatted time at 0 o'clock of the day, the format is "2006-01-02_00-00-00"
func GetCurDayZeroTimeFormat() string {
return time.Unix(GetCurDayZeroTimestamp(), 0).Format("2006-01-02_15-04-05")
}
//Get the formatted time at 12 o'clock of the day, the format is "2006-01-02_12-00-00"
func GetCurDayHalfTimeFormat() string {
return time.Unix(GetCurDayZeroTimestamp()+HalfOffset, 0).Format("2006-01-02_15-04-05")
}
func GetTimeStampByFormat(datetime string) string {
timeLayout := "2006-01-02 15:04:05" //转化所需模板
loc, _ := time.LoadLocation("Local") //获取时区
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
timestamp := tmp.Unix() //转化为时间戳 类型是int64
return strconv.FormatInt(timestamp, 10)
}
func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 {
tm, _ := time.Parse(timeFormat, timeSrc)
return tm.Unix()
}

View File

@ -85,6 +85,10 @@ func (l *ZapLogger) cores() (zap.Option, error) {
c := zap.NewProductionEncoderConfig() c := zap.NewProductionEncoderConfig()
c.EncodeTime = zapcore.ISO8601TimeEncoder c.EncodeTime = zapcore.ISO8601TimeEncoder
c.EncodeDuration = zapcore.SecondsDurationEncoder c.EncodeDuration = zapcore.SecondsDurationEncoder
c.MessageKey = "msg"
c.LevelKey = "level"
c.TimeKey = "time"
c.CallerKey = "caller"
//c.EncodeLevel = zapcore.LowercaseColorLevelEncoder //c.EncodeLevel = zapcore.LowercaseColorLevelEncoder
fileEncoder := zapcore.NewJSONEncoder(c) fileEncoder := zapcore.NewJSONEncoder(c)
fileEncoder.AddInt("PID", os.Getpid()) fileEncoder.AddInt("PID", os.Getpid())

View File

@ -1,131 +0,0 @@
package mw
import (
"OpenIM/pkg/common/constant"
"OpenIM/pkg/common/log"
"OpenIM/pkg/common/mw/specialerror"
"OpenIM/pkg/errs"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/wrapperspb"
"math"
"runtime/debug"
"errors"
)
const OperationID = "operationID"
const OpUserID = "opUserID"
func rpcString(v interface{}) string {
if s, ok := v.(interface{ String() string }); ok {
return s.String()
}
return fmt.Sprintf("%+v", v)
}
func rpcServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
var operationID string
defer func() {
if r := recover(); r != nil {
log.ZError(ctx, "rpc panic", nil, "FullMethod", info.FullMethod, "type:", fmt.Sprintf("%T", r), "panic:", r, string(debug.Stack()))
}
}()
log.Info("", "rpc come here,in rpc call")
funcName := info.FullMethod
log.ZInfo(ctx, "rpc req", "funcName", funcName, "req", rpcString(req))
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.New(codes.InvalidArgument, "missing metadata").Err()
}
if opts := md.Get(OperationID); len(opts) != 1 || opts[0] == "" {
return nil, status.New(codes.InvalidArgument, "operationID error").Err()
} else {
operationID = opts[0]
}
var opUserID string
if opts := md.Get(OpUserID); len(opts) == 1 {
opUserID = opts[0]
}
ctx = context.WithValue(ctx, OperationID, operationID)
ctx = context.WithValue(ctx, OpUserID, opUserID)
resp, err = handler(ctx, req)
if err == nil {
log.Info(operationID, "opUserID", opUserID, "RPC", funcName, "Resp", rpcString(resp))
return resp, nil
}
log.ZError(ctx, "rpc InternalServer:", err, "req", req)
unwrap := errs.Unwrap(err)
codeErr := specialerror.ErrCode(unwrap)
if codeErr == nil {
log.ZError(ctx, "rpc InternalServer:", err, "req", req)
codeErr = errs.ErrInternalServer
}
var stack string
if unwrap != err {
stack = fmt.Sprintf("%+v", err)
log.ZError(ctx, "rpc error stack:", err)
}
code := codeErr.Code()
if code <= 0 || code > math.MaxUint32 {
log.ZError(ctx, "rpc UnknownError", err, "rpc UnknownCode:", code)
code = errs.ServerInternalError
}
grpcStatus := status.New(codes.Code(code), codeErr.Msg())
if errs.Unwrap(err) != err {
if details, err := grpcStatus.WithDetails(wrapperspb.String(stack)); err == nil {
grpcStatus = details
}
}
log.ZInfo(ctx, "rpc resp", "funcName", funcName, "Resp", rpcString(resp))
return nil, grpcStatus.Err()
}
func rpcClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
if ctx == nil {
return errs.ErrInternalServer.Wrap("call rpc request context is nil")
}
operationID, ok := ctx.Value(constant.OperationID).(string)
if !ok {
log.ZError(ctx, "ctx missing operationID", errors.New("ctx missing operationID"))
return errs.ErrArgs.Wrap("ctx missing operationID")
}
md := metadata.Pairs(constant.OperationID, operationID)
opUserID, ok := ctx.Value(constant.OpUserID).(string)
if ok {
md.Append(constant.OpUserID, opUserID)
}
log.Info(operationID, "OpUserID", "RPC", method, "Req", rpcString(req))
err = invoker(metadata.NewOutgoingContext(ctx, md), method, req, reply, cc, opts...)
if err == nil {
log.Info(operationID, "Resp", rpcString(reply))
return nil
}
log.Info(operationID, "rpc error:", err.Error())
rpcErr, ok := err.(interface{ GRPCStatus() *status.Status })
if !ok {
return errs.ErrInternalServer.Wrap(err.Error())
}
sta := rpcErr.GRPCStatus()
if sta.Code() == 0 {
return errs.NewCodeError(errs.ServerInternalError, err.Error()).Wrap()
}
if details := sta.Details(); len(details) > 0 {
if v, ok := details[0].(*wrapperspb.StringValue); ok {
return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap(v.String())
}
}
return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap()
}
func GrpcServer() grpc.ServerOption {
return grpc.UnaryInterceptor(rpcServerInterceptor)
}
func GrpcClient() grpc.DialOption {
return grpc.WithUnaryInterceptor(rpcClientInterceptor)
}

View File

@ -0,0 +1,54 @@
package mw
import (
"OpenIM/pkg/common/constant"
"OpenIM/pkg/common/log"
"OpenIM/pkg/errs"
"context"
"errors"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func GrpcClient() grpc.DialOption {
return grpc.WithUnaryInterceptor(rpcClientInterceptor)
}
func rpcClientInterceptor(ctx context.Context, method string, req, resp interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
if ctx == nil {
return errs.ErrInternalServer.Wrap("call rpc request context is nil")
}
log.ZInfo(ctx, "rpc req", "req", "funcName", method, rpcString(req))
operationID, ok := ctx.Value(constant.OperationID).(string)
if !ok {
log.ZWarn(ctx, "ctx missing operationID", errors.New("ctx missing operationID"), "funcName", method)
return errs.ErrArgs.Wrap("ctx missing operationID")
}
md := metadata.Pairs(constant.OperationID, operationID)
opUserID, ok := ctx.Value(constant.OpUserID).(string)
if ok {
md.Append(constant.OpUserID, opUserID)
}
err = invoker(metadata.NewOutgoingContext(ctx, md), method, req, resp, cc, opts...)
if err == nil {
log.ZInfo(ctx, "rpc resp", "funcName", method, rpcString(resp))
return nil
}
log.ZError(ctx, "rpc resp error", err)
rpcErr, ok := err.(interface{ GRPCStatus() *status.Status })
if !ok {
return errs.ErrInternalServer.Wrap(err.Error())
}
sta := rpcErr.GRPCStatus()
if sta.Code() == 0 {
return errs.NewCodeError(errs.ServerInternalError, err.Error()).Wrap()
}
if details := sta.Details(); len(details) > 0 {
if v, ok := details[0].(*wrapperspb.StringValue); ok {
return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap(v.String())
}
}
return errs.NewCodeError(int(sta.Code()), sta.Message()).Wrap()
}

View File

@ -0,0 +1,80 @@
package mw
import (
"OpenIM/pkg/common/log"
"OpenIM/pkg/common/mw/specialerror"
"OpenIM/pkg/errs"
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"math"
"runtime/debug"
)
const OperationID = "operationID"
const OpUserID = "opUserID"
func rpcString(v interface{}) string {
if s, ok := v.(interface{ String() string }); ok {
return s.String()
}
return fmt.Sprintf("%+v", v)
}
func rpcServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
var operationID string
defer func() {
if r := recover(); r != nil {
log.ZError(ctx, "rpc panic", nil, "FullMethod", info.FullMethod, "type:", fmt.Sprintf("%T", r), "panic:", r, string(debug.Stack()))
}
}()
funcName := info.FullMethod
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.New(codes.InvalidArgument, "missing metadata").Err()
}
if opts := md.Get(OperationID); len(opts) != 1 || opts[0] == "" {
return nil, status.New(codes.InvalidArgument, "operationID error").Err()
} else {
operationID = opts[0]
}
var opUserID string
if opts := md.Get(OpUserID); len(opts) == 1 {
opUserID = opts[0]
}
ctx = context.WithValue(ctx, OperationID, operationID)
ctx = context.WithValue(ctx, OpUserID, opUserID)
log.ZInfo(ctx, "rpc req", "funcName", funcName, "req", rpcString(req))
resp, err = handler(ctx, req)
if err == nil {
log.ZInfo(ctx, "rpc resp", "funcName", funcName, "resp", rpcString(resp))
return resp, nil
}
unwrap := errs.Unwrap(err)
codeErr := specialerror.ErrCode(unwrap)
if codeErr == nil {
log.ZError(ctx, "rpc InternalServer error", err, "req", req)
codeErr = errs.ErrInternalServer
}
code := codeErr.Code()
if code <= 0 || code > math.MaxUint32 {
log.ZError(ctx, "rpc UnknownError", err, "rpc UnknownCode:", code)
code = errs.ServerInternalError
}
grpcStatus := status.New(codes.Code(code), codeErr.Msg())
//if unwrap != err {
// stack := fmt.Sprintf("%+v", err)
// if details, err := grpcStatus.WithDetails(wrapperspb.String(stack)); err == nil {
// grpcStatus = details
// }
//}
log.ZWarn(ctx, "rpc resp", unwrap, "funcName", funcName)
return nil, grpcStatus.Err()
}
func GrpcServer() grpc.ServerOption {
return grpc.UnaryInterceptor(rpcServerInterceptor)
}

View File

@ -61,9 +61,6 @@ func GetClaimFromToken(tokensString string) (*Claims, error) {
func CheckAccessV3(ctx context.Context, ownerUserID string) (err error) { func CheckAccessV3(ctx context.Context, ownerUserID string) (err error) {
opUserID := tracelog.GetOpUserID(ctx) opUserID := tracelog.GetOpUserID(ctx)
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "OpUserID", opUserID, "ownerUserID", ownerUserID)
}()
if utils.IsContain(opUserID, config.Config.Manager.AppManagerUid) { if utils.IsContain(opUserID, config.Config.Manager.AppManagerUid) {
return nil return nil
} }

View File

@ -2,43 +2,33 @@ package tracelog
import ( import (
"OpenIM/pkg/common/constant" "OpenIM/pkg/common/constant"
"OpenIM/pkg/utils"
"context" "context"
"github.com/sirupsen/logrus"
"runtime"
"strings"
//"errors"
"fmt"
"github.com/gin-gonic/gin"
) )
const TraceLogKey = "tracelog" func NewCtx(operationID string) context.Context {
func SetFuncInfos(c context.Context, rootFuncName string, operationID string) context.Context {
req := &FuncInfos{RootFuncName: rootFuncName, Funcs: &[]FuncInfo{}}
ctx := context.WithValue(c, TraceLogKey, req)
SetOperationID(ctx, operationID)
return ctx
}
func NewCtx(rootFuncName string, operationID string) context.Context {
c := context.Background() c := context.Background()
req := &FuncInfos{RootFuncName: rootFuncName, Funcs: &[]FuncInfo{}} ctx := context.WithValue(c, constant.OperationID, operationID)
ctx := context.WithValue(c, TraceLogKey, req)
SetOperationID(ctx, operationID) SetOperationID(ctx, operationID)
return ctx return ctx
} }
func SetOperationID(ctx context.Context, operationID string) { func SetOperationID(ctx context.Context, operationID string) {
ctx.Value(TraceLogKey).(*FuncInfos).OperationID = operationID ctx = context.WithValue(ctx, constant.OperationID, operationID)
}
func SetOpUserID(ctx context.Context, opUserID string) {
ctx = context.WithValue(ctx, constant.OpUserID, opUserID)
}
func SetConnID(ctx context.Context, connID string) {
ctx = context.WithValue(ctx, constant.ConnID, connID)
} }
func GetOperationID(ctx context.Context) string { func GetOperationID(ctx context.Context) string {
if ctx.Value(TraceLogKey) != nil { if ctx.Value(constant.OperationID) != nil {
f, ok := ctx.Value(TraceLogKey).(*FuncInfos) s, ok := ctx.Value(constant.OperationID).(string)
if ok { if ok {
return f.OperationID return s
} }
} }
return "" return ""
@ -63,115 +53,3 @@ func GetConnID(ctx context.Context) string {
} }
return "" return ""
} }
func Unwrap(err error) error {
for err != nil {
unwrap, ok := err.(interface {
Unwrap() error
})
if !ok {
break
}
err = unwrap.Unwrap()
}
return err
}
type FuncInfos struct {
RootFuncName string
OperationID string
Funcs *[]FuncInfo
GinCtx *gin.Context
}
type FuncInfo struct {
FuncName string
Args Args
Err error
LogLevel logrus.Level
File string
}
type Args map[string]interface{}
func (a Args) String() string {
var s string
var hasElement bool
for k, v := range a {
if !hasElement {
s += "{"
hasElement = true
}
s += fmt.Sprintf("%s: %v", k, v)
}
if hasElement {
s += "}"
}
return s
}
func SetCtxDebug(ctx context.Context, funcName string, err error, args ...interface{}) {
SetContextInfo(ctx, funcName, logrus.DebugLevel, err, args)
}
func SetCtxInfo(ctx context.Context, funcName string, err error, args ...interface{}) {
SetContextInfo(ctx, funcName, logrus.InfoLevel, err, args)
}
func SetCtxWarn(ctx context.Context, funcName string, err error, args ...interface{}) {
SetContextInfo(ctx, funcName, logrus.WarnLevel, err, args)
}
func SetContextInfo(ctx context.Context, funcName string, logLevel logrus.Level, err error, args ...interface{}) {
var t *FuncInfos
var ok bool
if t, ok = ctx.Value(TraceLogKey).(*FuncInfos); !ok {
return
}
var funcInfo FuncInfo
funcInfo.Args = make(map[string]interface{})
argsHandle(args, funcInfo.Args)
funcInfo.FuncName = funcName
funcInfo.Err = err
funcInfo.LogLevel = logLevel
_, file, line, _ := runtime.Caller(3)
var s string
i := strings.SplitAfter(file, "/")
if len(i) > 3 {
s = i[len(i)-3] + i[len(i)-2] + i[len(i)-1] + ":" + utils.IntToString(line)
}
funcInfo.File = s
*t.Funcs = append(*t.Funcs, funcInfo)
}
func SetRpcReqInfo(ctx context.Context, funcName string, req string) {
t := ctx.Value(TraceLogKey).(*FuncInfos)
var funcInfo FuncInfo
funcInfo.Args = make(map[string]interface{})
var args []interface{}
args = append(args, " rpc req ", req)
argsHandle(args, funcInfo.Args)
funcInfo.FuncName = funcName
*t.Funcs = append(*t.Funcs, funcInfo)
}
func SetRpcRespInfo(ctx context.Context, funcName string, resp string) {
t := ctx.Value(TraceLogKey).(*FuncInfos)
var funcInfo FuncInfo
funcInfo.Args = make(map[string]interface{})
var args []interface{}
args = append(args, " rpc resp ", resp)
argsHandle(args, funcInfo.Args)
funcInfo.FuncName = funcName
*t.Funcs = append(*t.Funcs, funcInfo)
}
func argsHandle(args []interface{}, fields map[string]interface{}) {
for i := 0; i < len(args); i += 2 {
if i+1 < len(args) {
fields[fmt.Sprintf("%v", args[i])] = fmt.Sprintf("%+v", args[i+1])
} else {
fields[fmt.Sprintf("%v", args[i])] = ""
}
}
}

View File

@ -22,84 +22,64 @@ const (
// 通用错误码 // 通用错误码
const ( const (
NoError = 0 //无错误 NoError = 0 //无错误
ArgsError = 90001 //输入参数错误 DatabaseError = 90002 //redis/mysql等db错误
DatabaseError = 90002 //redis/mysql等db错误 NetworkError = 90004 //网络错误
ServerInternalError = 90003 //服务器内部错误 IdentityError = 90008 // 身份错误 非管理员token且token中userID与请求userID不一致
NetworkError = 90004 //网络错误 GRPCConnIsNil = 90006 //grpc连接空
NoPermissionError = 90005 //权限不足 DefaultOtherError = 90006 //其他错误
GRPCConnIsNil = 90006 //grpc连接空 DataError = 90007 //数据错误
ConfigError = 90009
DefaultOtherError = 90006 //其他错误 CallbackError = 80000
DataError = 90007 //数据错误
IdentityError = 90008 // 身份错误 非管理员token且token中userID与请求userID不一致
ConfigError = 90009
CallbackError = 80000
)
const DuplicateKeyError = 12345
// 账号错误码
const (
UserIDNotFoundError = 91001 //UserID不存在 或未注册
GroupIDNotFoundError = 91002 //GroupID不存在
RecordNotFoundError = 91002 //记录不存在
GroupIDIDExisted = 91002 //GroupID已存在
UserIDExisted = 91002 //UserID已存在
)
// 关系链错误码
const (
RelationshipAlreadyError = 92001 //已经是好友关系(或者黑名单) RelationshipAlreadyError = 92001 //已经是好友关系(或者黑名单)
NotRelationshipYetError = 92002 //不是好友关系(或者黑名单) NotRelationshipYetError = 92002 //不是好友关系(或者黑名单)
CanNotAddYourselfError = 92003 //不能添加自己为好友
BlockedByPeer = 92004 //被对方拉黑
NotPeersFriend = 92005 //不是对方的好友
)
// 群组错误码 //通用错误码
const ( ServerInternalError = 500 //服务器内部错误
OnlyOneOwnerError = 93001 //只能有一个群主 ArgsError = 1001 //输入参数错误
InGroupAlreadyError = 93003 //已在群组中 NoPermissionError = 1002 //权限不足
NotInGroupYetError = 93004 //不在群组中 DuplicateKeyError = 1003
DismissedAlreadyError = 93004 //群组已经解散 RecordNotFoundError = 1004 //记录不存在
OwnerNotAllowedQuitError = 93004 //群主不能退群
GroupTypeNotSupport = 93005
GroupNoOwner = 93006
MutedInGroup = 93007 //群成员被禁言 // 账号错误码
MutedGroup = 93008 //群被禁言 UserIDNotFoundError = 1101 //UserID不存在 或未注册
) UserIDExisted = 1102 //UserID已存在
RegisteredAlreadyError = 1103 //用户已经注册过了
// 用户错误码 // 群组错误码
const ( GroupIDNotFoundError = 1201 //GroupID不存在
RegisteredAlreadyError = 94001 //用户已经注册过了 GroupIDIDExisted = 1202 //GroupID已存在
) OnlyOneOwnerError = 1203 //只能有一个群主
InGroupAlreadyError = 1204 //已在群组中
NotInGroupYetError = 1205 //不在群组中
DismissedAlreadyError = 1206 //群组已经解散
OwnerNotAllowedQuitError = 1207 //群主不能退群
GroupTypeNotSupport = 1208
GroupNoOwner = 1209
// token错误码 // 关系链错误码
const ( CanNotAddYourselfError = 1301 //不能添加自己为好友
TokenExpiredError = 95001 BlockedByPeer = 1302 //被对方拉黑
TokenInvalidError = 95002 NotPeersFriend = 1303 //不是对方的好友
TokenMalformedError = 95003
TokenNotValidYetError = 95004
TokenUnknownError = 95005
TokenKickedError = 95006
TokenDifferentPlatformIDError = 95007
TokenDifferentUserIDError = 95008
TokenNotExistError = 95009
)
// 消息错误码 // 消息错误码
const ( MessageHasReadDisable = 1401
MessageHasReadDisable = 96001 MutedInGroup = 1402 //群成员被禁言
) MutedGroup = 1403 //群被禁言
// 长连接网关错误码 // token错误码
const ( TokenExpiredError = 1501
ConnOverMaxNumLimit = 970001 TokenInvalidError = 1502
ConnArgsErr = 970002 TokenMalformedError = 1503
ConnUpdateErr = 970003 TokenNotValidYetError = 1504
TokenUnknownError = 1505
TokenKickedError = 1506
TokenDifferentPlatformIDError = 1507
TokenDifferentUserIDError = 1508
TokenNotExistError = 1509
// 长连接网关错误码
ConnOverMaxNumLimit = 1601
ConnArgsErr = 1602
ConnUpdateErr = 1603
) )