From b6fb98a43176215f16fc52b64abebde51355e5c1 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 14 Sep 2017 12:01:44 -0500 Subject: remove more global references (#7442) --- app/command.go | 4 +- app/command_away.go | 4 +- app/command_channel_header.go | 10 ++-- app/command_channel_purpose.go | 10 ++-- app/command_channel_rename.go | 10 ++-- app/command_channel_rename_test.go | 2 +- app/command_code.go | 2 +- app/command_code_test.go | 2 +- app/command_echo.go | 4 +- app/command_expand_collapse.go | 8 +-- app/command_help.go | 2 +- app/command_invite_people.go | 4 +- app/command_join.go | 10 ++-- app/command_leave.go | 8 +-- app/command_loadtest.go | 40 +++++++-------- app/command_logout.go | 4 +- app/command_me.go | 2 +- app/command_msg.go | 12 ++--- app/command_offline.go | 4 +- app/command_online.go | 4 +- app/command_search.go | 2 +- app/command_settings.go | 2 +- app/command_shortcuts.go | 2 +- app/command_shrug.go | 2 +- app/user_test.go | 34 ++++++------- app/web_conn.go | 12 +++-- store/layered_store.go | 5 +- store/local_cache_supplier.go | 36 +++++++------- store/local_cache_supplier_reactions.go | 10 ++-- store/sql_channel_store.go | 88 ++++++++++++++++----------------- store/sql_emoji_store.go | 21 ++++---- store/sql_file_info_store.go | 22 +++++---- store/sql_post_store.go | 47 +++++++++--------- store/sql_supplier.go | 15 +++--- store/sql_user_store.go | 32 ++++++------ store/sql_webhook_store.go | 17 ++++--- 36 files changed, 252 insertions(+), 241 deletions(-) diff --git a/app/command.go b/app/command.go index 74bc61333..f5b8f1fbb 100644 --- a/app/command.go +++ b/app/command.go @@ -19,7 +19,7 @@ import ( type CommandProvider interface { GetTrigger() string GetCommand(T goi18n.TranslateFunc) *model.Command - DoCommand(args *model.CommandArgs, message string) *model.CommandResponse + DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse } var commandProviders = make(map[string]CommandProvider) @@ -140,7 +140,7 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, * provider := GetCommandProvider(trigger) if provider != nil { - response := provider.DoCommand(args, message) + response := provider.DoCommand(a, args, message) return a.HandleCommandResponse(provider.GetCommand(args.T), args, response, true) } else { if !*utils.Cfg.ServiceSettings.EnableCommands { diff --git a/app/command_away.go b/app/command_away.go index 43cb26fd4..7505f0551 100644 --- a/app/command_away.go +++ b/app/command_away.go @@ -32,8 +32,8 @@ func (me *AwayProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *AwayProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - Global().SetStatusAwayIfNeeded(args.UserId, true) +func (me *AwayProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + a.SetStatusAwayIfNeeded(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")} } diff --git a/app/command_channel_header.go b/app/command_channel_header.go index efbc19dc2..51f40eb4f 100644 --- a/app/command_channel_header.go +++ b/app/command_channel_header.go @@ -34,17 +34,17 @@ func (me *HeaderProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := Global().GetChannel(args.ChannelId) +func (me *HeaderProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_header.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_header.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -57,7 +57,7 @@ func (me *HeaderProvider) DoCommand(args *model.CommandArgs, message string) *mo } *patch.Header = message - _, err = Global().PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_header.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_purpose.go b/app/command_channel_purpose.go index 55ccdb206..d342991c7 100644 --- a/app/command_channel_purpose.go +++ b/app/command_channel_purpose.go @@ -33,17 +33,17 @@ func (me *PurposeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := Global().GetChannel(args.ChannelId) +func (me *PurposeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -60,7 +60,7 @@ func (me *PurposeProvider) DoCommand(args *model.CommandArgs, message string) *m } *patch.Purpose = message - _, err = Global().PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_purpose.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_rename.go b/app/command_channel_rename.go index b6523e4b0..b58a9e091 100644 --- a/app/command_channel_rename.go +++ b/app/command_channel_rename.go @@ -33,17 +33,17 @@ func (me *RenameProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - channel, err := Global().GetChannel(args.ChannelId) +func (me *RenameProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + channel, err := a.GetChannel(args.ChannelId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_rename.channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_OPEN && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_OPEN && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if channel.Type == model.CHANNEL_PRIVATE && !Global().SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { + if channel.Type == model.CHANNEL_PRIVATE && !a.SessionHasPermissionToChannel(args.Session, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) { return &model.CommandResponse{Text: args.T("api.command_channel_rename.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -64,7 +64,7 @@ func (me *RenameProvider) DoCommand(args *model.CommandArgs, message string) *mo } *patch.DisplayName = message - _, err = Global().PatchChannel(channel, patch, args.UserId) + _, err = a.PatchChannel(channel, patch, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_channel_rename.update_channel.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_channel_rename_test.go b/app/command_channel_rename_test.go index 070462036..ed4186c7f 100644 --- a/app/command_channel_rename_test.go +++ b/app/command_channel_rename_test.go @@ -25,7 +25,7 @@ func TestRenameProviderDoCommand(t *testing.T) { "1234567890123456789012": "", "12345678901234567890123": "api.command_channel_rename.too_long.app_error", } { - actual := rp.DoCommand(args, msg).Text + actual := rp.DoCommand(th.App, args, msg).Text assert.Equal(t, expected, actual) } } diff --git a/app/command_code.go b/app/command_code.go index c8d8f92ea..6685144dd 100644 --- a/app/command_code.go +++ b/app/command_code.go @@ -35,7 +35,7 @@ func (me *CodeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *CodeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *CodeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { if len(message) == 0 { return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_code_test.go b/app/command_code_test.go index e9d677a50..89699ab3f 100644 --- a/app/command_code_test.go +++ b/app/command_code_test.go @@ -18,7 +18,7 @@ func TestCodeProviderDoCommand(t *testing.T) { "foo\nbar": " foo\n bar", "foo\nbar\n": " foo\n bar\n ", } { - actual := cp.DoCommand(args, msg).Text + actual := cp.DoCommand(nil, args, msg).Text if actual != expected { t.Errorf("expected `%v`, got `%v`", expected, actual) } diff --git a/app/command_echo.go b/app/command_echo.go index bcfc06b2d..61a24b59a 100644 --- a/app/command_echo.go +++ b/app/command_echo.go @@ -40,7 +40,7 @@ func (me *EchoProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *EchoProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *EchoProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { if len(message) == 0 { return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } @@ -88,7 +88,7 @@ func (me *EchoProvider) DoCommand(args *model.CommandArgs, message string) *mode time.Sleep(time.Duration(delay) * time.Second) - if _, err := Global().CreatePostMissingChannel(post, true); err != nil { + if _, err := a.CreatePostMissingChannel(post, true); err != nil { l4g.Error(args.T("api.command_echo.create.app_error"), err) } }() diff --git a/app/command_expand_collapse.go b/app/command_expand_collapse.go index 484243e02..116e29f17 100644 --- a/app/command_expand_collapse.go +++ b/app/command_expand_collapse.go @@ -52,12 +52,12 @@ func (me *CollapseProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *ExpandProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - return Global().setCollapsePreference(args, false) +func (me *ExpandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + return a.setCollapsePreference(args, false) } -func (me *CollapseProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - return Global().setCollapsePreference(args, true) +func (me *CollapseProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + return a.setCollapsePreference(args, true) } func (a *App) setCollapsePreference(args *model.CommandArgs, isCollapse bool) *model.CommandResponse { diff --git a/app/command_help.go b/app/command_help.go index b0960bfc9..41f3a3cb4 100644 --- a/app/command_help.go +++ b/app/command_help.go @@ -33,7 +33,7 @@ func (h *HelpProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (h *HelpProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (h *HelpProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { helpLink := *utils.Cfg.SupportSettings.HelpLink if helpLink == "" { diff --git a/app/command_invite_people.go b/app/command_invite_people.go index 5ce0f4e9e..d81eaa34a 100644 --- a/app/command_invite_people.go +++ b/app/command_invite_people.go @@ -41,7 +41,7 @@ func (me *InvitePeopleProvider) GetCommand(T goi18n.TranslateFunc) *model.Comman } } -func (me *InvitePeopleProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *InvitePeopleProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { if !utils.Cfg.EmailSettings.SendEmailNotifications { return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")} } @@ -63,7 +63,7 @@ func (me *InvitePeopleProvider) DoCommand(args *model.CommandArgs, message strin return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")} } - if err := Global().InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { + if err := a.InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil { l4g.Error(err.Error()) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")} } diff --git a/app/command_join.go b/app/command_join.go index a4ba6ec31..58b0170be 100644 --- a/app/command_join.go +++ b/app/command_join.go @@ -33,15 +33,15 @@ func (me *JoinProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - if result := <-Global().Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil { +func (me *JoinProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + if result := <-a.Srv.Store.Channel().GetByName(args.TeamId, message, true); result.Err != nil { return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { channel := result.Data.(*model.Channel) if channel.Name == message { allowed := false - if (channel.Type == model.CHANNEL_PRIVATE && Global().SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN { + if (channel.Type == model.CHANNEL_PRIVATE && a.SessionHasPermissionToChannel(args.Session, channel.Id, model.PERMISSION_READ_CHANNEL)) || channel.Type == model.CHANNEL_OPEN { allowed = true } @@ -49,11 +49,11 @@ func (me *JoinProvider) DoCommand(args *model.CommandArgs, message string) *mode return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - if err := Global().JoinChannel(channel, args.UserId); err != nil { + if err := a.JoinChannel(channel, args.UserId); err != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - team, err := Global().GetTeam(channel.TeamId) + team, err := a.GetTeam(channel.TeamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_leave.go b/app/command_leave.go index 1e7c9c113..9d76f7ee5 100644 --- a/app/command_leave.go +++ b/app/command_leave.go @@ -32,21 +32,21 @@ func (me *LeaveProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *LeaveProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LeaveProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { var channel *model.Channel var noChannelErr *model.AppError - if channel, noChannelErr = Global().GetChannel(args.ChannelId); noChannelErr != nil { + if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } if channel.Name == model.DEFAULT_CHANNEL { return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - err := Global().LeaveChannel(args.ChannelId, args.UserId) + err := a.LeaveChannel(args.ChannelId, args.UserId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } - team, err := Global().GetTeam(args.TeamId) + team, err := a.GetTeam(args.TeamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_loadtest.go b/app/command_loadtest.go index df443ccba..629b9c9f5 100644 --- a/app/command_loadtest.go +++ b/app/command_loadtest.go @@ -85,33 +85,33 @@ func (me *LoadTestProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *LoadTestProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { //This command is only available when EnableTesting is true if !utils.Cfg.ServiceSettings.EnableTesting { return &model.CommandResponse{} } if strings.HasPrefix(message, "setup") { - return me.SetupCommand(args, message) + return me.SetupCommand(a, args, message) } if strings.HasPrefix(message, "users") { - return me.UsersCommand(args, message) + return me.UsersCommand(a, args, message) } if strings.HasPrefix(message, "channels") { - return me.ChannelsCommand(args, message) + return me.ChannelsCommand(a, args, message) } if strings.HasPrefix(message, "posts") { - return me.PostsCommand(args, message) + return me.PostsCommand(a, args, message) } if strings.HasPrefix(message, "url") { - return me.UrlCommand(args, message) + return me.UrlCommand(a, args, message) } if strings.HasPrefix(message, "json") { - return me.JsonCommand(args, message) + return me.JsonCommand(a, args, message) } return me.HelpCommand(args, message) } @@ -120,7 +120,7 @@ func (me *LoadTestProvider) HelpCommand(args *model.CommandArgs, message string) return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) SetupCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { tokens := strings.Fields(strings.TrimPrefix(message, "setup")) doTeams := contains(tokens, "teams") doFuzz := contains(tokens, "fuzz") @@ -161,7 +161,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string client := model.NewClient(args.SiteURL) if doTeams { - if err := Global().CreateBasicUser(client); err != nil { + if err := a.CreateBasicUser(client); err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD) @@ -184,7 +184,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string } else { var team *model.Team - if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -204,7 +204,7 @@ func (me *LoadTestProvider) SetupCommand(args *model.CommandArgs, message string return &model.CommandResponse{Text: "Created enviroment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) UsersCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { cmd := strings.TrimSpace(strings.TrimPrefix(message, "users")) doFuzz := false @@ -219,7 +219,7 @@ func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string } var team *model.Team - if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -234,7 +234,7 @@ func (me *LoadTestProvider) UsersCommand(args *model.CommandArgs, message string return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) ChannelsCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels")) doFuzz := false @@ -249,7 +249,7 @@ func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message str } var team *model.Team - if tr := <-Global().Srv.Store.Team().Get(args.TeamId); tr.Err != nil { + if tr := <-a.Srv.Store.Team().Get(args.TeamId); tr.Err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { team = tr.Data.(*model.Team) @@ -265,7 +265,7 @@ func (me *LoadTestProvider) ChannelsCommand(args *model.CommandArgs, message str return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) PostsCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts")) doFuzz := false @@ -288,7 +288,7 @@ func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string } var usernames []string - if result := <-Global().Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil { + if result := <-a.Srv.Store.User().GetProfiles(args.TeamId, 0, 1000); result.Err == nil { profileUsers := result.Data.([]*model.User) usernames = make([]string, len(profileUsers)) i := 0 @@ -315,7 +315,7 @@ func (me *LoadTestProvider) PostsCommand(args *model.CommandArgs, message string return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) UrlCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { url := strings.TrimSpace(strings.TrimPrefix(message, "url")) if len(url) == 0 { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} @@ -357,7 +357,7 @@ func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string) post.ChannelId = args.ChannelId post.UserId = args.UserId - if _, err := Global().CreatePostMissingChannel(post, false); err != nil { + if _, err := a.CreatePostMissingChannel(post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } @@ -365,7 +365,7 @@ func (me *LoadTestProvider) UrlCommand(args *model.CommandArgs, message string) return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } -func (me *LoadTestProvider) JsonCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LoadTestProvider) JsonCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { url := strings.TrimSpace(strings.TrimPrefix(message, "json")) if len(url) == 0 { return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} @@ -396,7 +396,7 @@ func (me *LoadTestProvider) JsonCommand(args *model.CommandArgs, message string) post.Message = message } - if _, err := Global().CreatePostMissingChannel(post, false); err != nil { + if _, err := a.CreatePostMissingChannel(post, false); err != nil { return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} diff --git a/app/command_logout.go b/app/command_logout.go index 0cb5293c3..b21045b6a 100644 --- a/app/command_logout.go +++ b/app/command_logout.go @@ -33,13 +33,13 @@ func (me *LogoutProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *LogoutProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *LogoutProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { FAIL := &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_logout.fail_message")} SUCCESS := &model.CommandResponse{GotoLocation: "/login"} // We can't actually remove the user's cookie from here so we just dump their session and let the browser figure it out if args.Session.Id != "" { - if err := Global().RevokeSessionById(args.Session.Id); err != nil { + if err := a.RevokeSessionById(args.Session.Id); err != nil { return FAIL } return SUCCESS diff --git a/app/command_me.go b/app/command_me.go index 2e23955cb..5683ff80d 100644 --- a/app/command_me.go +++ b/app/command_me.go @@ -33,6 +33,6 @@ func (me *MeProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *MeProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *MeProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: "*" + message + "*"} } diff --git a/app/command_msg.go b/app/command_msg.go index 348499f57..648903f0d 100644 --- a/app/command_msg.go +++ b/app/command_msg.go @@ -36,7 +36,7 @@ func (me *msgProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *msgProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { splitMessage := strings.SplitN(message, " ", 2) @@ -51,7 +51,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model targetUsername = strings.TrimPrefix(targetUsername, "@") var userProfile *model.User - if result := <-Global().Srv.Store.User().GetByUsername(targetUsername); result.Err != nil { + if result := <-a.Srv.Store.User().GetByUsername(targetUsername); result.Err != nil { l4g.Error(result.Err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { @@ -66,9 +66,9 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) targetChannelId := "" - if channel := <-Global().Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { + if channel := <-a.Srv.Store.Channel().GetByName(args.TeamId, channelName, true); channel.Err != nil { if channel.Err.Id == "store.sql_channel.get_by_name.missing.app_error" { - if directChannel, err := Global().CreateDirectChannel(args.UserId, userProfile.Id); err != nil { + if directChannel, err := a.CreateDirectChannel(args.UserId, userProfile.Id); err != nil { l4g.Error(err.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } else { @@ -89,7 +89,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model post.Message = parsedMessage post.ChannelId = targetChannelId post.UserId = args.UserId - if _, err := Global().CreatePostMissingChannel(post, true); err != nil { + if _, err := a.CreatePostMissingChannel(post, true); err != nil { return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } } @@ -101,7 +101,7 @@ func (me *msgProvider) DoCommand(args *model.CommandArgs, message string) *model teamId = args.Session.TeamMembers[0].TeamId } - team, err := Global().GetTeam(teamId) + team, err := a.GetTeam(teamId) if err != nil { return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL} } diff --git a/app/command_offline.go b/app/command_offline.go index d32b0873c..ddc539c06 100644 --- a/app/command_offline.go +++ b/app/command_offline.go @@ -32,8 +32,8 @@ func (me *OfflineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *OfflineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - Global().SetStatusOffline(args.UserId, true) +func (me *OfflineProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + a.SetStatusOffline(args.UserId, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")} } diff --git a/app/command_online.go b/app/command_online.go index ddceaaa4f..b1319dd14 100644 --- a/app/command_online.go +++ b/app/command_online.go @@ -32,8 +32,8 @@ func (me *OnlineProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *OnlineProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { - Global().SetStatusOnline(args.UserId, args.Session.Id, true) +func (me *OnlineProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { + a.SetStatusOnline(args.UserId, args.Session.Id, true) return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")} } diff --git a/app/command_search.go b/app/command_search.go index ea09fe19c..e7fb7617c 100644 --- a/app/command_search.go +++ b/app/command_search.go @@ -33,7 +33,7 @@ func (search *SearchProvider) GetCommand(T goi18n.TranslateFunc) *model.Command } } -func (search *SearchProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (search *SearchProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_search.unsupported.app_error"), diff --git a/app/command_settings.go b/app/command_settings.go index 25401814f..c6fceb504 100644 --- a/app/command_settings.go +++ b/app/command_settings.go @@ -33,7 +33,7 @@ func (settings *SettingsProvider) GetCommand(T goi18n.TranslateFunc) *model.Comm } } -func (settings *SettingsProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (settings *SettingsProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_settings.unsupported.app_error"), diff --git a/app/command_shortcuts.go b/app/command_shortcuts.go index 1f002a5c1..170911af8 100644 --- a/app/command_shortcuts.go +++ b/app/command_shortcuts.go @@ -33,7 +33,7 @@ func (me *ShortcutsProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *ShortcutsProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *ShortcutsProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { // This command is handled client-side and shouldn't hit the server. return &model.CommandResponse{ Text: args.T("api.command_shortcuts.unsupported.app_error"), diff --git a/app/command_shrug.go b/app/command_shrug.go index 55c09eeea..c476e6d88 100644 --- a/app/command_shrug.go +++ b/app/command_shrug.go @@ -33,7 +33,7 @@ func (me *ShrugProvider) GetCommand(T goi18n.TranslateFunc) *model.Command { } } -func (me *ShrugProvider) DoCommand(args *model.CommandArgs, message string) *model.CommandResponse { +func (me *ShrugProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse { rmsg := `¯\\\_(ツ)\_/¯` if len(message) > 0 { rmsg = message + " " + rmsg diff --git a/app/user_test.go b/app/user_test.go index a01ee5c07..63d2aafd5 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -128,8 +128,8 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { var user, user2 *model.User var gitlabUserObj oauthgitlab.GitLabUser - user, gitlabUserObj = createGitlabUser(t, username, email) - user2, _ = createGitlabUser(t, username2, email2) + user, gitlabUserObj = createGitlabUser(t, th.App, username, email) + user2, _ = createGitlabUser(t, th.App, username2, email2) t.Run("UpdateUsername", func(t *testing.T) { t.Run("NoExistingUserWithSameUsername", func(t *testing.T) { @@ -137,9 +137,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.Username != gitlabUserObj.Username { t.Fatal("user's username is not updated") @@ -152,9 +152,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.Username == gitlabUserObj.Username { t.Fatal("user's username is updated though there already exists another user with the same username") @@ -168,9 +168,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.Email != gitlabUserObj.Email { t.Fatal("user's email is not updated") @@ -187,9 +187,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.Email == gitlabUserObj.Email { t.Fatal("user's email is updated though there already exists another user with the same email") @@ -202,9 +202,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.FirstName != "Updated" { t.Fatal("user's first name is not updated") @@ -216,9 +216,9 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { gitlabUser := getGitlabUserPayload(gitlabUserObj, t) data := bytes.NewReader(gitlabUser) - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") - user = getUserFromDB(user.Id, t) + user = getUserFromDB(th.App, user.Id, t) if user.LastName != "Lastname" { t.Fatal("user's last name is not updated") @@ -226,8 +226,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { }) } -func getUserFromDB(id string, t *testing.T) *model.User { - a := Global() +func getUserFromDB(a *App, id string, t *testing.T) *model.User { if user, err := a.GetUser(id); err != nil { t.Fatal("user is not found") return nil @@ -246,8 +245,7 @@ func getGitlabUserPayload(gitlabUser oauthgitlab.GitLabUser, t *testing.T) []byt return payload } -func createGitlabUser(t *testing.T, email string, username string) (*model.User, oauthgitlab.GitLabUser) { - a := Global() +func createGitlabUser(t *testing.T, a *App, email string, username string) (*model.User, oauthgitlab.GitLabUser) { r := rand.New(rand.NewSource(time.Now().UnixNano())) gitlabUserObj := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: username, Login: "user1", Email: email, Name: "Test User"} gitlabUser := getGitlabUserPayload(gitlabUserObj, t) diff --git a/app/web_conn.go b/app/web_conn.go index 8a26f7c9c..556612e79 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -30,6 +30,7 @@ const ( type WebConn struct { sessionExpiresAt int64 // This should stay at the top for 64-bit alignment of 64-bit words accessed atomically + App *App WebSocket *websocket.Conn Send chan model.WebSocketMessage sessionToken atomic.Value @@ -51,6 +52,7 @@ func (a *App) NewWebConn(ws *websocket.Conn, session model.Session, t goi18n.Tra } wc := &WebConn{ + App: a, Send: make(chan model.WebSocketMessage, SEND_QUEUE_SIZE), WebSocket: ws, UserId: session.UserId, @@ -103,7 +105,7 @@ func (c *WebConn) ReadPump() { c.WebSocket.SetPongHandler(func(string) error { c.WebSocket.SetReadDeadline(time.Now().Add(PONG_WAIT)) if c.IsAuthenticated() { - go Global().SetStatusAwayIfNeeded(c.UserId, false) + go c.App.SetStatusAwayIfNeeded(c.UserId, false) } return nil }) @@ -120,7 +122,7 @@ func (c *WebConn) ReadPump() { return } else { - Global().Srv.WebSocketRouter.ServeWebSocket(c, &req) + c.App.Srv.WebSocketRouter.ServeWebSocket(c, &req) } } } @@ -231,7 +233,7 @@ func (webCon *WebConn) IsAuthenticated() bool { return false } - session, err := Global().GetSession(webCon.GetSessionToken()) + session, err := webCon.App.GetSession(webCon.GetSessionToken()) if err != nil { l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) webCon.SetSessionToken("") @@ -283,7 +285,7 @@ func (webCon *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { } if webCon.AllChannelMembers == nil { - if result := <-Global().Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil { + if result := <-webCon.App.Srv.Store.Channel().GetAllChannelMembersForUser(webCon.UserId, true); result.Err != nil { l4g.Error("webhub.shouldSendEvent: " + result.Err.Error()) return false } else { @@ -313,7 +315,7 @@ func (webCon *WebConn) IsMemberOfTeam(teamId string) bool { currentSession := webCon.GetSession() if currentSession == nil || len(currentSession.Token) == 0 { - session, err := Global().GetSession(webCon.GetSessionToken()) + session, err := webCon.App.GetSession(webCon.GetSessionToken()) if err != nil { l4g.Error(utils.T("api.websocket.invalid_session.error"), err.Error()) return false diff --git a/store/layered_store.go b/store/layered_store.go index 84b3ab1f5..ac0713f57 100644 --- a/store/layered_store.go +++ b/store/layered_store.go @@ -7,6 +7,7 @@ import ( "context" l4g "github.com/alecthomas/log4go" + "github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/model" ) @@ -26,8 +27,8 @@ type LayeredStore struct { func NewLayeredStore() Store { store := &LayeredStore{ TmpContext: context.TODO(), - DatabaseLayer: NewSqlSupplier(), - LocalCacheLayer: NewLocalCacheSupplier(), + DatabaseLayer: NewSqlSupplier(einterfaces.GetMetricsInterface()), + LocalCacheLayer: NewLocalCacheSupplier(einterfaces.GetMetricsInterface(), einterfaces.GetClusterInterface()), } store.ReactionStore = &LayeredReactionStore{store} diff --git a/store/local_cache_supplier.go b/store/local_cache_supplier.go index a2f03db8e..91aa94768 100644 --- a/store/local_cache_supplier.go +++ b/store/local_cache_supplier.go @@ -21,11 +21,15 @@ const ( type LocalCacheSupplier struct { next LayeredStoreSupplier reactionCache *utils.Cache + metrics einterfaces.MetricsInterface + cluster einterfaces.ClusterInterface } -func NewLocalCacheSupplier() *LocalCacheSupplier { +func NewLocalCacheSupplier(metrics einterfaces.MetricsInterface, cluster einterfaces.ClusterInterface) *LocalCacheSupplier { supplier := &LocalCacheSupplier{ reactionCache: utils.NewLruWithParams(REACTION_CACHE_SIZE, "Reaction", REACTION_CACHE_SEC, model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_REACTIONS), + metrics: metrics, + cluster: cluster, } registerClusterHandlers(supplier) @@ -47,58 +51,56 @@ func (s *LocalCacheSupplier) Next() LayeredStoreSupplier { return s.next } -func doStandardReadCache(ctx context.Context, cache utils.ObjectCache, key string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { - metrics := einterfaces.GetMetricsInterface() - +func (s *LocalCacheSupplier) doStandardReadCache(ctx context.Context, cache utils.ObjectCache, key string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { if hintsContains(hints, LSH_NO_CACHE) { - if metrics != nil { - metrics.IncrementMemCacheMissCounter(cache.Name()) + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter(cache.Name()) } return nil } if cacheItem, ok := cache.Get(key); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter(cache.Name()) + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter(cache.Name()) } result := NewSupplierResult() result.Data = cacheItem return result } - if metrics != nil { - metrics.IncrementMemCacheMissCounter(cache.Name()) + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter(cache.Name()) } return nil } -func doStandardAddToCache(ctx context.Context, cache utils.ObjectCache, key string, result *LayeredStoreSupplierResult, hints ...LayeredStoreHint) { +func (s *LocalCacheSupplier) doStandardAddToCache(ctx context.Context, cache utils.ObjectCache, key string, result *LayeredStoreSupplierResult, hints ...LayeredStoreHint) { if result.Err == nil && result.Data != nil { cache.AddWithDefaultExpires(key, result.Data) } } -func doInvalidateCacheCluster(cache utils.ObjectCache, key string) { +func (s *LocalCacheSupplier) doInvalidateCacheCluster(cache utils.ObjectCache, key string) { cache.Remove(key) - if einterfaces.GetClusterInterface() != nil { + if s.cluster != nil { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: key, } - einterfaces.GetClusterInterface().SendClusterMessage(msg) + s.cluster.SendClusterMessage(msg) } } -func doClearCacheCluster(cache utils.ObjectCache) { +func (s *LocalCacheSupplier) doClearCacheCluster(cache utils.ObjectCache) { cache.Purge() - if einterfaces.GetClusterInterface() != nil { + if s.cluster != nil { msg := &model.ClusterMessage{ Event: cache.GetInvalidateClusterEvent(), SendType: model.CLUSTER_SEND_BEST_EFFORT, Data: CLEAR_CACHE_MESSAGE_DATA, } - einterfaces.GetClusterInterface().SendClusterMessage(msg) + s.cluster.SendClusterMessage(msg) } } diff --git a/store/local_cache_supplier_reactions.go b/store/local_cache_supplier_reactions.go index 102215941..a67cff2e4 100644 --- a/store/local_cache_supplier_reactions.go +++ b/store/local_cache_supplier_reactions.go @@ -18,23 +18,23 @@ func (s *LocalCacheSupplier) handleClusterInvalidateReaction(msg *model.ClusterM } func (s *LocalCacheSupplier) ReactionSave(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { - doInvalidateCacheCluster(s.reactionCache, reaction.PostId) + s.doInvalidateCacheCluster(s.reactionCache, reaction.PostId) return s.Next().ReactionSave(ctx, reaction, hints...) } func (s *LocalCacheSupplier) ReactionDelete(ctx context.Context, reaction *model.Reaction, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { - doInvalidateCacheCluster(s.reactionCache, reaction.PostId) + s.doInvalidateCacheCluster(s.reactionCache, reaction.PostId) return s.Next().ReactionDelete(ctx, reaction, hints...) } func (s *LocalCacheSupplier) ReactionGetForPost(ctx context.Context, postId string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { - if result := doStandardReadCache(ctx, s.reactionCache, postId, hints...); result != nil { + if result := s.doStandardReadCache(ctx, s.reactionCache, postId, hints...); result != nil { return result } result := s.Next().ReactionGetForPost(ctx, postId, hints...) - doStandardAddToCache(ctx, s.reactionCache, postId, result, hints...) + s.doStandardAddToCache(ctx, s.reactionCache, postId, result, hints...) return result } @@ -42,6 +42,6 @@ func (s *LocalCacheSupplier) ReactionGetForPost(ctx context.Context, postId stri func (s *LocalCacheSupplier) ReactionDeleteAllWithEmojiName(ctx context.Context, emojiName string, hints ...LayeredStoreHint) *LayeredStoreSupplierResult { // This could be improved. Right now we just clear the whole // cache because we don't have a way find what post Ids have this emoji name. - doClearCacheCluster(s.reactionCache) + s.doClearCacheCluster(s.reactionCache) return s.Next().ReactionDeleteAllWithEmojiName(ctx, emojiName, hints...) } diff --git a/store/sql_channel_store.go b/store/sql_channel_store.go index c25e3dd3a..aefccbbac 100644 --- a/store/sql_channel_store.go +++ b/store/sql_channel_store.go @@ -36,6 +36,7 @@ const ( type SqlChannelStore struct { SqlStore + metrics einterfaces.MetricsInterface } var channelMemberCountsCache = utils.NewLru(CHANNEL_MEMBERS_COUNTS_CACHE_SIZE) @@ -52,8 +53,11 @@ func ClearChannelCaches() { channelByNameCache.Purge() } -func NewSqlChannelStore(sqlStore SqlStore) ChannelStore { - s := &SqlChannelStore{sqlStore} +func NewSqlChannelStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) ChannelStore { + s := &SqlChannelStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.Channel{}, "Channels").SetKeys(false, "Id") @@ -391,7 +395,6 @@ func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreC go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() var db *gorp.DbMap if master { @@ -402,21 +405,21 @@ func (s SqlChannelStore) get(id string, master bool, allowFromCache bool) StoreC if allowFromCache { if cacheItem, ok := channelCache.Get(id); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Channel") } result.Data = (cacheItem.(*model.Channel)).DeepCopy() storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel") } } @@ -758,18 +761,17 @@ func (s SqlChannelStore) getByName(teamId string, name string, includeDeleted bo channel := model.Channel{} if allowFromCache { - metrics := einterfaces.GetMetricsInterface() if cacheItem, ok := channelByNameCache.Get(teamId + name); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Channel By Name") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Channel By Name") } result.Data = cacheItem.(*model.Channel) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel By Name") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel By Name") } } } @@ -978,10 +980,9 @@ func (us SqlChannelStore) InvalidateAllChannelMembersForUser(userId string) { } func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId string) bool { - metrics := einterfaces.GetMetricsInterface() if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("All Channel Members for User") + if us.metrics != nil { + us.metrics.IncrementMemCacheHitCounter("All Channel Members for User") } ids := cacheItem.(map[string]string) if _, ok := ids[channelId]; ok { @@ -990,8 +991,8 @@ func (us SqlChannelStore) IsUserInChannelUseCache(userId string, channelId strin return false } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("All Channel Members for User") + if us.metrics != nil { + us.metrics.IncrementMemCacheMissCounter("All Channel Members for User") } } @@ -1048,25 +1049,24 @@ func (s SqlChannelStore) GetAllChannelMembersForUser(userId string, allowFromCac go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { if cacheItem, ok := allChannelMembersForUserCache.Get(userId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("All Channel Members for User") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("All Channel Members for User") } result.Data = cacheItem.(map[string]string) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("All Channel Members for User") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("All Channel Members for User") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("All Channel Members for User") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("All Channel Members for User") } } @@ -1110,25 +1110,24 @@ func (s SqlChannelStore) GetAllChannelMembersNotifyPropsForChannel(channelId str go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { if cacheItem, ok := allChannelMembersNotifyPropsForChannelCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("All Channel Members Notify Props for Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("All Channel Members Notify Props for Channel") } result.Data = cacheItem.(map[string]model.StringMap) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("All Channel Members Notify Props for Channel") } } @@ -1164,16 +1163,14 @@ func (us SqlChannelStore) InvalidateMemberCount(channelId string) { } func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 { - metrics := einterfaces.GetMetricsInterface() - if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Channel Member Counts") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Channel Member Counts") } return cacheItem.(int64) } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel Member Counts") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel Member Counts") } } @@ -1186,28 +1183,27 @@ func (s SqlChannelStore) GetMemberCountFromCache(channelId string) int64 { func (s SqlChannelStore) GetMemberCount(channelId string, allowFromCache bool) StoreChannel { storeChannel := make(StoreChannel, 1) - metrics := einterfaces.GetMetricsInterface() go func() { result := StoreResult{} if allowFromCache { if cacheItem, ok := channelMemberCountsCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Channel Member Counts") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Channel Member Counts") } result.Data = cacheItem.(int64) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel Member Counts") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel Member Counts") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Channel Member Counts") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Channel Member Counts") } } diff --git a/store/sql_emoji_store.go b/store/sql_emoji_store.go index 5fd49ab3b..efab82d1f 100644 --- a/store/sql_emoji_store.go +++ b/store/sql_emoji_store.go @@ -20,10 +20,14 @@ var emojiCache *utils.Cache = utils.NewLru(EMOJI_CACHE_SIZE) type SqlEmojiStore struct { SqlStore + metrics einterfaces.MetricsInterface } -func NewSqlEmojiStore(sqlStore SqlStore) EmojiStore { - s := &SqlEmojiStore{sqlStore} +func NewSqlEmojiStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) EmojiStore { + s := &SqlEmojiStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.Emoji{}, "Emoji").SetKeys(false, "Id") @@ -74,25 +78,24 @@ func (es SqlEmojiStore) Get(id string, allowFromCache bool) StoreChannel { go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { if cacheItem, ok := emojiCache.Get(id); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Emoji") + if es.metrics != nil { + es.metrics.IncrementMemCacheHitCounter("Emoji") } result.Data = cacheItem.(*model.Emoji) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Emoji") + if es.metrics != nil { + es.metrics.IncrementMemCacheMissCounter("Emoji") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Emoji") + if es.metrics != nil { + es.metrics.IncrementMemCacheMissCounter("Emoji") } } diff --git a/store/sql_file_info_store.go b/store/sql_file_info_store.go index fc4a9513f..eab83992f 100644 --- a/store/sql_file_info_store.go +++ b/store/sql_file_info_store.go @@ -13,6 +13,7 @@ import ( type SqlFileInfoStore struct { SqlStore + metrics einterfaces.MetricsInterface } const ( @@ -26,8 +27,11 @@ func ClearFileCaches() { fileInfoCache.Purge() } -func NewSqlFileInfoStore(sqlStore SqlStore) FileInfoStore { - s := &SqlFileInfoStore{sqlStore} +func NewSqlFileInfoStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) FileInfoStore { + s := &SqlFileInfoStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.FileInfo{}, "FileInfo").SetKeys(false, "Id") @@ -149,12 +153,10 @@ func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowF go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() - if allowFromCache { if cacheItem, ok := fileInfoCache.Get(postId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("File Info Cache") + if fs.metrics != nil { + fs.metrics.IncrementMemCacheHitCounter("File Info Cache") } result.Data = cacheItem.([]*model.FileInfo) @@ -162,13 +164,13 @@ func (fs SqlFileInfoStore) GetForPost(postId string, readFromMaster bool, allowF close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("File Info Cache") + if fs.metrics != nil { + fs.metrics.IncrementMemCacheMissCounter("File Info Cache") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("File Info Cache") + if fs.metrics != nil { + fs.metrics.IncrementMemCacheMissCounter("File Info Cache") } } diff --git a/store/sql_post_store.go b/store/sql_post_store.go index d823bdc22..2aa862218 100644 --- a/store/sql_post_store.go +++ b/store/sql_post_store.go @@ -18,6 +18,7 @@ import ( type SqlPostStore struct { SqlStore + metrics einterfaces.MetricsInterface } const ( @@ -36,8 +37,11 @@ func ClearPostCaches() { lastPostsCache.Purge() } -func NewSqlPostStore(sqlStore SqlStore) PostStore { - s := &SqlPostStore{sqlStore} +func NewSqlPostStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) PostStore { + s := &SqlPostStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.Post{}, "Posts").SetKeys(false, "Id") @@ -398,25 +402,24 @@ func (s SqlPostStore) GetEtag(channelId string, allowFromCache bool) StoreChanne go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { if cacheItem, ok := lastPostTimeCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Last Post Time") } result.Data = fmt.Sprintf("%v.%v", model.CurrentVersion, cacheItem.(int64)) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Post Time") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Post Time") } } @@ -570,7 +573,6 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if limit > 1000 { result.Err = model.NewLocAppError("SqlPostStore.GetLinearPosts", "store.sql_post.get_posts.app_error", nil, "channelId="+channelId) @@ -581,8 +583,8 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro if allowFromCache && offset == 0 && limit == 60 { if cacheItem, ok := lastPostsCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Last Posts Cache") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Last Posts Cache") } result.Data = cacheItem.(*model.PostList) @@ -590,13 +592,13 @@ func (s SqlPostStore) GetPosts(channelId string, offset int, limit int, allowFro close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Posts Cache") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Posts Cache") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Posts Cache") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Posts Cache") } } @@ -643,14 +645,13 @@ func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { // If the last post in the channel's time is less than or equal to the time we are getting posts since, // we can safely return no posts. if cacheItem, ok := lastPostTimeCache.Get(channelId); ok && cacheItem.(int64) <= time { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Last Post Time") } list := model.NewPostList() result.Data = list @@ -658,13 +659,13 @@ func (s SqlPostStore) GetPostsSince(channelId string, time int64, allowFromCache close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Post Time") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Last Post Time") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Last Post Time") } } diff --git a/store/sql_supplier.go b/store/sql_supplier.go index b6dd77cd1..f839bbed5 100644 --- a/store/sql_supplier.go +++ b/store/sql_supplier.go @@ -19,6 +19,7 @@ import ( "github.com/go-sql-driver/mysql" "github.com/lib/pq" "github.com/mattermost/gorp" + "github.com/mattermost/mattermost-server/einterfaces" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" ) @@ -96,7 +97,7 @@ type SqlSupplier struct { oldStores SqlSupplierOldStores } -func NewSqlSupplier() *SqlSupplier { +func NewSqlSupplier(metrics einterfaces.MetricsInterface) *SqlSupplier { supplier := &SqlSupplier{ rrCounter: 0, srCounter: 0, @@ -105,24 +106,24 @@ func NewSqlSupplier() *SqlSupplier { supplier.initConnection() supplier.oldStores.team = NewSqlTeamStore(supplier) - supplier.oldStores.channel = NewSqlChannelStore(supplier) - supplier.oldStores.post = NewSqlPostStore(supplier) - supplier.oldStores.user = NewSqlUserStore(supplier) + supplier.oldStores.channel = NewSqlChannelStore(supplier, metrics) + supplier.oldStores.post = NewSqlPostStore(supplier, metrics) + supplier.oldStores.user = NewSqlUserStore(supplier, metrics) supplier.oldStores.audit = NewSqlAuditStore(supplier) supplier.oldStores.cluster = NewSqlClusterDiscoveryStore(supplier) supplier.oldStores.compliance = NewSqlComplianceStore(supplier) supplier.oldStores.session = NewSqlSessionStore(supplier) supplier.oldStores.oauth = NewSqlOAuthStore(supplier) supplier.oldStores.system = NewSqlSystemStore(supplier) - supplier.oldStores.webhook = NewSqlWebhookStore(supplier) + supplier.oldStores.webhook = NewSqlWebhookStore(supplier, metrics) supplier.oldStores.command = NewSqlCommandStore(supplier) supplier.oldStores.commandWebhook = NewSqlCommandWebhookStore(supplier) supplier.oldStores.preference = NewSqlPreferenceStore(supplier) supplier.oldStores.license = NewSqlLicenseStore(supplier) supplier.oldStores.token = NewSqlTokenStore(supplier) - supplier.oldStores.emoji = NewSqlEmojiStore(supplier) + supplier.oldStores.emoji = NewSqlEmojiStore(supplier, metrics) supplier.oldStores.status = NewSqlStatusStore(supplier) - supplier.oldStores.fileInfo = NewSqlFileInfoStore(supplier) + supplier.oldStores.fileInfo = NewSqlFileInfoStore(supplier, metrics) supplier.oldStores.job = NewSqlJobStore(supplier) supplier.oldStores.userAccessToken = NewSqlUserAccessTokenStore(supplier) diff --git a/store/sql_user_store.go b/store/sql_user_store.go index a162ab4b6..6d8b116b3 100644 --- a/store/sql_user_store.go +++ b/store/sql_user_store.go @@ -34,6 +34,7 @@ const ( type SqlUserStore struct { SqlStore + metrics einterfaces.MetricsInterface } var profilesInChannelCache *utils.Cache = utils.NewLru(PROFILES_IN_CHANNEL_CACHE_SIZE) @@ -48,8 +49,11 @@ func (us SqlUserStore) InvalidatProfileCacheForUser(userId string) { profileByIdsCache.Remove(userId) } -func NewSqlUserStore(sqlStore SqlStore) UserStore { - us := &SqlUserStore{sqlStore} +func NewSqlUserStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) UserStore { + us := &SqlUserStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.User{}, "Users").SetKeys(false, "Id") @@ -572,25 +576,24 @@ func (us SqlUserStore) GetAllProfilesInChannel(channelId string, allowFromCache go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() if allowFromCache { if cacheItem, ok := profilesInChannelCache.Get(channelId); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Profiles in Channel") + if us.metrics != nil { + us.metrics.IncrementMemCacheHitCounter("Profiles in Channel") } result.Data = cacheItem.(map[string]*model.User) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Profiles in Channel") + if us.metrics != nil { + us.metrics.IncrementMemCacheMissCounter("Profiles in Channel") } } } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Profiles in Channel") + if us.metrics != nil { + us.metrics.IncrementMemCacheMissCounter("Profiles in Channel") } } @@ -838,7 +841,6 @@ func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) St go func() { result := StoreResult{} - metrics := einterfaces.GetMetricsInterface() users := []*model.User{} props := make(map[string]interface{}) @@ -855,14 +857,14 @@ func (us SqlUserStore) GetProfileByIds(userIds []string, allowFromCache bool) St remainingUserIds = append(remainingUserIds, userId) } } - if metrics != nil { - metrics.AddMemCacheHitCounter("Profile By Ids", float64(len(users))) - metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) + if us.metrics != nil { + us.metrics.AddMemCacheHitCounter("Profile By Ids", float64(len(users))) + us.metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) } } else { remainingUserIds = userIds - if metrics != nil { - metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) + if us.metrics != nil { + us.metrics.AddMemCacheMissCounter("Profile By Ids", float64(len(remainingUserIds))) } } diff --git a/store/sql_webhook_store.go b/store/sql_webhook_store.go index 5cc2df43c..a43e78fc4 100644 --- a/store/sql_webhook_store.go +++ b/store/sql_webhook_store.go @@ -15,6 +15,7 @@ import ( type SqlWebhookStore struct { SqlStore + metrics einterfaces.MetricsInterface } const ( @@ -28,8 +29,11 @@ func ClearWebhookCaches() { webhookCache.Purge() } -func NewSqlWebhookStore(sqlStore SqlStore) WebhookStore { - s := &SqlWebhookStore{sqlStore} +func NewSqlWebhookStore(sqlStore SqlStore, metrics einterfaces.MetricsInterface) WebhookStore { + s := &SqlWebhookStore{ + SqlStore: sqlStore, + metrics: metrics, + } for _, db := range sqlStore.GetAllConns() { table := db.AddTableWithName(model.IncomingWebhook{}, "IncomingWebhooks").SetKeys(false, "Id") @@ -137,18 +141,17 @@ func (s SqlWebhookStore) GetIncoming(id string, allowFromCache bool) StoreChanne result := StoreResult{} if allowFromCache { - metrics := einterfaces.GetMetricsInterface() if cacheItem, ok := webhookCache.Get(id); ok { - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Webhook") + if s.metrics != nil { + s.metrics.IncrementMemCacheHitCounter("Webhook") } result.Data = cacheItem.(*model.IncomingWebhook) storeChannel <- result close(storeChannel) return } else { - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Webhook") + if s.metrics != nil { + s.metrics.IncrementMemCacheMissCounter("Webhook") } } } -- cgit v1.2.3-1-g7c22