diff --git a/Makefile b/Makefile index fd814de1cf..2d830a9ba3 100644 --- a/Makefile +++ b/Makefile @@ -392,10 +392,14 @@ email-mocks: ## Creates mocks for misc interfaces. $(GO) install github.com/vektra/mockery/v2/...@v2.10.4 $(GOBIN)/mockery --dir app/email --name ServiceInterface --output app/email/mocks --note 'Regenerate this file using `make email-mocks`.' +platform-mocks: ## Creates mocks for platform interfaces. + $(GO) install github.com/vektra/mockery/v2/...@v2.14.0 + $(GOBIN)/mockery --dir app/platform --name SuiteIFace --output app/platform/mocks --note 'Regenerate this file using `make platform-mocks`.' + pluginapi: ## Generates api and hooks glue code for plugins $(GO) generate $(GOFLAGS) ./plugin -mocks: store-mocks telemetry-mocks filestore-mocks ldap-mocks plugin-mocks einterfaces-mocks searchengine-mocks sharedchannel-mocks misc-mocks email-mocks +mocks: store-mocks telemetry-mocks filestore-mocks ldap-mocks plugin-mocks einterfaces-mocks searchengine-mocks sharedchannel-mocks misc-mocks email-mocks platform-mocks layers: app-layers store-layers pluginapi diff --git a/api4/apitestlib.go b/api4/apitestlib.go index ef7e78b685..9b5e53abfc 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -34,7 +34,6 @@ import ( "github.com/mattermost/mattermost-server/v6/services/searchengine" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" - "github.com/mattermost/mattermost-server/v6/store/localcachelayer" "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" "github.com/mattermost/mattermost-server/v6/testlib" "github.com/mattermost/mattermost-server/v6/web" @@ -115,13 +114,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent options = append(options, app.ConfigStore(configStore)) if includeCache { // Adds the cache layer to the test store - options = append(options, app.StoreOverride(func(s *app.Server) store.Store { - lcl, err2 := localcachelayer.NewLocalCacheLayer(dbStore, s.GetMetrics(), s.Cluster, s.CacheProvider) - if err2 != nil { - panic(err2) - } - return lcl - })) + options = append(options, app.StoreOverrideWithCache(dbStore)) } else { options = append(options, app.StoreOverride(dbStore)) } @@ -150,8 +143,8 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent } th.Context.SetLogger(testLogger) - if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && searchEngine != nil { - searchEngine.BleveEngine = s.SearchEngine.BleveEngine + if s.Platform().SearchEngine != nil && s.Platform().SearchEngine.BleveEngine != nil && searchEngine != nil { + searchEngine.BleveEngine = s.Platform().SearchEngine.BleveEngine } if searchEngine != nil { @@ -303,7 +296,7 @@ func SetupConfigWithStoreMock(tb testing.TB, updateConfig func(cfg *model.Config emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) emptyMockStore.On("Status").Return(&statusMock) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -317,7 +310,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) emptyMockStore.On("Status").Return(&statusMock) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -331,7 +324,7 @@ func SetupEnterpriseWithStoreMock(tb testing.TB, options ...app.Option) *TestHel emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) emptyMockStore.On("Status").Return(&statusMock) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -587,7 +580,7 @@ func (th *TestHelper) CreateUserWithClient(client *model.Client4) *model.User { } ruser.Password = "Pa$$word11" - _, err = th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err = th.App.Srv().Store().User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return nil } @@ -773,7 +766,7 @@ func (th *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel } func (th *TestHelper) CreateMessagePostNoClient(channel *model.Channel, message string, createAtTime int64) *model.Post { - post, err := th.App.Srv().Store.Post().Save(&model.Post{ + post, err := th.App.Srv().Store().Post().Save(&model.Post{ UserId: th.BasicUser.Id, ChannelId: channel.Id, Message: message, @@ -1157,9 +1150,9 @@ func (th *TestHelper) cleanupTestFile(info *model.FileInfo) error { } func (th *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Channel) { - if cm, err := th.App.Srv().Store.Channel().GetMember(context.Background(), channel.Id, user.Id); err == nil { + if cm, err := th.App.Srv().Store().Channel().GetMember(context.Background(), channel.Id, user.Id); err == nil { cm.SchemeAdmin = true - if _, err = th.App.Srv().Store.Channel().UpdateMember(cm); err != nil { + if _, err = th.App.Srv().Store().Channel().UpdateMember(cm); err != nil { panic(err) } } else { @@ -1168,9 +1161,9 @@ func (th *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Chan } func (th *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) { - if tm, err := th.App.Srv().Store.Team().GetMember(context.Background(), team.Id, user.Id); err == nil { + if tm, err := th.App.Srv().Store().Team().GetMember(context.Background(), team.Id, user.Id); err == nil { tm.SchemeAdmin = true - if _, err = th.App.Srv().Store.Team().UpdateMember(tm); err != nil { + if _, err = th.App.Srv().Store().Team().UpdateMember(tm); err != nil { panic(err) } } else { @@ -1179,9 +1172,9 @@ func (th *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) } func (th *TestHelper) UpdateUserToNonTeamAdmin(user *model.User, team *model.Team) { - if tm, err := th.App.Srv().Store.Team().GetMember(context.Background(), team.Id, user.Id); err == nil { + if tm, err := th.App.Srv().Store().Team().GetMember(context.Background(), team.Id, user.Id); err == nil { tm.SchemeAdmin = false - if _, err = th.App.Srv().Store.Team().UpdateMember(tm); err != nil { + if _, err = th.App.Srv().Store().Team().UpdateMember(tm); err != nil { panic(err) } } else { diff --git a/api4/channel_test.go b/api4/channel_test.go index 7604906e3f..16e432bf0d 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -1168,7 +1168,7 @@ func TestGetAllChannels(t *testing.T) { require.NoError(t, err) CheckOKStatus(t, resp) policyChannel := (sysManagerChannels)[0] - policy, err := th.App.Srv().Store.RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ + policy, err := th.App.Srv().Store().RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ RetentionPolicy: model.RetentionPolicy{ DisplayName: "Policy 1", PostDurationDays: model.NewInt64(30), @@ -1661,7 +1661,7 @@ func TestSearchAllChannels(t *testing.T) { require.NoError(t, err) CheckOKStatus(t, resp) policyChannel := sysManagerChannels[0] - policy, savePolicyErr := th.App.Srv().Store.RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ + policy, savePolicyErr := th.App.Srv().Store().RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ RetentionPolicy: model.RetentionPolicy{ DisplayName: "Policy 1", PostDurationDays: model.NewInt64(30), @@ -1923,7 +1923,7 @@ func TestDeleteChannel2(t *testing.T) { // successful delete by channel admin th.MakeUserChannelAdmin(user, publicChannel6) th.MakeUserChannelAdmin(user, privateChannel7) - th.App.Srv().Store.Channel().ClearCaches() + th.App.Srv().Store().Channel().ClearCaches() _, err = client.DeleteChannel(publicChannel6.Id) require.NoError(t, err) @@ -4139,17 +4139,17 @@ func TestGetChannelModerations(t *testing.T) { mockSchemeStore := mocks.SchemeStore{} mockSchemeStore.On("Get", mock.Anything).Return(scheme, nil) mockStore.On("Scheme").Return(&mockSchemeStore) - mockStore.On("Team").Return(th.App.Srv().Store.Team()) - mockStore.On("Channel").Return(th.App.Srv().Store.Channel()) - mockStore.On("User").Return(th.App.Srv().Store.User()) - mockStore.On("Post").Return(th.App.Srv().Store.Post()) - mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo()) - mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook()) - mockStore.On("System").Return(th.App.Srv().Store.System()) - mockStore.On("License").Return(th.App.Srv().Store.License()) - mockStore.On("Role").Return(th.App.Srv().Store.Role()) + mockStore.On("Team").Return(th.App.Srv().Store().Team()) + mockStore.On("Channel").Return(th.App.Srv().Store().Channel()) + mockStore.On("User").Return(th.App.Srv().Store().User()) + mockStore.On("Post").Return(th.App.Srv().Store().Post()) + mockStore.On("FileInfo").Return(th.App.Srv().Store().FileInfo()) + mockStore.On("Webhook").Return(th.App.Srv().Store().Webhook()) + mockStore.On("System").Return(th.App.Srv().Store().System()) + mockStore.On("License").Return(th.App.Srv().Store().License()) + mockStore.On("Role").Return(th.App.Srv().Store().Role()) mockStore.On("Close").Return(nil) - th.App.Srv().Store = &mockStore + th.App.Srv().SetStore(&mockStore) team.SchemeId = &scheme.Id _, appErr := th.App.UpdateTeamScheme(team) @@ -4283,17 +4283,17 @@ func TestPatchChannelModerations(t *testing.T) { mockSchemeStore.On("Save", mock.Anything).Return(scheme, nil) mockSchemeStore.On("Delete", mock.Anything).Return(scheme, nil) mockStore.On("Scheme").Return(&mockSchemeStore) - mockStore.On("Team").Return(th.App.Srv().Store.Team()) - mockStore.On("Channel").Return(th.App.Srv().Store.Channel()) - mockStore.On("User").Return(th.App.Srv().Store.User()) - mockStore.On("Post").Return(th.App.Srv().Store.Post()) - mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo()) - mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook()) - mockStore.On("System").Return(th.App.Srv().Store.System()) - mockStore.On("License").Return(th.App.Srv().Store.License()) - mockStore.On("Role").Return(th.App.Srv().Store.Role()) + mockStore.On("Team").Return(th.App.Srv().Store().Team()) + mockStore.On("Channel").Return(th.App.Srv().Store().Channel()) + mockStore.On("User").Return(th.App.Srv().Store().User()) + mockStore.On("Post").Return(th.App.Srv().Store().Post()) + mockStore.On("FileInfo").Return(th.App.Srv().Store().FileInfo()) + mockStore.On("Webhook").Return(th.App.Srv().Store().Webhook()) + mockStore.On("System").Return(th.App.Srv().Store().System()) + mockStore.On("License").Return(th.App.Srv().Store().License()) + mockStore.On("Role").Return(th.App.Srv().Store().Role()) mockStore.On("Close").Return(nil) - th.App.Srv().Store = &mockStore + th.App.Srv().SetStore(&mockStore) team.SchemeId = &scheme.Id _, appErr := th.App.UpdateTeamScheme(team) @@ -4548,7 +4548,7 @@ func TestRootMentionsCount(t *testing.T) { channel := th.BasicChannel // initially, MentionCountRoot is 0 in the database - channelMember, err := th.App.Srv().Store.Channel().GetMember(context.Background(), channel.Id, user.Id) + channelMember, err := th.App.Srv().Store().Channel().GetMember(context.Background(), channel.Id, user.Id) require.NoError(t, err) require.Equal(t, int64(0), channelMember.MentionCountRoot) require.Equal(t, int64(0), channelMember.MentionCount) @@ -4569,7 +4569,7 @@ func TestRootMentionsCount(t *testing.T) { // regular count stays the same require.Equal(t, int64(2), channelUnread.MentionCount) // validate that DB is updated - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channel.Id, user.Id) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channel.Id, user.Id) require.NoError(t, err) require.EqualValues(t, int64(1), channelMember.MentionCountRoot) diff --git a/api4/cloud_test.go b/api4/cloud_test.go index 16da33ae88..999f1077e4 100644 --- a/api4/cloud_test.go +++ b/api4/cloud_test.go @@ -297,6 +297,7 @@ func Test_requestTrial(t *testing.T) { require.Equal(t, http.StatusOK, r.StatusCode, "Status OK") }) } + func Test_validateBusinessEmail(t *testing.T) { t.Run("Returns forbidden for non admin executors", func(t *testing.T) { th := Setup(t).InitBasic() diff --git a/api4/command_help_test.go b/api4/command_help_test.go index 7fab1d5758..ca255cc6a5 100644 --- a/api4/command_help_test.go +++ b/api4/command_help_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v6/model" ) @@ -24,12 +25,14 @@ func TestHelpCommand(t *testing.T) { }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" }) - rs1, _, _ := client.ExecuteCommand(channel.Id, "/help ") + rs1, _, err := client.ExecuteCommand(channel.Id, "/help ") + require.NoError(t, err) assert.Contains(t, rs1.Text, model.SupportSettingsDefaultHelpLink, "failed to default help link") th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html" }) - rs2, _, _ := client.ExecuteCommand(channel.Id, "/help ") + rs2, _, err := client.ExecuteCommand(channel.Id, "/help ") + require.NoError(t, err) assert.Contains(t, rs2.Text, "https://docs.mattermost.com/guides/user.html", "failed to help link") } diff --git a/api4/config.go b/api4/config.go index 2b6779c31f..91e62862a4 100644 --- a/api4/config.go +++ b/api4/config.go @@ -239,9 +239,9 @@ func getClientConfig(c *Context, w http.ResponseWriter, r *http.Request) { var config map[string]string if c.AppContext.Session().UserId == "" { - config = c.App.LimitedClientConfigWithComputed() + config = c.App.Srv().Platform().LimitedClientConfigWithComputed() } else { - config = c.App.ClientConfigWithComputed() + config = c.App.Srv().Platform().ClientConfigWithComputed() } w.Write([]byte(model.MapToJSON(config))) diff --git a/api4/config_test.go b/api4/config_test.go index 52de0491c8..2af4fe7bac 100644 --- a/api4/config_test.go +++ b/api4/config_test.go @@ -542,12 +542,7 @@ func TestUpdateConfigDiffInAuditRecord(t *testing.T) { defer os.Unsetenv("MM_EXPERIMENTALAUDITSETTINGS_FILEENABLED") defer os.Unsetenv("MM_EXPERIMENTALAUDITSETTINGS_FILENAME") - options := []app.Option{ - func(s *app.Server) error { - s.SetLicense(model.NewTestLicense("advanced_logging")) - return nil - }, - } + options := []app.Option{app.WithLicense(model.NewTestLicense("advanced_logging"))} th := SetupWithServerOptions(t, options) defer th.TearDown() diff --git a/api4/cors_test.go b/api4/cors_test.go index 214cec9f04..7836f27641 100644 --- a/api4/cors_test.go +++ b/api4/cors_test.go @@ -129,7 +129,7 @@ func TestCORSRequestHandling(t *testing.T) { defer th.TearDown() licenseStore := mocks.LicenseStore{} licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil) - th.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore) + th.App.Srv().Store().(*mocks.Store).On("License").Return(&licenseStore) port := th.App.Srv().ListenAddr.Port host := fmt.Sprintf("http://localhost:%v", port) diff --git a/api4/file_test.go b/api4/file_test.go index 49fcfd9b79..0184f972b7 100644 --- a/api4/file_test.go +++ b/api4/file_test.go @@ -663,7 +663,7 @@ func TestUploadFiles(t *testing.T) { fmt.Sprintf("Wrong clientId returned, expected %v, got %v", tc.clientIds[i], fileResp.ClientIds[i])) } - dbInfo, err := th.App.Srv().Store.FileInfo().Get(ri.Id) + dbInfo, err := th.App.Srv().Store().FileInfo().Get(ri.Id) require.NoError(t, err) assert.Equal(t, dbInfo.Id, ri.Id, "File id from response should match one stored in database") assert.Equal(t, dbInfo.CreatorId, tc.expectedCreatorId, "F ile should be assigned to user") @@ -912,7 +912,7 @@ func TestGetFileLink(t *testing.T) { CheckBadRequestStatus(t, resp) // Hacky way to assign file to a post (usually would be done by CreatePost call) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = false }) @@ -948,7 +948,7 @@ func TestGetFileLink(t *testing.T) { _, _, err = th.SystemAdminClient.GetFileLink(fileId) require.NoError(t, err) - fileInfo, err := th.App.Srv().Store.FileInfo().Get(fileId) + fileInfo, err := th.App.Srv().Store().FileInfo().Get(fileId) require.NoError(t, err) th.cleanupTestFile(fileInfo) } @@ -1070,10 +1070,10 @@ func TestGetPublicFile(t *testing.T) { fileId := fileResp.FileInfos[0].Id // Hacky way to assign file to a post (usually would be done by CreatePost call) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) - info, err := th.App.Srv().Store.FileInfo().Get(fileId) + info, err := th.App.Srv().Store().FileInfo().Get(fileId) require.NoError(t, err) link := th.App.GeneratePublicLink(client.URL, info) @@ -1103,7 +1103,7 @@ func TestGetPublicFile(t *testing.T) { require.NoError(t, err) require.Equal(t, http.StatusBadRequest, resp.StatusCode, "should've failed to get image with public link after salt changed") - fileInfo, err := th.App.Srv().Store.FileInfo().Get(fileId) + fileInfo, err := th.App.Srv().Store().FileInfo().Get(fileId) require.NoError(t, err) require.NoError(t, th.cleanupTestFile(fileInfo)) @@ -1135,25 +1135,25 @@ func TestSearchFiles(t *testing.T) { filename := "search for fileInfo1" fileInfo1, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo1.Id, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileInfo1.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "search for fileInfo2" fileInfo2, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo2.Id, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileInfo2.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "tagged search for fileInfo3" fileInfo3, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo3.Id, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileInfo3.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) filename = "tagged for fileInfo4" fileInfo4, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename) require.Nil(t, appErr) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo4.Id, th.BasicPost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileInfo4.Id, th.BasicPost.Id, th.BasicUser.Id) require.NoError(t, err) archivedChannel := th.CreatePublicChannel() @@ -1162,7 +1162,7 @@ func TestSearchFiles(t *testing.T) { post := &model.Post{ChannelId: archivedChannel.Id, Message: model.NewId() + "a"} rpost, _, err := client.CreatePost(post) require.NoError(t, err) - err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo5.Id, rpost.Id, th.BasicUser.Id) + err = th.App.Srv().Store().FileInfo().AttachToPost(fileInfo5.Id, rpost.Id, th.BasicUser.Id) require.NoError(t, err) th.Client.DeleteChannel(archivedChannel.Id) diff --git a/api4/group.go b/api4/group.go index 4be5bc4201..f8b65aa5bb 100644 --- a/api4/group.go +++ b/api4/group.go @@ -938,7 +938,7 @@ func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { err error ) if c.Params.IncludeTotalCount { - totalCount, cerr := c.App.Srv().Store.Group().GroupCount() + totalCount, cerr := c.App.Srv().Store().Group().GroupCount() if cerr != nil { c.Err = model.NewAppError("Api4.getGroups", "api.custom_groups.count_err", nil, "", http.StatusInternalServerError).Wrap(cerr) return diff --git a/api4/insights_test.go b/api4/insights_test.go index 1eca69c72c..089bd26842 100644 --- a/api4/insights_test.go +++ b/api4/insights_test.go @@ -153,7 +153,7 @@ func TestGetTopReactionsForTeamSince(t *testing.T) { } for _, userReaction := range userReactions { - _, err := th.App.Srv().Store.Reaction().Save(userReaction) + _, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) } @@ -197,7 +197,7 @@ func TestGetTopReactionsForTeamSince(t *testing.T) { EmojiName: "confused", } - _, err = th.App.Srv().Store.Reaction().Save(reaction) + _, err = th.App.Srv().Store().Reaction().Save(reaction) require.NoError(t, err) } @@ -377,7 +377,7 @@ func TestGetTopReactionsForUserSince(t *testing.T) { } for _, userReaction := range userReactions { - _, err := th.App.Srv().Store.Reaction().Save(userReaction) + _, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) } @@ -806,7 +806,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { _, appErr = th.App.DeletePost(th.Context, replyPostUser2InPrivate.Id, th.BasicUser2.Id) require.Nil(t, appErr) // unfollow thread - _, err := th.App.Srv().Store.Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ + _, err := th.App.Srv().Store().Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ Following: false, UpdateFollowing: true, }) diff --git a/api4/job_test.go b/api4/job_test.go index 103764ae4f..e80b1e2d14 100644 --- a/api4/job_test.go +++ b/api4/job_test.go @@ -35,7 +35,7 @@ func TestCreateJob(t *testing.T) { t.Run("valid job as user with permissions", func(t *testing.T) { received, _, err := th.SystemAdminClient.CreateJob(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(received.Id) + defer th.App.Srv().Store().Job().Delete(received.Id) }) t.Run("invalid job type as user without permissions", func(t *testing.T) { @@ -54,10 +54,10 @@ func TestGetJob(t *testing.T) { Status: model.JobStatusPending, Type: model.JobTypeMessageExport, } - _, err := th.App.Srv().Store.Job().Save(job) + _, err := th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) received, _, err := th.SystemAdminClient.GetJob(job.Id) require.NoError(t, err) @@ -104,9 +104,9 @@ func TestGetJobs(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv().Store.Job().Save(job) + _, err := th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) } received, _, err := th.SystemAdminClient.GetJobs(0, 2) @@ -157,9 +157,9 @@ func TestGetJobsByType(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv().Store.Job().Save(job) + _, err := th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) } received, _, err := th.SystemAdminClient.GetJobsByType(jobType, 0, 2) @@ -226,9 +226,9 @@ func TestDownloadJob(t *testing.T) { // Here we have a job that exist in our database but the results do not exist therefore when we try to download the results // as a system admin, we should get a not found status. - _, err = th.App.Srv().Store.Job().Save(job) + _, err = th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) filePath := "./data/export/" + job.Id + "/testdat.txt" mkdirAllErr := os.MkdirAll(filepath.Dir(filePath), 0770) @@ -250,7 +250,7 @@ func TestDownloadJob(t *testing.T) { CheckBadRequestStatus(t, resp) job.Data["is_downloadable"] = "true" - updateStatus, err := th.App.Srv().Store.Job().UpdateOptimistically(job, model.JobStatusSuccess) + updateStatus, err := th.App.Srv().Store().Job().UpdateOptimistically(job, model.JobStatusSuccess) require.True(t, updateStatus) require.NoError(t, err) @@ -278,9 +278,9 @@ func TestDownloadJob(t *testing.T) { }, Status: model.JobStatusSuccess, } - _, err = th.App.Srv().Store.Job().Save(job) + _, err = th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) // System admin shouldn't be able to download since the job type is not message export _, resp, err = th.SystemAdminClient.DownloadJob(job.Id) @@ -312,9 +312,9 @@ func TestCancelJob(t *testing.T) { } for _, job := range jobs { - _, err := th.App.Srv().Store.Job().Save(job) + _, err := th.App.Srv().Store().Job().Save(job) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(job.Id) + defer th.App.Srv().Store().Job().Delete(job.Id) } resp, err := th.Client.CancelJob(jobs[0].Id) diff --git a/api4/license.go b/api4/license.go index ee7a79fa54..e98f859910 100644 --- a/api4/license.go +++ b/api4/license.go @@ -106,7 +106,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { // skip the restrictions if license is a sanctioned trial if !license.IsSanctionedTrial() && license.IsTrialLicense() { - canStartTrialLicense, err := c.App.Srv().LicenseManager.CanStartTrial() + canStartTrialLicense, err := c.App.Srv().Platform().LicenseManager().CanStartTrial() if err != nil { c.Err = model.NewAppError("addLicense", "api.license.add_license.open.app_error", nil, "", http.StatusInternalServerError) return @@ -180,12 +180,12 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.Srv().LicenseManager == nil { + if c.App.Srv().Platform().LicenseManager() == nil { c.Err = model.NewAppError("requestTrialLicense", "api.license.upgrade_needed.app_error", nil, "", http.StatusForbidden) return } - canStartTrialLicense, err := c.App.Srv().LicenseManager.CanStartTrial() + canStartTrialLicense, err := c.App.Srv().Platform().LicenseManager().CanStartTrial() if err != nil { c.Err = model.NewAppError("requestTrialLicense", "api.license.request-trial.can-start-trial.error", nil, err.Error(), http.StatusInternalServerError) return @@ -264,12 +264,12 @@ func requestRenewalLink(c *Context, w http.ResponseWriter, r *http.Request) { } func getPrevTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.Srv().LicenseManager == nil { + if c.App.Srv().Platform().LicenseManager() == nil { c.Err = model.NewAppError("getPrevTrialLicense", "api.license.upgrade_needed.app_error", nil, "", http.StatusForbidden) return } - license, err := c.App.Srv().LicenseManager.GetPrevTrial() + license, err := c.App.Srv().Platform().LicenseManager().GetPrevTrial() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/api4/license_test.go b/api4/license_test.go index af3b6fb8df..05acd6378c 100644 --- a/api4/license_test.go +++ b/api4/license_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/mattermost/mattermost-server/v6/app" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/einterfaces/mocks" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/utils" @@ -117,7 +118,7 @@ func TestUploadLicenseFile(t *testing.T) { licenseManagerMock := &mocks.LicenseInterface{} licenseManagerMock.On("CanStartTrial").Return(false, nil).Once() - th.App.Srv().LicenseManager = licenseManagerMock + th.App.Srv().Platform().SetLicenseManager(licenseManagerMock) resp, err := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa")) CheckErrorID(t, err, "api.license.request-trial.can-start-trial.not-allowed") @@ -155,7 +156,7 @@ func TestUploadLicenseFile(t *testing.T) { licenseManagerMock := &mocks.LicenseInterface{} licenseManagerMock.On("CanStartTrial").Return(false, nil).Once() - th.App.Srv().LicenseManager = licenseManagerMock + th.App.Srv().Platform().SetLicenseManager(licenseManagerMock) resp, err := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa")) require.NoError(t, err) @@ -202,7 +203,7 @@ func TestRequestTrialLicense(t *testing.T) { licenseManagerMock := &mocks.LicenseInterface{} licenseManagerMock.On("CanStartTrial").Return(true, nil) - th.App.Srv().LicenseManager = licenseManagerMock + th.App.Srv().Platform().SetLicenseManager(licenseManagerMock) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" }) @@ -235,7 +236,7 @@ func TestRequestTrialLicense(t *testing.T) { utils.LicenseValidator = &mockLicenseValidator licenseManagerMock := &mocks.LicenseInterface{} licenseManagerMock.On("CanStartTrial").Return(true, nil).Once() - th.App.Srv().LicenseManager = licenseManagerMock + th.App.Srv().Platform().SetLicenseManager(licenseManagerMock) defer func(requestTrialURL string) { app.RequestTrialURL = requestTrialURL @@ -265,19 +266,19 @@ func TestRequestTrialLicense(t *testing.T) { utils.LicenseValidator = &mockLicenseValidator licenseManagerMock := &mocks.LicenseInterface{} licenseManagerMock.On("CanStartTrial").Return(true, nil).Once() - th.App.Srv().LicenseManager = licenseManagerMock + th.App.Srv().Platform().SetLicenseManager(licenseManagerMock) defer func(requestTrialURL string) { - app.RequestTrialURL = requestTrialURL - }(app.RequestTrialURL) - app.RequestTrialURL = testServer.URL + platform.RequestTrialURL = requestTrialURL + }(platform.RequestTrialURL) + platform.RequestTrialURL = testServer.URL resp, err := th.SystemAdminClient.RequestTrialLicense(nUsers) require.Error(t, err) require.Equal(t, resp.StatusCode, 451) }) - th.App.Srv().LicenseManager = nil + th.App.Srv().Platform().SetLicenseManager(nil) t.Run("trial license should fail if LicenseManager is nil", func(t *testing.T) { resp, err := th.SystemAdminClient.RequestTrialLicense(1) CheckErrorID(t, err, "api.license.upgrade_needed.app_error") diff --git a/api4/plugin.go b/api4/plugin.go index eb5fd11652..be5b298d02 100644 --- a/api4/plugin.go +++ b/api4/plugin.go @@ -422,7 +422,7 @@ func setFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h Value: "true", } - if err := c.App.Srv().Store.System().SaveOrUpdate(&firstAdminVisitMarketplaceObj); err != nil { + if err := c.App.Srv().Store().System().SaveOrUpdate(&firstAdminVisitMarketplaceObj); err != nil { c.Err = model.NewAppError("setFirstAdminVisitMarketplaceStatus", "api.error_set_first_admin_visit_marketplace_status", nil, err.Error(), http.StatusInternalServerError) return } @@ -445,7 +445,7 @@ func getFirstAdminVisitMarketplaceStatus(c *Context, w http.ResponseWriter, r *h return } - firstAdminVisitMarketplaceObj, err := c.App.Srv().Store.System().GetByName(model.SystemFirstAdminVisitMarketplace) + firstAdminVisitMarketplaceObj, err := c.App.Srv().Store().System().GetByName(model.SystemFirstAdminVisitMarketplace) if err != nil { var nfErr *store.ErrNotFound switch { diff --git a/api4/plugin_test.go b/api4/plugin_test.go index da5f145412..1967f9a617 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -287,7 +287,7 @@ func TestNotifyClusterPluginEvent(t *testing.T) { defer th.TearDown() testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true diff --git a/api4/post_test.go b/api4/post_test.go index b1b4754e6e..8eeffa58a8 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -1480,18 +1480,18 @@ func TestGetFlaggedPostsForUser(t *testing.T) { mockPostStore := mocks.PostStore{} mockPostStore.On("GetFlaggedPosts", mock.AnythingOfType("string"), mock.AnythingOfType("int"), mock.AnythingOfType("int")).Return(nil, errors.New("some-error")) mockPostStore.On("ClearCaches").Return() - mockStore.On("Team").Return(th.App.Srv().Store.Team()) - mockStore.On("Channel").Return(th.App.Srv().Store.Channel()) - mockStore.On("User").Return(th.App.Srv().Store.User()) - mockStore.On("Scheme").Return(th.App.Srv().Store.Scheme()) + mockStore.On("Team").Return(th.App.Srv().Store().Team()) + mockStore.On("Channel").Return(th.App.Srv().Store().Channel()) + mockStore.On("User").Return(th.App.Srv().Store().User()) + mockStore.On("Scheme").Return(th.App.Srv().Store().Scheme()) mockStore.On("Post").Return(&mockPostStore) - mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo()) - mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook()) - mockStore.On("System").Return(th.App.Srv().Store.System()) - mockStore.On("License").Return(th.App.Srv().Store.License()) - mockStore.On("Role").Return(th.App.Srv().Store.Role()) + mockStore.On("FileInfo").Return(th.App.Srv().Store().FileInfo()) + mockStore.On("Webhook").Return(th.App.Srv().Store().Webhook()) + mockStore.On("System").Return(th.App.Srv().Store().System()) + mockStore.On("License").Return(th.App.Srv().Store().License()) + mockStore.On("Role").Return(th.App.Srv().Store().Role()) mockStore.On("Close").Return(nil) - th.App.Srv().Store = &mockStore + th.App.Srv().SetStore(&mockStore) _, resp, err = th.SystemAdminClient.GetFlaggedPostsForUser(user.Id, 0, 10) require.Error(t, err) @@ -1898,12 +1898,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { // Set channel member's last viewed to 0. // All returned posts are latest posts as if all previous posts were already read by the user. - channelMember, err := th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err := th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = 0 - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 20, 20, false) require.NoError(t, err) @@ -1919,12 +1919,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { postIdNames[systemPost1.Id] = "system post 1" // Set channel member's last viewed before post1. - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = post1.CreateAt - 1 - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 3, 3, false) require.NoError(t, err) @@ -1943,12 +1943,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed before post6. - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = post6.CreateAt - 1 - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 3, 3, false) require.NoError(t, err) @@ -1970,12 +1970,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed before post10. - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = post10.CreateAt - 1 - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 3, 3, false) require.NoError(t, err) @@ -1995,12 +1995,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { }, posts) // Set channel member's last viewed equal to post10. - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = post10.CreateAt - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 3, 3, false) require.NoError(t, err) @@ -2034,12 +2034,12 @@ func TestGetPostsForChannelAroundLastUnread(t *testing.T) { postIdNames[post12.Id] = "post12 (reply to post4)" postIdNames[post13.Id] = "post13" - channelMember, err = th.App.Srv().Store.Channel().GetMember(context.Background(), channelId, userId) + channelMember, err = th.App.Srv().Store().Channel().GetMember(context.Background(), channelId, userId) require.NoError(t, err) channelMember.LastViewedAt = post12.CreateAt - 1 - _, err = th.App.Srv().Store.Channel().UpdateMember(channelMember) + _, err = th.App.Srv().Store().Channel().UpdateMember(channelMember) require.NoError(t, err) - th.App.Srv().Store.Post().InvalidateLastPostTimeCache(channelId) + th.App.Srv().Store().Post().InvalidateLastPostTimeCache(channelId) posts, _, err = client.GetPostsAroundLastUnread(userId, channelId, 1, 2, false) require.NoError(t, err) @@ -3175,7 +3175,7 @@ func TestCreatePostNotificationsWithCRT(t *testing.T) { } // reset the cache so that channel member notify props includes all users - th.App.Srv().Store.Channel().ClearCaches() + th.App.Srv().Store().Channel().ClearCaches() for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { diff --git a/api4/reaction_test.go b/api4/reaction_test.go index 86044498d8..21aeaa3b0e 100644 --- a/api4/reaction_test.go +++ b/api4/reaction_test.go @@ -229,7 +229,7 @@ func TestGetReactions(t *testing.T) { var reactions []*model.Reaction for _, userReaction := range userReactions { - reaction, err := th.App.Srv().Store.Reaction().Save(userReaction) + reaction, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) reactions = append(reactions, reaction) } @@ -555,7 +555,7 @@ func TestGetBulkReactions(t *testing.T) { for _, userReaction := range userReactions { reactions := expectedPostIdsReactionsMap[userReaction.PostId] - reaction, err := th.App.Srv().Store.Reaction().Save(userReaction) + reaction, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) reactions = append(reactions, reaction) expectedPostIdsReactionsMap[userReaction.PostId] = reactions diff --git a/api4/resolver.go b/api4/resolver.go index 6cc43e3d33..8a4c021f01 100644 --- a/api4/resolver.go +++ b/api4/resolver.go @@ -111,9 +111,9 @@ func (r *resolver) Config(ctx context.Context) (model.StringMap, error) { } if c.AppContext.Session().UserId == "" { - return c.App.LimitedClientConfigWithComputed(), nil + return c.App.Srv().Platform().LimitedClientConfigWithComputed(), nil } - return c.App.ClientConfigWithComputed(), nil + return c.App.Srv().Platform().ClientConfigWithComputed(), nil } // match with api4.getClientLicense @@ -212,7 +212,7 @@ func (*resolver) ChannelsLeft(ctx context.Context, args struct { return nil, c.Err } - return c.App.Srv().Store.ChannelMemberHistory().GetChannelsLeftSince(args.UserID, int64(args.Since)) + return c.App.Srv().Store().ChannelMemberHistory().GetChannelsLeftSince(args.UserID, int64(args.Since)) } // match with api4.getChannelMember @@ -296,7 +296,7 @@ func (*resolver) ChannelMembers(ctx context.Context, args struct { LastUpdateAt: int(args.LastUpdateAt), ExcludeTeam: args.ExcludeTeam, } - members, err := c.App.Srv().Store.Channel().GetMembersForUserWithCursor(args.UserID, args.TeamID, opts) + members, err := c.App.Srv().Store().Channel().GetMembersForUserWithCursor(args.UserID, args.TeamID, opts) if err != nil { return nil, err } diff --git a/api4/resolver_channel.go b/api4/resolver_channel.go index 4e9a59da38..e8f10a8a98 100644 --- a/api4/resolver_channel.go +++ b/api4/resolver_channel.go @@ -107,7 +107,7 @@ func postProcessChannels(c *web.Context, channels []*model.Channel) ([]*channel, // Avoiding unnecessary queries unless necessary. if len(channelIDs) > 0 { - userInfo, err = c.App.Srv().Store.Channel().GetMembersInfoByChannelIds(channelIDs) + userInfo, err = c.App.Srv().Store().Channel().GetMembersInfoByChannelIds(channelIDs) if err != nil { return nil, err } diff --git a/api4/role_test.go b/api4/role_test.go index 80cbcd5221..0a1d3145cd 100644 --- a/api4/role_test.go +++ b/api4/role_test.go @@ -19,7 +19,7 @@ func TestGetAllRoles(t *testing.T) { th := Setup(t) defer th.TearDown() - roles, err := th.App.Srv().Store.Role().GetAll() + roles, err := th.App.Srv().Store().Role().GetAll() require.NoError(t, err) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { @@ -49,9 +49,9 @@ func TestGetRole(t *testing.T) { SchemeManaged: true, } - role, err := th.App.Srv().Store.Role().Save(role) + role, err := th.App.Srv().Store().Role().Save(role) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(role.Id) + defer th.App.Srv().Store().Job().Delete(role.Id) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { received, _, err := client.GetRole(role.Id) @@ -88,9 +88,9 @@ func TestGetRoleByName(t *testing.T) { SchemeManaged: true, } - role, err := th.App.Srv().Store.Role().Save(role) + role, err := th.App.Srv().Store().Role().Save(role) assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(role.Id) + defer th.App.Srv().Store().Job().Delete(role.Id) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { received, _, err := client.GetRoleByName(role.Name) @@ -141,17 +141,17 @@ func TestGetRolesByNames(t *testing.T) { SchemeManaged: true, } - role1, err := th.App.Srv().Store.Role().Save(role1) + role1, err := th.App.Srv().Store().Role().Save(role1) assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(role1.Id) + defer th.App.Srv().Store().Job().Delete(role1.Id) - role2, err = th.App.Srv().Store.Role().Save(role2) + role2, err = th.App.Srv().Store().Role().Save(role2) assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(role2.Id) + defer th.App.Srv().Store().Job().Delete(role2.Id) - role3, err = th.App.Srv().Store.Role().Save(role3) + role3, err = th.App.Srv().Store().Role().Save(role3) assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(role3.Id) + defer th.App.Srv().Store().Job().Delete(role3.Id) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { // Check all three roles can be found. @@ -199,9 +199,9 @@ func TestPatchRole(t *testing.T) { SchemeManaged: true, } - role, err2 := th.App.Srv().Store.Role().Save(role) + role, err2 := th.App.Srv().Store().Role().Save(role) assert.NoError(t, err2) - defer th.App.Srv().Store.Job().Delete(role.Id) + defer th.App.Srv().Store().Job().Delete(role.Id) patch := &model.RolePatch{ Permissions: &[]string{"manage_system", "create_public_channel", "manage_incoming_webhooks", "manage_outgoing_webhooks"}, @@ -210,18 +210,18 @@ func TestPatchRole(t *testing.T) { th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { // Cannot edit a system admin - adminRole, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_admin") + adminRole, err := th.App.Srv().Store().Role().GetByName(context.Background(), "system_admin") assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(adminRole.Id) + defer th.App.Srv().Store().Job().Delete(adminRole.Id) _, resp, err := client.PatchRole(adminRole.Id, patch) require.Error(t, err) CheckNotImplementedStatus(t, resp) // Cannot give other roles read / write to system roles or manage roles because only system admin can do these actions - systemManager, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_manager") + systemManager, err := th.App.Srv().Store().Role().GetByName(context.Background(), "system_manager") assert.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(systemManager.Id) + defer th.App.Srv().Store().Job().Delete(systemManager.Id) patchWriteSystemRoles := &model.RolePatch{ Permissions: &[]string{model.PermissionSysconsoleWriteUserManagementSystemRoles.Id}, @@ -300,7 +300,7 @@ func TestPatchRole(t *testing.T) { license.Features.GuestAccountsPermissions = model.NewBool(false) th.App.Srv().SetLicense(license) - guestRole, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_guest") + guestRole, err := th.App.Srv().Store().Role().GetByName(context.Background(), "system_guest") require.NoError(t, err) received, resp, err = client.PatchRole(guestRole.Id, patch) require.Error(t, err) @@ -311,7 +311,7 @@ func TestPatchRole(t *testing.T) { license := model.NewTestLicense() license.Features.GuestAccountsPermissions = model.NewBool(true) th.App.Srv().SetLicense(license) - guestRole, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_guest") + guestRole, err := th.App.Srv().Store().Role().GetByName(context.Background(), "system_guest") require.NoError(t, err) _, _, err = client.PatchRole(guestRole.Id, patch) require.NoError(t, err) diff --git a/api4/scheme_test.go b/api4/scheme_test.go index 8f76e9998a..8fda68d19f 100644 --- a/api4/scheme_test.go +++ b/api4/scheme_test.go @@ -315,7 +315,7 @@ func TestGetTeamsForScheme(t *testing.T) { Type: model.TeamOpen, } - team1, err = th.App.Srv().Store.Team().Save(team1) + team1, err = th.App.Srv().Store().Team().Save(team1) require.NoError(t, err) l2, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -323,7 +323,7 @@ func TestGetTeamsForScheme(t *testing.T) { assert.Zero(t, len(l2)) team1.SchemeId = &scheme1.Id - team1, err = th.App.Srv().Store.Team().Update(team1) + team1, err = th.App.Srv().Store().Team().Update(team1) assert.NoError(t, err) l3, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -337,7 +337,7 @@ func TestGetTeamsForScheme(t *testing.T) { Type: model.TeamOpen, SchemeId: &scheme1.Id, } - team2, err = th.App.Srv().Store.Team().Save(team2) + team2, err = th.App.Srv().Store().Team().Save(team2) require.NoError(t, err) l4, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100) @@ -409,7 +409,7 @@ func TestGetChannelsForScheme(t *testing.T) { Type: model.ChannelTypeOpen, } - channel1, errCh := th.App.Srv().Store.Channel().Save(channel1, 1000000) + channel1, errCh := th.App.Srv().Store().Channel().Save(channel1, 1000000) assert.NoError(t, errCh) l2, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -417,7 +417,7 @@ func TestGetChannelsForScheme(t *testing.T) { assert.Zero(t, len(l2)) channel1.SchemeId = &scheme1.Id - channel1, err = th.App.Srv().Store.Channel().Update(channel1) + channel1, err = th.App.Srv().Store().Channel().Update(channel1) assert.NoError(t, err) l3, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -432,7 +432,7 @@ func TestGetChannelsForScheme(t *testing.T) { Type: model.ChannelTypeOpen, SchemeId: &scheme1.Id, } - channel2, err = th.App.Srv().Store.Channel().Save(channel2, 1000000) + channel2, err = th.App.Srv().Store().Channel().Save(channel2, 1000000) assert.NoError(t, err) l4, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100) @@ -630,7 +630,7 @@ func TestDeleteScheme(t *testing.T) { assert.Zero(t, role6.DeleteAt) // Make sure this scheme is in use by a team. - team, err := th.App.Srv().Store.Team().Save(&model.Team{ + team, err := th.App.Srv().Store().Team().Save(&model.Team{ Name: "zz" + model.NewId(), DisplayName: model.NewId(), Email: model.NewId() + "@nowhere.com", @@ -699,7 +699,7 @@ func TestDeleteScheme(t *testing.T) { assert.Zero(t, role6.DeleteAt) // Make sure this scheme is in use by a team. - channel, err := th.App.Srv().Store.Channel().Save(&model.Channel{ + channel, err := th.App.Srv().Store().Channel().Save(&model.Channel{ TeamId: model.NewId(), DisplayName: model.NewId(), Name: model.NewId(), diff --git a/api4/system.go b/api4/system.go index 3d60335d63..9008bd4606 100644 --- a/api4/system.go +++ b/api4/system.go @@ -640,7 +640,7 @@ func setServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddEventParameter("seconds", i) - c.App.Srv().Busy.Set(time.Second * time.Duration(i)) + c.App.Srv().Platform().Busy.Set(time.Second * time.Duration(i)) mlog.Warn("server busy state activated - non-critical services disabled", mlog.Int64("seconds", i)) auditRec.Success() @@ -656,7 +656,7 @@ func clearServerBusy(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("clearServerBusy", audit.Fail) defer c.LogAuditRec(auditRec) - c.App.Srv().Busy.Clear() + c.App.Srv().Platform().Busy.Clear() mlog.Info("server busy state cleared - non-critical services enabled") auditRec.Success() @@ -671,7 +671,7 @@ func getServerBusyExpires(c *Context, w http.ResponseWriter, r *http.Request) { // We call to ToJSON because it actually returns a different struct // along with doing some computations. - sbsJSON, jsonErr := c.App.Srv().Busy.ToJSON() + sbsJSON, jsonErr := c.App.Srv().Platform().Busy.ToJSON() if jsonErr != nil { mlog.Warn(jsonErr.Error()) } diff --git a/api4/system_test.go b/api4/system_test.go index b65d843f58..f63f21438e 100644 --- a/api4/system_test.go +++ b/api4/system_test.go @@ -684,13 +684,13 @@ func TestSetServerBusy(t *testing.T) { resp, err := th.Client.SetServerBusy(secs) require.Error(t, err) CheckForbiddenStatus(t, resp) - require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") + require.False(t, th.App.Srv().Platform().Busy.IsBusy(), "server should not be marked busy") }) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { _, err := c.SetServerBusy(secs) require.NoError(t, err) - require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") + require.True(t, th.App.Srv().Platform().Busy.IsBusy(), "server should be marked busy") }, "as system admin") } @@ -704,7 +704,7 @@ func TestSetServerBusyInvalidParam(t *testing.T) { resp, err := c.SetServerBusy(p) require.Error(t, err) CheckBadRequestStatus(t, resp) - require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy due to invalid param ", p) + require.False(t, th.App.Srv().Platform().Busy.IsBusy(), "server should not be marked busy due to invalid param ", p) } }, "as system admin, invalid param") } @@ -713,19 +713,19 @@ func TestClearServerBusy(t *testing.T) { th := Setup(t) defer th.TearDown() - th.App.Srv().Busy.Set(time.Second * 30) + th.App.Srv().Platform().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { resp, err := th.Client.ClearServerBusy() require.Error(t, err) CheckForbiddenStatus(t, resp) - require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy") + require.True(t, th.App.Srv().Platform().Busy.IsBusy(), "server should be marked busy") }) - th.App.Srv().Busy.Set(time.Second * 30) + th.App.Srv().Platform().Busy.Set(time.Second * 30) th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) { _, err := c.ClearServerBusy() require.NoError(t, err) - require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy") + require.False(t, th.App.Srv().Platform().Busy.IsBusy(), "server should not be marked busy") }, "as system admin") } @@ -733,7 +733,7 @@ func TestGetServerBusy(t *testing.T) { th := Setup(t) defer th.TearDown() - th.App.Srv().Busy.Set(time.Second * 30) + th.App.Srv().Platform().Busy.Set(time.Second * 30) t.Run("as system user", func(t *testing.T) { _, resp, err := th.Client.GetServerBusy() @@ -753,7 +753,7 @@ func TestServerBusy503(t *testing.T) { th := Setup(t) defer th.TearDown() - th.App.Srv().Busy.Set(time.Second * 30) + th.App.Srv().Platform().Busy.Set(time.Second * 30) t.Run("search users while busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} @@ -783,7 +783,7 @@ func TestServerBusy503(t *testing.T) { CheckServiceUnavailableStatus(t, resp) }) - th.App.Srv().Busy.Clear() + th.App.Srv().Platform().Busy.Clear() t.Run("search users while not busy", func(t *testing.T) { us := &model.UserSearch{Term: "test"} diff --git a/api4/team_local.go b/api4/team_local.go index 66b5bc96b9..8f35695e56 100644 --- a/api4/team_local.go +++ b/api4/team_local.go @@ -118,7 +118,7 @@ func localInviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) auditRec.AddMeta("channels", memberInvite.ChannelIds) } - team, err := c.App.Srv().Store.Team().Get(c.Params.TeamId) + team, err := c.App.Srv().Store().Team().Get(c.Params.TeamId) if err != nil { var nfErr *store.ErrNotFound switch { @@ -134,7 +134,7 @@ func localInviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) var channels []*model.Channel if len(memberInvite.ChannelIds) > 0 { - channels, err = c.App.Srv().Store.Channel().GetChannelsByIds(memberInvite.ChannelIds, false) + channels, err = c.App.Srv().Store().Channel().GetChannelsByIds(memberInvite.ChannelIds, false) if err != nil { c.Err = model.NewAppError("prepareLocalInviteNewUsersToTeam", "app.channel.get_channels_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/api4/team_test.go b/api4/team_test.go index e4dcc431c2..a476f17903 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -1155,7 +1155,7 @@ func TestGetAllTeams(t *testing.T) { require.True(t, found) }) // Now actually create the policy and assign the team to it - policy, savePolicyErr := th.App.Srv().Store.RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ + policy, savePolicyErr := th.App.Srv().Store().RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ RetentionPolicy: model.RetentionPolicy{ DisplayName: "Policy 1", PostDurationDays: model.NewInt64(30), @@ -1469,7 +1469,7 @@ func TestSearchAllTeams(t *testing.T) { CheckOKStatus(t, resp) policyTeam := sysManagerTeams[0] // Now actually create the policy and assign the team to it - policy, savePolicyErr := th.App.Srv().Store.RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ + policy, savePolicyErr := th.App.Srv().Store().RetentionPolicy().Save(&model.RetentionPolicyWithTeamAndChannelIDs{ RetentionPolicy: model.RetentionPolicy{ DisplayName: "Policy 1", PostDurationDays: model.NewInt64(30), @@ -2148,7 +2148,7 @@ func TestAddTeamMember(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": team.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) tm, _, err = client.AddTeamMemberFromInvite(token.Token, "") require.NoError(t, err) @@ -2159,7 +2159,7 @@ func TestAddTeamMember(t *testing.T) { require.Equal(t, tm.TeamId, team.Id, "team ids should have matched") - _, err = th.App.Srv().Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after be used") tm, resp, err = client.AddTeamMemberFromInvite("junk", "") @@ -2171,7 +2171,7 @@ func TestAddTeamMember(t *testing.T) { // expired token of more than 50 hours token = model.NewToken(app.TokenTypeTeamInvitation, "") token.CreateAt = model.GetMillis() - 1000*60*60*50 - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, resp, err = client.AddTeamMemberFromInvite(token.Token, "") require.Error(t, err) @@ -2184,7 +2184,7 @@ func TestAddTeamMember(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": testId}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, resp, err = client.AddTeamMemberFromInvite(token.Token, "") require.Error(t, err) @@ -2229,7 +2229,7 @@ func TestAddTeamMember(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": team.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err = client.AddTeamMemberFromInvite(token.Token, "") CheckErrorID(t, err, "app.team.invite_token.group_constrained.error") diff --git a/api4/usage_test.go b/api4/usage_test.go index 84067db6dd..41d96ae75c 100644 --- a/api4/usage_test.go +++ b/api4/usage_test.go @@ -33,9 +33,9 @@ func TestGetPostsUsage(t *testing.T) { th.CreatePost() } - total, err := th.Server.Store.Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true}) + total, err := th.Server.Store().Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true}) require.NoError(t, err) - usersOnly, err := th.Server.Store.Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true, UsersPostsOnly: true}) + usersOnly, err := th.Server.Store().Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true, UsersPostsOnly: true}) require.NoError(t, err) require.GreaterOrEqual(t, usersOnly, int64(14)) diff --git a/api4/user_test.go b/api4/user_test.go index 228628380c..ba5eaa70a2 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -225,7 +225,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) ruser, resp, err := th.Client.CreateUserWithToken(&user, token.Token) require.NoError(t, err) @@ -235,7 +235,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Equal(t, user.Nickname, ruser.Nickname) require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) - _, err = th.App.Srv().Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after being used") teams, appErr := th.App.GetTeamsForUser(ruser.Id) @@ -250,7 +250,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) ruser, resp, err := client.CreateUserWithToken(&user, token.Token) require.NoError(t, err) @@ -260,7 +260,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Equal(t, user.Nickname, ruser.Nickname) require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) - _, err = th.App.Srv().Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after being used") teams, appErr := th.App.GetTeamsForUser(ruser.Id) @@ -275,7 +275,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, _, err := th.Client.CreateUserWithToken(&user, "") @@ -292,7 +292,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) token.CreateAt = past49Hours - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, resp, err := th.Client.CreateUserWithToken(&user, token.Token) @@ -323,7 +323,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false }) @@ -344,7 +344,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserCreation = false }) @@ -362,7 +362,7 @@ func TestCreateUserWithToken(t *testing.T) { app.TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) enableOpenServer := th.App.Config().TeamSettings.EnableOpenServer defer func() { @@ -379,7 +379,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Equal(t, user.Nickname, ruser.Nickname) require.Equal(t, model.SystemUserRoleId, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) - _, err = th.App.Srv().Store.Token().GetByToken(token.Token) + _, err = th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, err, "The token must be deleted after be used") }) } @@ -1665,7 +1665,7 @@ func TestGetTotalUsersStat(t *testing.T) { th := Setup(t) defer th.TearDown() - total, _ := th.Server.Store.User().Count(model.UserCountOptions{ + total, _ := th.Server.Store().User().Count(model.UserCountOptions{ IncludeDeleted: false, IncludeBotAccounts: true, }) @@ -1934,7 +1934,7 @@ func TestUpdateUserAuth(t *testing.T) { user := th.CreateUser() th.LinkUserToTeam(user, team) - _, err := th.App.Srv().Store.User().VerifyEmail(user.Id, user.Email) + _, err := th.App.Srv().Store().User().VerifyEmail(user.Id, user.Email) require.NoError(t, err) userAuth := &model.UserAuth{} @@ -1967,7 +1967,7 @@ func TestUpdateUserAuth(t *testing.T) { // Regular user can not use endpoint user2 := th.CreateUser() th.LinkUserToTeam(user2, team) - _, err = th.App.Srv().Store.User().VerifyEmail(user2.Id, user2.Email) + _, err = th.App.Srv().Store().User().VerifyEmail(user2.Id, user2.Email) require.NoError(t, err) th.SystemAdminClient.Login(user2.Email, "passwd1") @@ -2100,11 +2100,11 @@ func TestPermanentDeleteAllUsers(t *testing.T) { require.Nil(t, appErr) // Check that we have users and posts in the database - users, err := th.App.Srv().Store.User().GetAll() + users, err := th.App.Srv().Store().User().GetAll() require.NoError(t, err) require.Greater(t, len(users), 0) - postCount, err := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + postCount, err := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) require.NoError(t, err) require.Greater(t, postCount, int64(0)) @@ -2113,11 +2113,11 @@ func TestPermanentDeleteAllUsers(t *testing.T) { require.NoError(t, err) // Check that both user and post tables are empty - users, err = th.App.Srv().Store.User().GetAll() + users, err = th.App.Srv().Store().User().GetAll() require.NoError(t, err) require.Len(t, users, 0) - postCount, err = th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + postCount, err = th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) require.NoError(t, err) require.Equal(t, postCount, int64(0)) @@ -2233,7 +2233,7 @@ func TestUpdateUserActive(t *testing.T) { require.NoError(t, err) authData := model.NewId() - _, err := th.App.Srv().Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) + _, err := th.App.Srv().Store().User().UpdateAuthData(user.Id, "random", &authData, "", true) require.NoError(t, err) _, err = client.UpdateUserActive(user.Id, false) @@ -2472,7 +2472,7 @@ func TestGetUsersWithoutTeam(t *testing.T) { }) require.NoError(t, err) th.LinkUserToTeam(user, th.BasicTeam) - defer th.App.Srv().Store.User().PermanentDelete(user.Id) + defer th.App.Srv().Store().User().PermanentDelete(user.Id) user2, _, err := th.Client.CreateUser(&model.User{ Username: "a000000001" + model.NewId(), @@ -2480,7 +2480,7 @@ func TestGetUsersWithoutTeam(t *testing.T) { Password: "Password1", }) require.NoError(t, err) - defer th.App.Srv().Store.User().PermanentDelete(user2.Id) + defer th.App.Srv().Store().User().PermanentDelete(user2.Id) rusers, _, err := th.SystemAdminClient.GetUsersWithoutTeam(0, 100, "") require.NoError(t, err) @@ -2789,13 +2789,13 @@ func TestUserLoginMFAFlow(t *testing.T) { assert.Nil(t, appErr) // Fake user has MFA enabled - err := th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + err := th.Server.Store().User().UpdateMfaActive(th.BasicUser.Id, true) require.NoError(t, err) - err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + err = th.Server.Store().User().UpdateMfaActive(th.BasicUser.Id, true) require.NoError(t, err) - err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) + err = th.Server.Store().User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) require.NoError(t, err) user, _, err := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) @@ -2822,10 +2822,10 @@ func TestUserLoginMFAFlow(t *testing.T) { assert.Nil(t, appErr) // Fake user has MFA enabled - err := th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + err := th.Server.Store().User().UpdateMfaActive(th.BasicUser.Id, true) require.NoError(t, err) - err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) + err = th.Server.Store().User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) require.NoError(t, err) code := dgoogauth.ComputeCode(secret.Secret, time.Now().UTC().Unix()/30) @@ -3006,7 +3006,7 @@ func TestResetPassword(t *testing.T) { loc += 6 recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TokenSize] } - recoveryToken, err := th.App.Srv().Store.Token().GetByToken(recoveryTokenString) + recoveryToken, err := th.App.Srv().Store().Token().GetByToken(recoveryTokenString) require.NoError(t, err, "Recovery token not found (%s)", recoveryTokenString) resp, err := th.Client.ResetPassword(recoveryToken.Token, "") @@ -3036,7 +3036,7 @@ func TestResetPassword(t *testing.T) { require.Error(t, err) CheckBadRequestStatus(t, resp) authData := model.NewId() - _, err = th.App.Srv().Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) + _, err = th.App.Srv().Store().User().UpdateAuthData(user.Id, "random", &authData, "", true) require.NoError(t, err) th.TestForAllClients(t, func(t *testing.T, client *model.Client4) { resp, err = client.SendPasswordResetEmail(user.Email) @@ -3200,10 +3200,10 @@ func TestRevokeSessionsFromAllUsers(t *testing.T) { th.Client.Login(user.Email, user.Password) admin := th.SystemAdminUser th.Client.Login(admin.Email, admin.Password) - sessions, err := th.Server.Store.Session().GetSessions(user.Id) + sessions, err := th.Server.Store().Session().GetSessions(user.Id) require.NotEmpty(t, sessions) require.NoError(t, err) - sessions, err = th.Server.Store.Session().GetSessions(admin.Id) + sessions, err = th.Server.Store().Session().GetSessions(admin.Id) require.NotEmpty(t, sessions) require.NoError(t, err) _, err = th.Client.RevokeSessionsFromAllUsers() @@ -3215,11 +3215,11 @@ func TestRevokeSessionsFromAllUsers(t *testing.T) { require.Error(t, err) CheckUnauthorizedStatus(t, resp) - sessions, err = th.Server.Store.Session().GetSessions(user.Id) + sessions, err = th.Server.Store().Session().GetSessions(user.Id) require.Empty(t, sessions) require.NoError(t, err) - sessions, err = th.Server.Store.Session().GetSessions(admin.Id) + sessions, err = th.Server.Store().Session().GetSessions(admin.Id) require.Empty(t, sessions) require.NoError(t, err) @@ -3891,7 +3891,7 @@ func TestSwitchAccount(t *testing.T) { th.LoginBasic() fakeAuthData := model.NewId() - _, appErr := th.App.Srv().Store.User().UpdateAuthData(th.BasicUser.Id, model.UserAuthServiceGitlab, &fakeAuthData, th.BasicUser.Email, true) + _, appErr := th.App.Srv().Store().User().UpdateAuthData(th.BasicUser.Id, model.UserAuthServiceGitlab, &fakeAuthData, th.BasicUser.Email, true) require.NoError(t, appErr) sr = &model.SwitchRequest{ @@ -4978,7 +4978,7 @@ func TestGetUsersByStatus(t *testing.T) { th.LinkUserToTeam(user, team) th.AddUserToChannel(user, channel) - th.App.SaveAndBroadcastStatus(&model.Status{ + th.App.Srv().Platform().SaveAndBroadcastStatus(&model.Status{ UserId: user.Id, Status: status, Manual: true, @@ -5169,7 +5169,7 @@ func TestLoginLockout(t *testing.T) { CheckErrorID(t, err, "api.user.check_user_login_attempts.too_many.app_error") // Fake user has MFA enabled - err = th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, true) + err = th.Server.Store().User().UpdateMfaActive(th.BasicUser2.Id, true) require.NoError(t, err) _, _, err = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000") CheckErrorID(t, err, "api.user.check_user_mfa.bad_code.app_error") @@ -5183,7 +5183,7 @@ func TestLoginLockout(t *testing.T) { CheckErrorID(t, err, "api.user.check_user_login_attempts.too_many.app_error") // Fake user has MFA disabled - err = th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, false) + err = th.Server.Store().User().UpdateMfaActive(th.BasicUser2.Id, false) require.NoError(t, err) //Check if lock is active @@ -5512,7 +5512,7 @@ func TestPublishUserTyping(t *testing.T) { }) }) - th.Server.Busy.Set(time.Second * 10) + th.Server.Platform().Busy.Set(time.Second * 10) t.Run("should return service unavailable for non-system admin user when triggering a typing event and server busy", func(t *testing.T) { resp, err := th.Client.PublishUserTyping("invalid", tr) @@ -5643,7 +5643,7 @@ func TestGetThreadsForUser(t *testing.T) { require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{}) require.NoError(t, err) @@ -5660,7 +5660,7 @@ func TestGetThreadsForUser(t *testing.T) { require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{}) require.NoError(t, err) @@ -5679,7 +5679,7 @@ func TestGetThreadsForUser(t *testing.T) { require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Extended: true, @@ -5701,7 +5701,7 @@ func TestGetThreadsForUser(t *testing.T) { require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -5744,7 +5744,7 @@ func TestGetThreadsForUser(t *testing.T) { CheckCreatedStatus(t, resp) } - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -5771,7 +5771,7 @@ func TestGetThreadsForUser(t *testing.T) { rootIdBefore := rootIds[14].Id rootIdAfter := rootIds[16].Id - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -5822,8 +5822,8 @@ func TestGetThreadsForUser(t *testing.T) { CheckCreatedStatus(t, resp) } - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -5858,8 +5858,8 @@ func TestGetThreadsForUser(t *testing.T) { CheckCreatedStatus(t, resp) } - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) uss, _, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -5881,7 +5881,7 @@ func TestGetThreadsForUser(t *testing.T) { }) t.Run("setting both threadsOnly, and totalsOnly params is not allowed", func(t *testing.T) { - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) _, resp, err := th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ ThreadsOnly: true, @@ -5966,8 +5966,8 @@ func TestThreadSocketEvents(t *testing.T) { replyPost, appErr := th.App.CreatePostAsUser(th.Context, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testReply @" + th.BasicUser.Username, UserId: th.BasicUser2.Id, RootId: rpost.Id}, th.Context.Session().Id, false) require.Nil(t, appErr) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser2.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser2.Id) t.Run("Listed for update event", func(t *testing.T) { var caught bool @@ -6230,7 +6230,7 @@ func TestFollowThreads(t *testing.T) { require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) var uss *model.Threads uss, _, err = th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ Deleted: false, @@ -6332,8 +6332,8 @@ func TestMaintainUnreadRepliesInThread(t *testing.T) { }) client := th.Client - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) // create a post by regular user rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsg"}) @@ -6389,8 +6389,8 @@ func TestThreadCounts(t *testing.T) { }) client := th.Client - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) // create a post by regular user rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsg"}) @@ -6409,7 +6409,7 @@ func TestThreadCounts(t *testing.T) { }) // delete first thread - th.App.Srv().Store.Post().Delete(rpost.Id, model.GetMillis(), th.BasicUser.Id) + th.App.Srv().Store().Post().Delete(rpost.Id, model.GetMillis(), th.BasicUser.Id) // we should now have 1 thread with 2 replies checkThreadListReplies(t, th, th.Client, th.BasicUser.Id, 2, 1, &model.GetUserThreadsOpts{ @@ -6432,8 +6432,8 @@ func TestSingleThreadGet(t *testing.T) { }) client := th.Client - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) // create a post by regular user rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsg"}) @@ -6489,8 +6489,8 @@ func TestMaintainUnreadMentionsInThread(t *testing.T) { return uss, resp } - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) // create regular post rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsg"}) @@ -6545,7 +6545,7 @@ func TestReadThreads(t *testing.T) { _, resp, err = client.CreatePost(&model.Post{ChannelId: th.BasicChannel.Id, Message: "testReply", RootId: rpost.Id}) require.NoError(t, err) CheckCreatedStatus(t, resp) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) var uss, uss2 *model.Threads uss, _, err = th.Client.GetUserThreads(th.BasicUser.Id, th.BasicTeam.Id, model.GetUserThreadsOpts{ @@ -6567,8 +6567,8 @@ func TestReadThreads(t *testing.T) { }) t.Run("1 thread by timestamp", func(t *testing.T) { - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsgC1"}) postAndCheck(t, th.SystemAdminClient, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testReplyC1", RootId: rpost.Id}) @@ -6595,8 +6595,8 @@ func TestReadThreads(t *testing.T) { }) t.Run("1 thread by post id", func(t *testing.T) { - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.BasicUser.Id) - defer th.App.Srv().Store.Post().PermanentDeleteByUser(th.SystemAdminUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.BasicUser.Id) + defer th.App.Srv().Store().Post().PermanentDeleteByUser(th.SystemAdminUser.Id) rpost, _ := postAndCheck(t, client, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testMsgC1"}) reply1, _ := postAndCheck(t, th.SystemAdminClient, &model.Post{ChannelId: th.BasicChannel.Id, Message: "testReplyC1", RootId: rpost.Id}) diff --git a/api4/websocket.go b/api4/websocket.go index 63834e0a69..540188be8a 100644 --- a/api4/websocket.go +++ b/api4/websocket.go @@ -8,7 +8,7 @@ import ( "github.com/gorilla/websocket" - "github.com/mattermost/mattermost-server/v6/app" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mlog" ) @@ -38,7 +38,7 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { // We initialize webconn with all the necessary data. // If the queues are empty, they are initialized in the constructor. - cfg := &app.WebConnConfig{ + cfg := &platform.WebConnConfig{ WebSocket: ws, Session: *c.AppContext.Session(), TFunc: c.AppContext.T, @@ -53,7 +53,7 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { cfg.ConnectionID = model.NewId() // In case of fresh connection id, sequence number is already zero. } else { - cfg, err = c.App.PopulateWebConnConfig(c.AppContext.Session(), cfg, r.URL.Query().Get(sequenceNumberParam)) + cfg, err = c.App.Srv().Platform().PopulateWebConnConfig(c.AppContext.Session(), cfg, r.URL.Query().Get(sequenceNumberParam)) if err != nil { mlog.Warn("Error while populating webconn config", mlog.String("id", r.URL.Query().Get(connectionIDParam)), mlog.Err(err)) ws.Close() @@ -61,9 +61,9 @@ func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) { } } - wc := c.App.NewWebConn(cfg) + wc := c.App.Srv().Platform().NewWebConn(cfg, c.App, c.App.Srv().Channels().GetPluginsEnvironment) if c.AppContext.Session().UserId != "" { - c.App.HubRegister(wc) + c.App.Srv().Platform().HubRegister(wc) } wc.Pump() diff --git a/api4/websocket_test.go b/api4/websocket_test.go index 051b7ae28f..28729b936a 100644 --- a/api4/websocket_test.go +++ b/api4/websocket_test.go @@ -295,14 +295,14 @@ func TestWebSocketStatuses(t *testing.T) { ruser, _, err := client.CreateUser(&user) require.NoError(t, err) th.LinkUserToTeam(ruser, rteam) - _, err = th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err = th.App.Srv().Store().User().VerifyEmail(ruser.Id, ruser.Email) require.NoError(t, err) user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"} ruser2, _, err := client.CreateUser(&user2) require.NoError(t, err) th.LinkUserToTeam(ruser2, rteam) - _, err = th.App.Srv().Store.User().VerifyEmail(ruser2.Id, ruser2.Email) + _, err = th.App.Srv().Store().User().VerifyEmail(ruser2.Id, ruser2.Email) require.NoError(t, err) client.Login(user.Email, user.Password) diff --git a/app/admin.go b/app/admin.go index 44baefa1a8..84be5e71d9 100644 --- a/app/admin.go +++ b/app/admin.go @@ -8,11 +8,8 @@ import ( "fmt" "io" "net/http" - "os" - "runtime/debug" "time" - "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/shared/i18n" @@ -28,8 +25,8 @@ func (s *Server) GetLogs(page, perPage int) ([]string, *model.AppError) { var lines []string license := s.License() - if license != nil && *license.Features.Cluster && s.Cluster != nil && *s.platform.Config().ClusterSettings.Enable { - if info := s.Cluster.GetMyClusterInfo(); info != nil { + if license != nil && *license.Features.Cluster && s.platform.Cluster() != nil && *s.platform.Config().ClusterSettings.Enable { + if info := s.platform.Cluster().GetMyClusterInfo(); info != nil { lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, info.Hostname) @@ -47,8 +44,8 @@ func (s *Server) GetLogs(page, perPage int) ([]string, *model.AppError) { lines = append(lines, melines...) - if s.Cluster != nil && *s.platform.Config().ClusterSettings.Enable { - clines, err := s.Cluster.GetLogs(page, perPage) + if s.platform.Cluster() != nil && *s.platform.Config().ClusterSettings.Enable { + clines, err := s.platform.Cluster().GetLogs(page, perPage) if err != nil { return nil, err } @@ -64,75 +61,7 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { } func (s *Server) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { - var lines []string - - if *s.platform.Config().LogSettings.EnableFile { - s.Log().Flush() - logFile := config.GetLogFileLocation(*s.platform.Config().LogSettings.FileLocation) - file, err := os.Open(logFile) - if err != nil { - return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - defer file.Close() - - var newLine = []byte{'\n'} - var lineCount int - const searchPos = -1 - b := make([]byte, 1) - var endOffset int64 = 0 - - // if the file exists and it's last byte is '\n' - skip it - var stat os.FileInfo - if stat, err = os.Stat(logFile); err == nil { - if _, err = file.ReadAt(b, stat.Size()-1); err == nil && b[0] == newLine[0] { - endOffset = -1 - } - } - lineEndPos, err := file.Seek(endOffset, io.SeekEnd) - if err != nil { - return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - for { - pos, err := file.Seek(searchPos, io.SeekCurrent) - if err != nil { - return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - _, err = file.ReadAt(b, pos) - if err != nil { - return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - if b[0] == newLine[0] || pos == 0 { - lineCount++ - if lineCount > page*perPage { - line := make([]byte, lineEndPos-pos) - _, err := file.ReadAt(line, pos) - if err != nil { - return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - lines = append(lines, string(line)) - } - if pos == 0 { - break - } - lineEndPos = pos - } - - if len(lines) == perPage { - break - } - } - - for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { - lines[i], lines[j] = lines[j], lines[i] - } - } else { - lines = append(lines, "") - } - - return lines, nil + return s.platform.GetLogsSkipSend(page, perPage) } func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { @@ -150,35 +79,12 @@ func (a *App) GetClusterStatus() []*model.ClusterInfo { } func (s *Server) InvalidateAllCaches() *model.AppError { - debug.FreeOSMemory() - s.InvalidateAllCachesSkipSend() - - if s.Cluster != nil { - - msg := &model.ClusterMessage{ - Event: model.ClusterEventInvalidateAllCaches, - SendType: model.ClusterSendReliable, - WaitForAllToSend: true, - } - - s.Cluster.SendClusterMessage(msg) - } - - return nil + return s.platform.InvalidateAllCaches() } func (s *Server) InvalidateAllCachesSkipSend() { - mlog.Info("Purging all caches") - s.userService.ClearAllUsersSessionCacheLocal() - s.statusCache.Purge() - s.Store.Team().ClearCaches() - s.Store.Channel().ClearCaches() - s.Store.User().ClearCaches() - s.Store.Post().ClearCaches() - s.Store.FileInfo().ClearCaches() - s.Store.Webhook().ClearCaches() - linkCache.Purge() - s.LoadLicense() + s.platform.InvalidateAllCachesSkipSend() + } func (a *App) RecycleDatabaseConnection() { @@ -187,7 +93,7 @@ func (a *App) RecycleDatabaseConnection() { // This works by setting 10 seconds as the max conn lifetime for all DB connections. // This allows in gradually closing connections as they expire. In future, we can think // of exposing this as a param from the REST api. - a.Srv().Store.RecycleDBConnections(10 * time.Second) + a.Srv().Store().RecycleDBConnections(10 * time.Second) mlog.Info("Finished recycling database connections.") } @@ -237,16 +143,6 @@ func (a *App) TestEmail(userID string, cfg *model.Config) *model.AppError { return nil } -// serverBusyStateChanged is called when a CLUSTER_EVENT_BUSY_STATE_CHANGED is received. -func (s *Server) serverBusyStateChanged(sbs *model.ServerBusyState) { - s.Busy.ClusterEventChanged(sbs) - if sbs.Busy { - mlog.Warn("server busy state activated via cluster event - non-critical services disabled", mlog.Int64("expires_sec", sbs.Expires)) - } else { - mlog.Info("server busy state cleared via cluster event - non-critical services enabled") - } -} - func (a *App) GetLatestVersion(latestVersionUrl string) (*model.GithubReleaseInfo, *model.AppError) { var cachedLatestVersion *model.GithubReleaseInfo if cacheErr := latestVersionCache.Get("latest_version_cache", &cachedLatestVersion); cacheErr == nil { diff --git a/app/admin_advisor.go b/app/admin_advisor.go index 2fdd0c16be..487443d860 100644 --- a/app/admin_advisor.go +++ b/app/admin_advisor.go @@ -15,7 +15,7 @@ import ( ) func (a *App) GetWarnMetricsStatus() (map[string]*model.WarnMetricStatus, *model.AppError) { - systemDataList, nErr := a.Srv().Store.System().Get() + systemDataList, nErr := a.Srv().Store().System().Get() if nErr != nil { return nil, model.NewAppError("GetWarnMetricsStatus", "app.system.get.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -148,7 +148,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18 func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, forceAck bool, isBot bool) *model.AppError { if warnMetric, ok := model.WarnMetricsTable[warnMetricId]; ok { - data, nErr := a.Srv().Store.System().GetByName(warnMetric.Id) + data, nErr := a.Srv().Store().System().GetByName(warnMetric.Id) if nErr == nil && data != nil && data.Value == model.WarnMetricStatusAck { mlog.Debug("This metric warning has already been acknowledged", mlog.String("id", warnMetric.Id)) return nil @@ -166,7 +166,7 @@ func (a *App) NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, data.Props["ContactEmailValue"] = sender.Email //same definition as the active users count metric displayed in the SystemConsole Analytics section - registeredUsersCount, cerr := a.Srv().Store.User().Count(model.UserCountOptions{}) + registeredUsersCount, cerr := a.Srv().Store().User().Count(model.UserCountOptions{}) if cerr != nil { mlog.Warn("Error retrieving the number of registered users", mlog.Err(cerr)) } else { @@ -232,7 +232,7 @@ func (a *App) setWarnMetricsStatus(status string) *model.AppError { func (a *App) setWarnMetricsStatusForId(warnMetricId string, status string) *model.AppError { mlog.Debug("Store status for warn metric", mlog.String("warnMetricId", warnMetricId), mlog.String("status", status)) - if err := a.Srv().Store.System().SaveOrUpdateWithWarnMetricHandling(&model.System{ + if err := a.Srv().Store().System().SaveOrUpdateWithWarnMetricHandling(&model.System{ Name: warnMetricId, Value: status, }); err != nil { @@ -251,7 +251,7 @@ func (a *App) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId st return appErr } - registeredUsersCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) + registeredUsersCount, err := a.Srv().Store().User().Count(model.UserCountOptions{}) if err != nil { return model.NewAppError("RequestLicenseAndAckWarnMetric", "api.license.request_trial_license.fail_get_user_count.app_error", nil, "", http.StatusBadRequest).Wrap(err) } diff --git a/app/analytics.go b/app/analytics.go index c7b2288749..dba7f78bd1 100644 --- a/app/analytics.go +++ b/app/analytics.go @@ -20,7 +20,7 @@ const ( func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *model.AppError) { skipIntensiveQueries := false var systemUserCount int64 - systemUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) + systemUserCount, err := a.Srv().Store().User().Count(model.UserCountOptions{}) if err != nil { return nil, model.NewAppError("GetAnalytics", "app.user.get_total_users_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -48,7 +48,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var openChannelsCount int64 g.Go(func() error { var err error - if openChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypeOpen); err != nil { + if openChannelsCount, err = a.Srv().Store().Channel().AnalyticsTypeCount(teamID, model.ChannelTypeOpen); err != nil { return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -57,7 +57,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var privateChannelsCount int64 g.Go(func() error { var err error - if privateChannelsCount, err = a.Srv().Store.Channel().AnalyticsTypeCount(teamID, model.ChannelTypePrivate); err != nil { + if privateChannelsCount, err = a.Srv().Store().Channel().AnalyticsTypeCount(teamID, model.ChannelTypePrivate); err != nil { return model.NewAppError("GetAnalytics", "app.channel.analytics_type_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -68,7 +68,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo if teamID == "" { g.Go(func() error { var err error - if inactiveUsersCount, err = a.Srv().Store.User().AnalyticsGetInactiveUsersCount(); err != nil { + if inactiveUsersCount, err = a.Srv().Store().User().AnalyticsGetInactiveUsersCount(); err != nil { return model.NewAppError("GetAnalytics", "app.user.analytics_get_inactive_users_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -76,7 +76,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo } else { g.Go(func() error { var err error - if usersCount, err = a.Srv().Store.User().Count(model.UserCountOptions{TeamId: teamID}); err != nil { + if usersCount, err = a.Srv().Store().User().Count(model.UserCountOptions{TeamId: teamID}); err != nil { return model.NewAppError("GetAnalytics", "app.user.get_total_users_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -87,7 +87,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo if !skipIntensiveQueries { g.Go(func() error { var err error - if postsCount, err = a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID}); err != nil { + if postsCount, err = a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID}); err != nil { return model.NewAppError("GetAnalytics", "app.post.analytics_posts_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -97,7 +97,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var teamsCount int64 g.Go(func() error { var err error - if teamsCount, err = a.Srv().Store.Team().AnalyticsTeamCount(nil); err != nil { + if teamsCount, err = a.Srv().Store().Team().AnalyticsTeamCount(nil); err != nil { return model.NewAppError("GetAnalytics", "app.team.analytics_team_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -106,7 +106,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var dailyActiveUsersCount int64 g.Go(func() error { var err error - if dailyActiveUsersCount, err = a.Srv().Store.User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}); err != nil { + if dailyActiveUsersCount, err = a.Srv().Store().User().AnalyticsActiveCount(DayMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}); err != nil { return model.NewAppError("GetAnalytics", "app.user.analytics_daily_active_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -115,7 +115,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var monthlyActiveUsersCount int64 g.Go(func() error { var err error - if monthlyActiveUsersCount, err = a.Srv().Store.User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}); err != nil { + if monthlyActiveUsersCount, err = a.Srv().Store().User().AnalyticsActiveCount(MonthMilliseconds, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}); err != nil { return model.NewAppError("GetAnalytics", "app.user.analytics_daily_active_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -152,8 +152,8 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo } totalSockets := a.TotalWebsocketConnections() - totalMasterDb := a.Srv().Store.TotalMasterDbConnections() - totalReadDb := a.Srv().Store.TotalReadDbConnections() + totalMasterDb := a.Srv().Store().TotalMasterDbConnections() + totalReadDb := a.Srv().Store().TotalReadDbConnections() for _, stat := range stats { totalSockets = totalSockets + stat.TotalWebsocketConnections @@ -167,8 +167,8 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo } else { rows[5].Value = float64(a.TotalWebsocketConnections()) - rows[6].Value = float64(a.Srv().Store.TotalMasterDbConnections()) - rows[7].Value = float64(a.Srv().Store.TotalReadDbConnections()) + rows[6].Value = float64(a.Srv().Store().TotalMasterDbConnections()) + rows[7].Value = float64(a.Srv().Store().TotalReadDbConnections()) } rows[8].Value = float64(dailyActiveUsersCount) @@ -180,7 +180,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo rows := model.AnalyticsRows{&model.AnalyticsRow{Name: "", Value: -1}} return rows, nil } - analyticsRows, nErr := a.Srv().Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ + analyticsRows, nErr := a.Srv().Store().Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ TeamId: teamID, BotsOnly: true, YesterdayOnly: false, @@ -195,7 +195,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo rows := model.AnalyticsRows{&model.AnalyticsRow{Name: "", Value: -1}} return rows, nil } - analyticsRows, nErr := a.Srv().Store.Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ + analyticsRows, nErr := a.Srv().Store().Post().AnalyticsPostCountsByDay(&model.AnalyticsPostCountsOptions{ TeamId: teamID, BotsOnly: false, YesterdayOnly: false, @@ -211,7 +211,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo return rows, nil } - analyticsRows, nErr := a.Srv().Store.Post().AnalyticsUserCountsWithPostsByDay(teamID) + analyticsRows, nErr := a.Srv().Store().Post().AnalyticsUserCountsWithPostsByDay(teamID) if nErr != nil { return nil, model.NewAppError("GetAnalytics", "app.post.analytics_user_counts_posts_by_day.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -231,7 +231,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var incomingWebhookCount int64 g2.Go(func() error { var err error - if incomingWebhookCount, err = a.Srv().Store.Webhook().AnalyticsIncomingCount(teamID); err != nil { + if incomingWebhookCount, err = a.Srv().Store().Webhook().AnalyticsIncomingCount(teamID); err != nil { return model.NewAppError("GetAnalytics", "app.webhooks.analytics_incoming_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -240,7 +240,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var outgoingWebhookCount int64 g2.Go(func() error { var err error - if outgoingWebhookCount, err = a.Srv().Store.Webhook().AnalyticsOutgoingCount(teamID); err != nil { + if outgoingWebhookCount, err = a.Srv().Store().Webhook().AnalyticsOutgoingCount(teamID); err != nil { return model.NewAppError("GetAnalytics", "app.webhooks.analytics_outgoing_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -249,7 +249,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var commandsCount int64 g2.Go(func() error { var err error - if commandsCount, err = a.Srv().Store.Command().AnalyticsCommandCount(teamID); err != nil { + if commandsCount, err = a.Srv().Store().Command().AnalyticsCommandCount(teamID); err != nil { return model.NewAppError("GetAnalytics", "app.analytics.getanalytics.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -258,7 +258,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo var sessionsCount int64 g2.Go(func() error { var err error - if sessionsCount, err = a.Srv().Store.Session().AnalyticsSessionCount(); err != nil { + if sessionsCount, err = a.Srv().Store().Session().AnalyticsSessionCount(); err != nil { return model.NewAppError("GetAnalytics", "app.session.analytics_session_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -269,7 +269,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo if !skipIntensiveQueries { g2.Go(func() error { var err error - if filesCount, err = a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID, MustHaveFile: true}); err != nil { + if filesCount, err = a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID, MustHaveFile: true}); err != nil { return model.NewAppError("GetAnalytics", "app.post.analytics_posts_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -277,7 +277,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo g2.Go(func() error { var err error - if hashtagsCount, err = a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID, MustHaveHashtag: true}); err != nil { + if hashtagsCount, err = a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamID, MustHaveHashtag: true}); err != nil { return model.NewAppError("GetAnalytics", "app.post.analytics_posts_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -308,7 +308,7 @@ func (a *App) GetAnalytics(name string, teamID string) (model.AnalyticsRows, *mo } func (a *App) GetRecentlyActiveUsersForTeam(teamID string) (map[string]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetRecentlyActiveUsersForTeam(teamID, 0, 100, nil) + users, err := a.Srv().Store().User().GetRecentlyActiveUsersForTeam(teamID, 0, 100, nil) if err != nil { return nil, model.NewAppError("GetRecentlyActiveUsersForTeam", "app.user.get_recently_active_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -323,7 +323,7 @@ func (a *App) GetRecentlyActiveUsersForTeam(teamID string) (map[string]*model.Us } func (a *App) GetRecentlyActiveUsersForTeamPage(teamID string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetRecentlyActiveUsersForTeam(teamID, page*perPage, perPage, viewRestrictions) + users, err := a.Srv().Store().User().GetRecentlyActiveUsersForTeam(teamID, page*perPage, perPage, viewRestrictions) if err != nil { return nil, model.NewAppError("GetRecentlyActiveUsersForTeamPage", "app.user.get_recently_active_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -332,7 +332,7 @@ func (a *App) GetRecentlyActiveUsersForTeamPage(teamID string, page, perPage int } func (a *App) GetNewUsersForTeamPage(teamID string, page, perPage int, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetNewUsersForTeam(teamID, page*perPage, perPage, viewRestrictions) + users, err := a.Srv().Store().User().GetNewUsersForTeam(teamID, page*perPage, perPage, viewRestrictions) if err != nil { return nil, model.NewAppError("GetNewUsersForTeamPage", "app.user.get_new_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/app.go b/app/app.go index 498bd64b2b..080cbb3465 100644 --- a/app/app.go +++ b/app/app.go @@ -58,20 +58,8 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) { utils.RenderWebAppError(a.Config(), w, r, model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound), a.AsymmetricSigningKey()) } -func (s *Server) getSystemInstallDate() (int64, *model.AppError) { - systemData, err := s.Store.System().GetByName(model.SystemInstallationDateKey) - if err != nil { - return 0, model.NewAppError("getSystemInstallDate", "app.system.get_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - value, err := strconv.ParseInt(systemData.Value, 10, 64) - if err != nil { - return 0, model.NewAppError("getSystemInstallDate", "app.system_install_date.parse_int.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - return value, nil -} - func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) { - systemData, err := s.Store.System().GetByName(model.SystemFirstServerRunTimestampKey) + systemData, err := s.Store().System().GetByName(model.SystemFirstServerRunTimestampKey) if err != nil { return 0, model.NewAppError("getFirstServerRunTimestamp", "app.system.get_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -99,7 +87,7 @@ func (a *App) AccountMigration() einterfaces.AccountMigrationInterface { return a.ch.AccountMigration } func (a *App) Cluster() einterfaces.ClusterInterface { - return a.ch.srv.Cluster + return a.ch.srv.platform.Cluster() } func (a *App) Compliance() einterfaces.ComplianceInterface { return a.ch.Compliance @@ -108,7 +96,7 @@ func (a *App) DataRetention() einterfaces.DataRetentionInterface { return a.ch.DataRetention } func (a *App) SearchEngine() *searchengine.Broker { - return a.ch.srv.SearchEngine + return a.ch.srv.platform.SearchEngine } func (a *App) Ldap() einterfaces.LdapInterface { return a.ch.Ldap @@ -144,14 +132,14 @@ func (a *App) License() *model.License { func (a *App) DBHealthCheckWrite() error { currentTime := strconv.FormatInt(time.Now().Unix(), 10) - return a.Srv().Store.System().SaveOrUpdate(&model.System{ + return a.Srv().Store().System().SaveOrUpdate(&model.System{ Name: a.dbHealthCheckKey(), Value: currentTime, }) } func (a *App) DBHealthCheckDelete() error { - _, err := a.Srv().Store.System().PermanentDeleteByName(a.dbHealthCheckKey()) + _, err := a.Srv().Store().System().PermanentDeleteByName(a.dbHealthCheckKey()) return err } @@ -160,7 +148,7 @@ func (a *App) dbHealthCheckKey() string { } func (a *App) CheckIntegrity() <-chan model.IntegrityCheckResult { - return a.Srv().Store.CheckIntegrity() + return a.Srv().Store().CheckIntegrity() } func (a *App) SetChannels(ch *Channels) { @@ -172,7 +160,7 @@ func (a *App) SetServer(srv *Server) { } func (a *App) UpdateExpiredDNDStatuses() ([]*model.Status, error) { - return a.Srv().Store.Status().UpdateExpiredDNDStatuses() + return a.Srv().Store().Status().UpdateExpiredDNDStatuses() } // Ensure system service adapter implements `product.SystemService` diff --git a/app/app_iface.go b/app/app_iface.go index 25fbb1694c..ef6b3b4733 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -18,6 +18,7 @@ import ( "reflect" "time" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/audit" "github.com/mattermost/mattermost-server/v6/einterfaces" @@ -74,8 +75,6 @@ type AppIface interface { // overriding attributes set by the user's login provider; otherwise, the name of the offending // field is returned. CheckProviderAttributes(user *model.User, patch *model.UserPatch) string - // ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. - ClientConfigWithComputed() map[string]string // ComputeLastAccessibleFileTime updates cache with CreateAt time of the last accessible file as per the cloud plan's limit. // Use GetLastAccessibleFileTime() to access the result. ComputeLastAccessibleFileTime() error @@ -241,13 +240,11 @@ type AppIface interface { // HasRemote returns whether a given channelID is present in the channel remotes or not. HasRemote(channelID string, remoteID string) (bool, error) // HubRegister registers a connection to a hub. - HubRegister(webConn *WebConn) + HubRegister(webConn *platform.WebConn) // HubUnregister unregisters a connection from a hub. - HubUnregister(webConn *WebConn) + HubUnregister(webConn *platform.WebConn) // InstallPlugin unpacks and installs a plugin but does not enable or activate it. InstallPlugin(pluginFile io.ReadSeeker, replace bool) (*model.Manifest, *model.AppError) - // LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. - LimitedClientConfigWithComputed() map[string]string // LogAuditRec logs an audit record using default LvlAuditCLI. LogAuditRec(rec *audit.Record, err error) // LogAuditRecWithLevel logs an audit record using specified Level. @@ -266,7 +263,7 @@ type AppIface interface { // function is only exposed to sysadmins and the possibility of this edge case is relatively small. MoveChannel(c request.CTX, team *model.Team, channel *model.Channel, user *model.User) *model.AppError // NewWebConn returns a new WebConn instance. - NewWebConn(cfg *WebConnConfig) *WebConn + NewWebConn(cfg *platform.WebConnConfig) *platform.WebConn // NotifySessionsExpired is called periodically from the job server to notify any mobile sessions that have expired. NotifySessionsExpired() error // OverrideIconURLIfEmoji changes the post icon override URL prop, if it has an emoji icon, @@ -284,7 +281,7 @@ type AppIface interface { PermanentDeleteBot(botUserId string) *model.AppError // PopulateWebConnConfig checks if the connection id already exists in the hub, // and if so, accordingly populates the other fields of the webconn. - PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) + PopulateWebConnConfig(s *model.Session, cfg *platform.WebConnConfig, seqVal string) (*platform.WebConnConfig, error) // PostCountsByDuration returns the post counts for the given channels, grouped by day, starting at the given time. // Unless one is specifically itending to omit results from part of the calendar day, it will typically makes the most sense to // use a sinceUnixMillis parameter value as returned by model.GetStartOfDayMillis. @@ -411,8 +408,6 @@ type AppIface interface { AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError AddSamlPublicCertificate(fileData *multipart.FileHeader) *model.AppError AddSessionToCache(session *model.Session) - AddStatusCache(status *model.Status) - AddStatusCacheSkipClusterSend(status *model.Status) AddTeamMember(c request.CTX, teamID, userID string) (*model.TeamMember, *model.AppError) AddTeamMemberByInviteId(c *request.Context, inviteId, userID string) (*model.TeamMember, *model.AppError) AddTeamMemberByToken(c *request.Context, userID, tokenID string) (*model.TeamMember, *model.AppError) @@ -438,7 +433,6 @@ type AppIface interface { AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term string) (model.ChannelList, *model.AppError) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) AutocompleteUsersInTeam(teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) - BroadcastStatus(status *model.Status) BuildPostReactions(ctx request.CTX, postID string) (*[]ReactionImportData, *model.AppError) BuildPushNotificationMessage(c request.CTX, contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError) BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataResponse, *model.AppError) @@ -460,7 +454,7 @@ type AppIface interface { CheckUserMfa(user *model.User, token string) *model.AppError CheckUserPostflightAuthenticationCriteria(user *model.User) *model.AppError CheckUserPreflightAuthenticationCriteria(user *model.User, mfaToken string) *model.AppError - CheckWebConn(userID, connectionID string) *CheckConnResult + CheckWebConn(userID, connectionID string) *platform.CheckConnResult ClearChannelMembersCache(c request.CTX, channelID string) error ClearLatestVersionCache() ClearSessionCacheForAllUsers() @@ -584,7 +578,6 @@ type AppIface interface { GetAllPublicTeams() ([]*model.Team, *model.AppError) GetAllRemoteClusters(filter model.RemoteClusterQueryFilter) ([]*model.RemoteCluster, *model.AppError) GetAllRoles() ([]*model.Role, *model.AppError) - GetAllStatuses() map[string]*model.Status GetAllTeams() ([]*model.Team, *model.AppError) GetAllTeamsPage(offset int, limit int, opts *model.TeamSearch) ([]*model.Team, *model.AppError) GetAllTeamsPageWithCount(offset int, limit int, opts *model.TeamSearch) (*model.TeamsWithCount, *model.AppError) @@ -661,7 +654,7 @@ type AppIface interface { GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) GetGroupsByUserId(userID string) ([]*model.Group, *model.AppError) - GetHubForUserId(userID string) *Hub + GetHubForUserId(userID string) *platform.Hub GetIncomingWebhook(hookID string) (*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPage(teamID string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPageByUser(teamID string, userID string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) @@ -772,7 +765,6 @@ type AppIface interface { GetSiteURL() string GetStatus(userID string) (*model.Status, *model.AppError) GetStatusFromCache(userID string) *model.Status - GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) GetSystemBot() (*model.Bot, *model.AppError) GetTeam(teamID string) (*model.Team, *model.AppError) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) @@ -910,7 +902,6 @@ type AppIface interface { MigrateIdLDAP(toAttribute string) *model.AppError MoveCommand(team *model.Team, command *model.Command) *model.AppError MoveFile(oldPath, newPath string) *model.AppError - NewClusterDiscoveryService() *ClusterDiscoveryService NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API Notification() einterfaces.NotificationInterface NotificationsLog() *mlog.Logger @@ -995,7 +986,6 @@ type AppIface interface { SanitizeTeams(session model.Session, teams []*model.Team) []*model.Team SaveAdminNotification(userId string, notifyData *model.NotifyAdminToUpgradeRequest) *model.AppError SaveAdminNotifyData(data *model.NotifyAdminData) (*model.NotifyAdminData, *model.AppError) - SaveAndBroadcastStatus(status *model.Status) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) diff --git a/app/app_test.go b/app/app_test.go index 2a47e03b6e..9f4d2fa0a9 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -41,7 +41,7 @@ func TestUnitUpdateConfig(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -254,19 +254,19 @@ func TestDBHealthCheckWriteAndDelete(t *testing.T) { expectedKey := "health_check_" + th.App.GetClusterId() assert.Equal(t, expectedKey, th.App.dbHealthCheckKey()) - _, err := th.App.Srv().Store.System().GetByName(expectedKey) + _, err := th.App.Srv().Store().System().GetByName(expectedKey) assert.Error(t, err) err = th.App.DBHealthCheckWrite() assert.NoError(t, err) - systemVal, err := th.App.Srv().Store.System().GetByName(expectedKey) + systemVal, err := th.App.Srv().Store().System().GetByName(expectedKey) assert.NoError(t, err) assert.NotNil(t, systemVal) err = th.App.DBHealthCheckDelete() assert.NoError(t, err) - _, err = th.App.Srv().Store.System().GetByName(expectedKey) + _, err = th.App.Srv().Store().System().GetByName(expectedKey) assert.Error(t, err) } diff --git a/app/audit.go b/app/audit.go index e0e471c75e..0311e596a0 100644 --- a/app/audit.go +++ b/app/audit.go @@ -24,7 +24,7 @@ var ( ) func (a *App) GetAudits(userID string, limit int) (model.Audits, *model.AppError) { - audits, err := a.Srv().Store.Audit().Get(userID, 0, limit) + audits, err := a.Srv().Store().Audit().Get(userID, 0, limit) if err != nil { var outErr *store.ErrOutOfBounds switch { @@ -38,7 +38,7 @@ func (a *App) GetAudits(userID string, limit int) (model.Audits, *model.AppError } func (a *App) GetAuditsPage(userID string, page int, perPage int) (model.Audits, *model.AppError) { - audits, err := a.Srv().Store.Audit().Get(userID, page*perPage, perPage) + audits, err := a.Srv().Store().Audit().Get(userID, page*perPage, perPage) if err != nil { var outErr *store.ErrOutOfBounds switch { diff --git a/app/authentication.go b/app/authentication.go index 6e23d3ea84..f304c99d19 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -65,7 +65,7 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa } if err := users.CheckUserPassword(user, password); err != nil { - if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr) } @@ -84,7 +84,7 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa // If the mfaToken is not set, we assume the client used this as a pre-flight request to query the server // about the MFA state of the user in question if mfaToken != "" { - if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr) } } @@ -94,7 +94,7 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa return err } - if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { + if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { return model.NewAppError("CheckPasswordAndAllCriteria", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr) } @@ -114,7 +114,7 @@ func (a *App) DoubleCheckPassword(user *model.User, password string) *model.AppE } if err := users.CheckUserPassword(user, password); err != nil { - if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { + if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, user.FailedAttempts+1); passErr != nil { return model.NewAppError("DoubleCheckPassword", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr) } @@ -129,7 +129,7 @@ func (a *App) DoubleCheckPassword(user *model.User, password string) *model.AppE } } - if passErr := a.Srv().Store.User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { + if passErr := a.Srv().Store().User().UpdateFailedPasswordAttempts(user.Id, 0); passErr != nil { return model.NewAppError("DoubleCheckPassword", "app.user.update_failed_pwd_attempts.app_error", nil, "", http.StatusInternalServerError).Wrap(passErr) } @@ -207,7 +207,7 @@ func (a *App) CheckUserMfa(user *model.User, token string) *model.AppError { return model.NewAppError("CheckUserMfa", "mfa.mfa_disabled.app_error", nil, "", http.StatusNotImplemented) } - ok, err := mfa.New(a.Srv().Store.User()).ValidateToken(user.MfaSecret, token) + ok, err := mfa.New(a.Srv().Store().User()).ValidateToken(user.MfaSecret, token) if err != nil { return model.NewAppError("CheckUserMfa", "mfa.validate_token.authenticate.app_error", nil, "", http.StatusBadRequest).Wrap(err) } diff --git a/app/authorization.go b/app/authorization.go index 9945d5d6ce..5cb220c154 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -100,7 +100,7 @@ func (a *App) SessionHasPermissionToChannel(c request.CTX, session model.Session return false } - ids, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(session.UserId, true, true) + ids, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(session.UserId, true, true) var channelRoles []string if err == nil { @@ -144,7 +144,7 @@ func (a *App) SessionHasPermissionToChannels(c request.CTX, session model.Sessio return true } - ids, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(session.UserId, true, true) + ids, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(session.UserId, true, true) var channelRoles []string uniqueRoles := make(map[string]bool) @@ -192,7 +192,7 @@ func (a *App) SessionHasPermissionToChannels(c request.CTX, session model.Sessio } func (a *App) SessionHasPermissionToGroup(session model.Session, groupID string, permission *model.Permission) bool { - groupMember, err := a.Srv().Store.Group().GetMember(groupID, session.UserId) + groupMember, err := a.Srv().Store().Group().GetMember(groupID, session.UserId) // don't reject immediately on ErrNoRows error because there's further authz logic below for non-groupmembers if err != nil && !errors.Is(err, sql.ErrNoRows) { return false @@ -211,14 +211,14 @@ func (a *App) SessionHasPermissionToGroup(session model.Session, groupID string, } func (a *App) SessionHasPermissionToChannelByPost(session model.Session, postID string, permission *model.Permission) bool { - if channelMember, err := a.Srv().Store.Channel().GetMemberForPost(postID, session.UserId); err == nil { + if channelMember, err := a.Srv().Store().Channel().GetMemberForPost(postID, session.UserId); err == nil { if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) { return true } } - if channel, err := a.Srv().Store.Channel().GetForPost(postID); err == nil { + if channel, err := a.Srv().Store().Channel().GetForPost(postID); err == nil { if channel.TeamId != "" { return a.SessionHasPermissionToTeam(session, channel.TeamId, permission) } @@ -316,13 +316,13 @@ func (a *App) HasPermissionToChannel(c request.CTX, askingUserId string, channel } func (a *App) HasPermissionToChannelByPost(askingUserId string, postID string, permission *model.Permission) bool { - if channelMember, err := a.Srv().Store.Channel().GetMemberForPost(postID, askingUserId); err == nil { + if channelMember, err := a.Srv().Store().Channel().GetMemberForPost(postID, askingUserId); err == nil { if a.RolesGrantPermission(channelMember.GetRoles(), permission.Id) { return true } } - if channel, err := a.Srv().Store.Channel().GetForPost(postID); err == nil { + if channel, err := a.Srv().Store().Channel().GetForPost(postID); err == nil { return a.HasPermissionToTeam(askingUserId, channel.TeamId, permission) } diff --git a/app/authorization_test.go b/app/authorization_test.go index 9d3cc45264..7e66d29f89 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -87,19 +87,19 @@ func TestSessionHasPermissionToChannel(t *testing.T) { mockStore := mocks.Store{} mockChannelStore := mocks.ChannelStore{} mockChannelStore.On("Get", mock.Anything, mock.Anything).Return(nil, fmt.Errorf("arbitrary error")) - mockChannelStore.On("GetAllChannelMembersForUser", mock.Anything, mock.Anything, mock.Anything).Return(th.App.Srv().Store.Channel().GetAllChannelMembersForUser(th.BasicUser.Id, false, false)) + mockChannelStore.On("GetAllChannelMembersForUser", mock.Anything, mock.Anything, mock.Anything).Return(th.App.Srv().Store().Channel().GetAllChannelMembersForUser(th.BasicUser.Id, false, false)) mockChannelStore.On("ClearCaches").Return() mockStore.On("Channel").Return(&mockChannelStore) - mockStore.On("FileInfo").Return(th.App.Srv().Store.FileInfo()) - mockStore.On("License").Return(th.App.Srv().Store.License()) - mockStore.On("Post").Return(th.App.Srv().Store.Post()) - mockStore.On("Role").Return(th.App.Srv().Store.Role()) - mockStore.On("System").Return(th.App.Srv().Store.System()) - mockStore.On("Team").Return(th.App.Srv().Store.Team()) - mockStore.On("User").Return(th.App.Srv().Store.User()) - mockStore.On("Webhook").Return(th.App.Srv().Store.Webhook()) + mockStore.On("FileInfo").Return(th.App.Srv().Store().FileInfo()) + mockStore.On("License").Return(th.App.Srv().Store().License()) + mockStore.On("Post").Return(th.App.Srv().Store().Post()) + mockStore.On("Role").Return(th.App.Srv().Store().Role()) + mockStore.On("System").Return(th.App.Srv().Store().System()) + mockStore.On("Team").Return(th.App.Srv().Store().Team()) + mockStore.On("User").Return(th.App.Srv().Store().User()) + mockStore.On("Webhook").Return(th.App.Srv().Store().Webhook()) mockStore.On("Close").Return(nil) - th.App.Srv().Store = &mockStore + th.App.Srv().SetStore(&mockStore) // If there's an error returned from the GetChannel call the code should continue to cascade and since there // are no session level permissions in this test case, the permission should be denied. diff --git a/app/auto_responder.go b/app/auto_responder.go index ae12b93e60..e803992348 100644 --- a/app/auto_responder.go +++ b/app/auto_responder.go @@ -15,7 +15,7 @@ import ( func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) (bool, error) { y, m, d := model.GetTimeForMillis(createdAt).Date() since := model.GetMillisForTime(time.Date(y, m, d, 0, 0, 0, 0, time.UTC)) - return a.Srv().Store.Post().HasAutoResponsePostByUserSince( + return a.Srv().Store().Post().HasAutoResponsePostByUserSince( model.GetPostsSinceOptions{ChannelId: channelId, Time: since}, userId, ) diff --git a/app/bot.go b/app/bot.go index 4efad7f8df..3feee4550e 100644 --- a/app/bot.go +++ b/app/bot.go @@ -109,7 +109,7 @@ func (a *App) CreateBot(c request.CTX, bot *model.Bot) (*model.Bot, *model.AppEr return nil, vErr } - user, nErr := a.Srv().Store.User().Save(model.UserFromBot(bot)) + user, nErr := a.Srv().Store().User().Save(model.UserFromBot(bot)) if nErr != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -133,9 +133,9 @@ func (a *App) CreateBot(c request.CTX, bot *model.Bot) (*model.Bot, *model.AppEr } bot.UserId = user.Id - savedBot, nErr := a.Srv().Store.Bot().Save(bot) + savedBot, nErr := a.Srv().Store().Bot().Save(bot) if nErr != nil { - a.Srv().Store.User().PermanentDelete(bot.UserId) + a.Srv().Store().User().PermanentDelete(bot.UserId) var appErr *model.AppError switch { case errors.As(nErr, &appErr): // in case we haven't converted to plain error. @@ -146,7 +146,7 @@ func (a *App) CreateBot(c request.CTX, bot *model.Bot) (*model.Bot, *model.AppEr } // Get the owner of the bot, if one exists. If not, don't send a message - ownerUser, err := a.Srv().Store.User().Get(context.Background(), bot.OwnerId) + ownerUser, err := a.Srv().Store().User().Get(context.Background(), bot.OwnerId) var nfErr *store.ErrNotFound if err != nil && !errors.As(err, &nfErr) { return nil, model.NewAppError("CreateBot", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -244,7 +244,7 @@ func (a *App) getOrCreateBot(botDef *model.Bot) (*model.Bot, *model.AppError) { } // cannot find this bot user, save the user - user, nErr := a.Srv().Store.User().Save(model.UserFromBot(botDef)) + user, nErr := a.Srv().Store().User().Save(model.UserFromBot(botDef)) if nErr != nil { var appError *model.AppError var invErr *store.ErrInvalidInput @@ -269,9 +269,9 @@ func (a *App) getOrCreateBot(botDef *model.Bot) (*model.Bot, *model.AppError) { botDef.UserId = user.Id //save the bot - savedBot, nErr := a.Srv().Store.Bot().Save(botDef) + savedBot, nErr := a.Srv().Store().Bot().Save(botDef) if nErr != nil { - a.Srv().Store.User().PermanentDelete(savedBot.UserId) + a.Srv().Store().User().PermanentDelete(savedBot.UserId) var nAppErr *model.AppError switch { case errors.As(nErr, &nAppErr): // in case we haven't converted to plain error. @@ -309,7 +309,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, bot.Patch(botPatch) - user, nErr := a.Srv().Store.User().Get(context.Background(), botUserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), botUserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -326,7 +326,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, user.Email = patchedUser.Email user.FirstName = patchedUser.FirstName - userUpdate, nErr := a.Srv().Store.User().Update(user, true) + userUpdate, nErr := a.Srv().Store().User().Update(user, true) if nErr != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -350,7 +350,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, ruser := userUpdate.New a.sendUpdatedUserEvent(*ruser) - bot, nErr = a.Srv().Store.Bot().Update(bot) + bot, nErr = a.Srv().Store().Bot().Update(bot) if nErr != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -368,7 +368,7 @@ func (a *App) PatchBot(botUserId string, botPatch *model.BotPatch) (*model.Bot, // GetBot returns the given bot. func (a *App) GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model.AppError) { - bot, err := a.Srv().Store.Bot().Get(botUserId, includeDeleted) + bot, err := a.Srv().Store().Bot().Get(botUserId, includeDeleted) if err != nil { var nfErr *store.ErrNotFound switch { @@ -383,7 +383,7 @@ func (a *App) GetBot(botUserId string, includeDeleted bool) (*model.Bot, *model. // GetBots returns the requested page of bots. func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppError) { - bots, err := a.Srv().Store.Bot().GetAll(options) + bots, err := a.Srv().Store().Bot().GetAll(options) if err != nil { return nil, model.NewAppError("GetBots", "app.bot.getbots.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -392,7 +392,7 @@ func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppEr // UpdateBotActive marks a bot as active or inactive, along with its corresponding user. func (a *App) UpdateBotActive(c request.CTX, botUserId string, active bool) (*model.Bot, *model.AppError) { - user, nErr := a.Srv().Store.User().Get(context.Background(), botUserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), botUserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -407,7 +407,7 @@ func (a *App) UpdateBotActive(c request.CTX, botUserId string, active bool) (*mo return nil, err } - bot, nErr := a.Srv().Store.Bot().Get(botUserId, true) + bot, nErr := a.Srv().Store().Bot().Get(botUserId, true) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -428,7 +428,7 @@ func (a *App) UpdateBotActive(c request.CTX, botUserId string, active bool) (*mo } if changed { - bot, nErr = a.Srv().Store.Bot().Update(bot) + bot, nErr = a.Srv().Store().Bot().Update(bot) if nErr != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -448,7 +448,7 @@ func (a *App) UpdateBotActive(c request.CTX, botUserId string, active bool) (*mo // PermanentDeleteBot permanently deletes a bot and its corresponding user. func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { - if err := a.Srv().Store.Bot().PermanentDelete(botUserId); err != nil { + if err := a.Srv().Store().Bot().PermanentDelete(botUserId); err != nil { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): @@ -458,7 +458,7 @@ func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { } } - if err := a.Srv().Store.User().PermanentDelete(botUserId); err != nil { + if err := a.Srv().Store().User().PermanentDelete(botUserId); err != nil { return model.NewAppError("PermanentDeleteBot", "app.user.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -467,7 +467,7 @@ func (a *App) PermanentDeleteBot(botUserId string) *model.AppError { // UpdateBotOwner changes a bot's owner to the given value. func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError) { - bot, err := a.Srv().Store.Bot().Get(botUserId, true) + bot, err := a.Srv().Store().Bot().Get(botUserId, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -480,7 +480,7 @@ func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.A bot.OwnerId = newOwnerId - bot, err = a.Srv().Store.Bot().Update(bot) + bot, err = a.Srv().Store().Bot().Update(bot) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -644,7 +644,7 @@ func (a *App) getDisableBotSysadminMessage(user *model.User, userBots model.BotL // ConvertUserToBot converts a user to bot. func (a *App) ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError) { - bot, err := a.Srv().Store.Bot().Save(model.BotFromUser(user)) + bot, err := a.Srv().Store().Bot().Save(model.BotFromUser(user)) if err != nil { var appErr *model.AppError switch { diff --git a/app/channel.go b/app/channel.go index e7c0826c9a..8da9b638f9 100644 --- a/app/channel.go +++ b/app/channel.go @@ -81,7 +81,7 @@ func (a *App) JoinDefaultChannels(c request.CTX, teamID string, user *model.User var requestor *model.User var nErr error if userRequestorId != "" { - requestor, nErr = a.Srv().Store.User().Get(context.Background(), userRequestorId) + requestor, nErr = a.Srv().Store().User().Get(context.Background(), userRequestorId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -94,7 +94,7 @@ func (a *App) JoinDefaultChannels(c request.CTX, teamID string, user *model.User } for _, channelName := range a.DefaultChannelNames(c) { - channel, channelErr := a.Srv().Store.Channel().GetByName(teamID, channelName, true) + channel, channelErr := a.Srv().Store().Channel().GetByName(teamID, channelName, true) if channelErr != nil { c.Logger().Warn("No default channel with this name", mlog.String("channelName", channelName), mlog.String("teamID", teamID), mlog.Err(channelErr)) continue @@ -113,8 +113,8 @@ func (a *App) JoinDefaultChannels(c request.CTX, teamID string, user *model.User NotifyProps: model.GetDefaultChannelNotifyProps(), } - _, nErr = a.Srv().Store.Channel().SaveMember(cm) - if histErr := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); histErr != nil { + _, nErr = a.Srv().Store().Channel().SaveMember(cm) + if histErr := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); histErr != nil { return model.NewAppError("JoinDefaultChannels", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(histErr) } @@ -242,7 +242,7 @@ func (a *App) RenameChannel(c request.CTX, channel *model.Channel, newChannelNam func (a *App) CreateChannel(c request.CTX, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) { channel.DisplayName = strings.TrimSpace(channel.DisplayName) - sc, nErr := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) + sc, nErr := a.Srv().Store().Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam) if nErr != nil { var invErr *store.ErrInvalidInput var cErr *store.ErrConflict @@ -270,7 +270,7 @@ func (a *App) CreateChannel(c request.CTX, channel *model.Channel, addMember boo } if addMember { - user, nErr := a.Srv().Store.User().Get(context.Background(), channel.CreatorId) + user, nErr := a.Srv().Store().User().Get(context.Background(), channel.CreatorId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -290,7 +290,7 @@ func (a *App) CreateChannel(c request.CTX, channel *model.Channel, addMember boo NotifyProps: model.GetDefaultChannelNotifyProps(), } - if _, nErr := a.Srv().Store.Channel().SaveMember(cm); nErr != nil { + if _, nErr := a.Srv().Store().Channel().SaveMember(cm); nErr != nil { var appErr *model.AppError var cErr *store.ErrConflict switch { @@ -306,7 +306,7 @@ func (a *App) CreateChannel(c request.CTX, channel *model.Channel, addMember boo } } - if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(channel.CreatorId, sc.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(channel.CreatorId, sc.Id, model.GetMillis()); err != nil { return nil, model.NewAppError("CreateChannel", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -416,7 +416,7 @@ func (a *App) handleCreationEvent(c request.CTX, userID, otherUserID string, cha } func (a *App) createDirectChannel(c request.CTX, userID string, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { - users, err := a.Srv().Store.User().GetMany(context.Background(), []string{userID, otherUserID}) + users, err := a.Srv().Store().User().GetMany(context.Background(), []string{userID, otherUserID}) if err != nil { return nil, model.NewAppError("CreateDirectChannel", "api.channel.create_direct_channel.invalid_user.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -449,7 +449,7 @@ func (a *App) createDirectChannel(c request.CTX, userID string, otherUserID stri } func (a *App) createDirectChannelWithUser(c request.CTX, user, otherUser *model.User, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) { - channel, nErr := a.Srv().Store.Channel().CreateDirectChannel(user, otherUser, channelOptions...) + channel, nErr := a.Srv().Store().Channel().CreateDirectChannel(user, otherUser, channelOptions...) if nErr != nil { var invErr *store.ErrInvalidInput var cErr *store.ErrConflict @@ -481,11 +481,11 @@ func (a *App) createDirectChannelWithUser(c request.CTX, user, otherUser *model. } } - if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { return nil, model.NewAppError("createDirectChannelWithUser", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } if user.Id != otherUser.Id { - if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(otherUser.Id, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(otherUser.Id, channel.Id, model.GetMillis()); err != nil { return nil, model.NewAppError("createDirectChannelWithUser", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -539,7 +539,7 @@ func (a *App) createGroupChannel(c request.CTX, userIDs []string) (*model.Channe return nil, model.NewAppError("CreateGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } - users, err := a.Srv().Store.User().GetProfileByIds(context.Background(), userIDs, nil, true) + users, err := a.Srv().Store().User().GetProfileByIds(context.Background(), userIDs, nil, true) if err != nil { return nil, model.NewAppError("createGroupChannel", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -554,7 +554,7 @@ func (a *App) createGroupChannel(c request.CTX, userIDs []string) (*model.Channe Type: model.ChannelTypeGroup, } - channel, nErr := a.Srv().Store.Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam) + channel, nErr := a.Srv().Store().Channel().Save(group, *a.Config().TeamSettings.MaxChannelsPerTeam) if nErr != nil { var invErr *store.ErrInvalidInput var cErr *store.ErrConflict @@ -590,7 +590,7 @@ func (a *App) createGroupChannel(c request.CTX, userIDs []string) (*model.Channe SchemeUser: !user.IsGuest(), } - if _, nErr = a.Srv().Store.Channel().SaveMember(cm); nErr != nil { + if _, nErr = a.Srv().Store().Channel().SaveMember(cm); nErr != nil { var appErr *model.AppError var cErr *store.ErrConflict switch { @@ -605,7 +605,7 @@ func (a *App) createGroupChannel(c request.CTX, userIDs []string) (*model.Channe return nil, model.NewAppError("createGroupChannel", "app.channel.create_direct_channel.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } } - if err := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); err != nil { return nil, model.NewAppError("createGroupChannel", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -618,7 +618,7 @@ func (a *App) GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel, return nil, model.NewAppError("GetGroupChannel", "api.channel.create_group.bad_size.app_error", nil, "", http.StatusBadRequest) } - users, err := a.Srv().Store.User().GetProfileByIds(context.Background(), userIDs, nil, true) + users, err := a.Srv().Store().User().GetProfileByIds(context.Background(), userIDs, nil, true) if err != nil { return nil, model.NewAppError("GetGroupChannel", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -637,7 +637,7 @@ func (a *App) GetGroupChannel(c request.CTX, userIDs []string) (*model.Channel, // UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event. func (a *App) UpdateChannel(c request.CTX, channel *model.Channel) (*model.Channel, *model.AppError) { - _, err := a.Srv().Store.Channel().Update(channel) + _, err := a.Srv().Store().Channel().Update(channel) if err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -651,7 +651,7 @@ func (a *App) UpdateChannel(c request.CTX, channel *model.Channel) (*model.Chann } } - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelUpdated, "", channel.Id, "", nil, "") channelJSON, jsonErr := json.Marshal(channel) @@ -722,7 +722,7 @@ func (a *App) UpdateChannelPrivacy(c request.CTX, oldChannel *model.Channel, use return channel, err } - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) messageWs := model.NewWebSocketEvent(model.WebsocketEventChannelConverted, channel.TeamId, "", "", nil, "") messageWs.Add("channel_id", channel.Id) @@ -773,11 +773,11 @@ func (a *App) RestoreChannel(c request.CTX, channel *model.Channel, userID strin return nil, model.NewAppError("restoreChannel", "api.channel.restore_channel.restored.app_error", nil, "", http.StatusBadRequest) } - if err := a.Srv().Store.Channel().Restore(channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().Channel().Restore(channel.Id, model.GetMillis()); err != nil { return nil, model.NewAppError("RestoreChannel", "app.channel.restore.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } channel.DeleteAt = 0 - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) message := model.NewWebSocketEvent(model.WebsocketEventChannelRestored, channel.TeamId, "", "", nil, "") message.Add("channel_id", channel.Id) @@ -786,7 +786,7 @@ func (a *App) RestoreChannel(c request.CTX, channel *model.Channel, userID strin var user *model.User if userID != "" { var nErr error - user, nErr = a.Srv().Store.User().Get(context.Background(), userID) + user, nErr = a.Srv().Store().User().Get(context.Background(), userID) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -1094,7 +1094,7 @@ func (a *App) PatchChannelModerationsForChannel(c request.CTX, channel *model.Ch } cErr := a.forEachChannelMember(c, channel.Id, func(channelMember model.ChannelMember) error { - a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(channelMember.UserId) + a.Srv().Store().Channel().InvalidateAllChannelMembersForUser(channelMember.UserId) return nil }) if cErr != nil { @@ -1261,7 +1261,7 @@ func (a *App) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]stri filteredProps[model.IgnoreChannelMentionsNotifyProp] = ignoreChannelMentions } - member, err := a.Srv().Store.Channel().UpdateMemberNotifyProps(channelID, userID, filteredProps) + member, err := a.Srv().Store().Channel().UpdateMemberNotifyProps(channelID, userID, filteredProps) if err != nil { var appErr *model.AppError var nfErr *store.ErrNotFound @@ -1291,7 +1291,7 @@ func (a *App) UpdateChannelMemberNotifyProps(c request.CTX, data map[string]stri } func (a *App) updateChannelMember(c request.CTX, member *model.ChannelMember) (*model.ChannelMember, *model.AppError) { - member, err := a.Srv().Store.Channel().UpdateMember(member) + member, err := a.Srv().Store().Channel().UpdateMember(member) if err != nil { var appErr *model.AppError var nfErr *store.ErrNotFound @@ -1324,13 +1324,13 @@ func (a *App) DeleteChannel(c request.CTX, channel *model.Channel, userID string ohc := make(chan store.StoreResult, 1) go func() { - webhooks, err := a.Srv().Store.Webhook().GetIncomingByChannel(channel.Id) + webhooks, err := a.Srv().Store().Webhook().GetIncomingByChannel(channel.Id) ihc <- store.StoreResult{Data: webhooks, NErr: err} close(ihc) }() go func() { - outgoingHooks, err := a.Srv().Store.Webhook().GetOutgoingByChannel(channel.Id, -1, -1) + outgoingHooks, err := a.Srv().Store().Webhook().GetOutgoingByChannel(channel.Id, -1, -1) ohc <- store.StoreResult{Data: outgoingHooks, NErr: err} close(ohc) }() @@ -1338,7 +1338,7 @@ func (a *App) DeleteChannel(c request.CTX, channel *model.Channel, userID string var user *model.User if userID != "" { var nErr error - user, nErr = a.Srv().Store.User().Get(context.Background(), userID) + user, nErr = a.Srv().Store().User().Get(context.Background(), userID) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -1415,24 +1415,24 @@ func (a *App) DeleteChannel(c request.CTX, channel *model.Channel, userID string now := model.GetMillis() for _, hook := range incomingHooks { - if err := a.Srv().Store.Webhook().DeleteIncoming(hook.Id, now); err != nil { + if err := a.Srv().Store().Webhook().DeleteIncoming(hook.Id, now); err != nil { c.Logger().Warn("Encountered error deleting incoming webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } - a.invalidateCacheForWebhook(hook.Id) + a.Srv().Platform().InvalidateCacheForWebhook(hook.Id) } for _, hook := range outgoingHooks { - if err := a.Srv().Store.Webhook().DeleteOutgoing(hook.Id, now); err != nil { + if err := a.Srv().Store().Webhook().DeleteOutgoing(hook.Id, now); err != nil { c.Logger().Warn("Encountered error deleting outgoing webhook", mlog.String("hook_id", hook.Id), mlog.Err(err)) } } deleteAt := model.GetMillis() - if err := a.Srv().Store.Channel().Delete(channel.Id, deleteAt); err != nil { + if err := a.Srv().Store().Channel().Delete(channel.Id, deleteAt); err != nil { return model.NewAppError("DeleteChannel", "app.channel.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil, "") message.Add("channel_id", channel.Id) @@ -1447,7 +1447,7 @@ func (a *App) addUserToChannel(c request.CTX, user *model.User, channel *model.C return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user_to_channel.type.app_error", nil, "", http.StatusBadRequest) } - channelMember, nErr := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, user.Id) + channelMember, nErr := a.Srv().Store().Channel().GetMember(context.Background(), channel.Id, user.Id) if nErr != nil { var nfErr *store.ErrNotFound if !errors.As(nErr, &nfErr) { @@ -1484,13 +1484,13 @@ func (a *App) addUserToChannel(c request.CTX, user *model.User, channel *model.C newMember.SchemeAdmin = userShouldBeAdmin } - newMember, nErr = a.Srv().Store.Channel().SaveMember(newMember) + newMember, nErr = a.Srv().Store().Channel().SaveMember(newMember) if nErr != nil { return nil, model.NewAppError("AddUserToChannel", "api.channel.add_user.to.channel.failed.app_error", nil, fmt.Sprintf("failed to add member: %v, user_id: %s, channel_id: %s", nErr, user.Id, channel.Id), http.StatusInternalServerError) } - if nErr := a.Srv().Store.ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); nErr != nil { + if nErr := a.Srv().Store().ChannelMemberHistory().LogJoinEvent(user.Id, channel.Id, model.GetMillis()); nErr != nil { return nil, model.NewAppError("AddUserToChannel", "app.channel_member_history.log_join_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1503,7 +1503,7 @@ func (a *App) addUserToChannel(c request.CTX, user *model.User, channel *model.C // AddUserToChannel adds a user to a given channel. func (a *App) AddUserToChannel(c request.CTX, user *model.User, channel *model.Channel, skipTeamMemberIntegrityCheck bool) (*model.ChannelMember, *model.AppError) { if !skipTeamMemberIntegrityCheck { - teamMember, nErr := a.Srv().Store.Team().GetMember(context.Background(), channel.TeamId, user.Id) + teamMember, nErr := a.Srv().Store().Team().GetMember(context.Background(), channel.TeamId, user.Id) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -1544,7 +1544,7 @@ type ChannelMemberOpts struct { // AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel. func (a *App) AddChannelMember(c request.CTX, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) { - if member, err := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, userID); err != nil { + if member, err := a.Srv().Store().Channel().GetMember(context.Background(), channel.Id, userID); err != nil { var nfErr *store.ErrNotFound if !errors.As(err, &nfErr) { return nil, model.NewAppError("AddChannelMember", "app.channel.get_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -1598,7 +1598,7 @@ func (a *App) AddChannelMember(c request.CTX, userID string, channel *model.Chan func (a *App) AddDirectChannels(c request.CTX, teamID string, user *model.User) *model.AppError { var profiles []*model.User options := &model.UserGetOptions{InTeamId: teamID, Page: 0, PerPage: 100} - profiles, err := a.Srv().Store.User().GetProfiles(options) + profiles, err := a.Srv().Store().User().GetProfiles(options) if err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]any{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) } @@ -1624,7 +1624,7 @@ func (a *App) AddDirectChannels(c request.CTX, teamID string, user *model.User) } } - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { return model.NewAppError("AddDirectChannels", "api.user.add_direct_channels_and_forget.failed.error", map[string]any{"UserId": user.Id, "TeamId": teamID, "Error": err.Error()}, "", http.StatusInternalServerError) } @@ -1632,7 +1632,7 @@ func (a *App) AddDirectChannels(c request.CTX, teamID string, user *model.User) } func (a *App) PostUpdateChannelHeaderMessage(c request.CTX, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelHeaderMessage", "api.channel.post_update_channel_header_message_and_forget.retrieve_user.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1666,7 +1666,7 @@ func (a *App) PostUpdateChannelHeaderMessage(c request.CTX, userID string, chann } func (a *App) PostUpdateChannelPurposeMessage(c request.CTX, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1699,7 +1699,7 @@ func (a *App) PostUpdateChannelPurposeMessage(c request.CTX, userID string, chan } func (a *App) PostUpdateChannelDisplayNameMessage(c request.CTX, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) if err != nil { return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.retrieve_user.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1730,7 +1730,7 @@ func (a *App) GetChannel(c request.CTX, channelID string) (*model.Channel, *mode } func (s *Server) getChannel(c request.CTX, channelID string) (*model.Channel, *model.AppError) { - channel, err := s.Store.Channel().Get(channelID, true) + channel, err := s.Store().Channel().Get(channelID, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1744,7 +1744,7 @@ func (s *Server) getChannel(c request.CTX, channelID string) (*model.Channel, *m } func (a *App) GetChannels(c request.CTX, channelIDs []string) ([]*model.Channel, *model.AppError) { - channels, err := a.Srv().Store.Channel().GetMany(channelIDs, true) + channels, err := a.Srv().Store().Channel().GetMany(channelIDs, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1762,9 +1762,9 @@ func (a *App) GetChannelByName(c request.CTX, channelName, teamID string, includ var err error if includeDeleted { - channel, err = a.Srv().Store.Channel().GetByNameIncludeDeleted(teamID, channelName, false) + channel, err = a.Srv().Store().Channel().GetByNameIncludeDeleted(teamID, channelName, false) } else { - channel, err = a.Srv().Store.Channel().GetByName(teamID, channelName, false) + channel, err = a.Srv().Store().Channel().GetByName(teamID, channelName, false) } if err != nil { @@ -1781,7 +1781,7 @@ func (a *App) GetChannelByName(c request.CTX, channelName, teamID string, includ } func (a *App) GetChannelsByNames(c request.CTX, channelNames []string, teamID string) ([]*model.Channel, *model.AppError) { - channels, err := a.Srv().Store.Channel().GetByNames(teamID, channelNames, true) + channels, err := a.Srv().Store().Channel().GetByNames(teamID, channelNames, true) if err != nil { return nil, model.NewAppError("GetChannelsByNames", "app.channel.get_by_name.existing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1791,7 +1791,7 @@ func (a *App) GetChannelsByNames(c request.CTX, channelNames []string, teamID st func (a *App) GetChannelByNameForTeamName(c request.CTX, channelName, teamName string, includeDeleted bool) (*model.Channel, *model.AppError) { var team *model.Team - team, err := a.Srv().Store.Team().GetByName(teamName) + team, err := a.Srv().Store().Team().GetByName(teamName) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1806,9 +1806,9 @@ func (a *App) GetChannelByNameForTeamName(c request.CTX, channelName, teamName s var nErr error if includeDeleted { - result, nErr = a.Srv().Store.Channel().GetByNameIncludeDeleted(team.Id, channelName, false) + result, nErr = a.Srv().Store().Channel().GetByNameIncludeDeleted(team.Id, channelName, false) } else { - result, nErr = a.Srv().Store.Channel().GetByName(team.Id, channelName, false) + result, nErr = a.Srv().Store().Channel().GetByName(team.Id, channelName, false) } if nErr != nil { @@ -1825,7 +1825,7 @@ func (a *App) GetChannelByNameForTeamName(c request.CTX, channelName, teamName s } func (s *Server) getChannelsForTeamForUser(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts) (model.ChannelList, *model.AppError) { - list, err := s.Store.Channel().GetChannels(teamID, userID, opts) + list, err := s.Store().Channel().GetChannels(teamID, userID, opts) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1844,7 +1844,7 @@ func (a *App) GetChannelsForTeamForUser(c request.CTX, teamID string, userID str } func (a *App) GetChannelsForTeamForUserWithCursor(c request.CTX, teamID string, userID string, opts *model.ChannelSearchOpts, afterChannelID string) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetChannelsWithCursor(teamID, userID, opts, afterChannelID) + list, err := a.Srv().Store().Channel().GetChannelsWithCursor(teamID, userID, opts, afterChannelID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1859,7 +1859,7 @@ func (a *App) GetChannelsForTeamForUserWithCursor(c request.CTX, teamID string, } func (a *App) GetChannelsForUser(c request.CTX, userID string, includeDeleted bool, lastDeleteAt, pageSize int, fromChannelID string) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetChannelsByUser(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID) + list, err := a.Srv().Store().Channel().GetChannelsByUser(userID, includeDeleted, lastDeleteAt, pageSize, fromChannelID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1884,7 +1884,7 @@ func (a *App) GetAllChannels(c request.CTX, page, perPage int, opts model.Channe ExcludePolicyConstrained: opts.ExcludePolicyConstrained, IncludePolicyID: opts.IncludePolicyID, } - channels, err := a.Srv().Store.Channel().GetAllChannels(page*perPage, perPage, storeOpts) + channels, err := a.Srv().Store().Channel().GetAllChannels(page*perPage, perPage, storeOpts) if err != nil { return nil, model.NewAppError("GetAllChannels", "app.channel.get_all_channels.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1901,7 +1901,7 @@ func (a *App) GetAllChannelsCount(c request.CTX, opts model.ChannelSearchOpts) ( NotAssociatedToGroup: opts.NotAssociatedToGroup, IncludeDeleted: opts.IncludeDeleted, } - count, err := a.Srv().Store.Channel().GetAllChannelsCount(storeOpts) + count, err := a.Srv().Store().Channel().GetAllChannelsCount(storeOpts) if err != nil { return 0, model.NewAppError("GetAllChannelsCount", "app.channel.get_all_channels_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1910,7 +1910,7 @@ func (a *App) GetAllChannelsCount(c request.CTX, opts model.ChannelSearchOpts) ( } func (a *App) GetDeletedChannels(c request.CTX, teamID string, offset int, limit int, userID string) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetDeleted(teamID, offset, limit, userID) + list, err := a.Srv().Store().Channel().GetDeleted(teamID, offset, limit, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1925,7 +1925,7 @@ func (a *App) GetDeletedChannels(c request.CTX, teamID string, offset int, limit } func (a *App) GetChannelsUserNotIn(c request.CTX, teamID string, userID string, offset int, limit int) (model.ChannelList, *model.AppError) { - channels, err := a.Srv().Store.Channel().GetMoreChannels(teamID, userID, offset, limit) + channels, err := a.Srv().Store().Channel().GetMoreChannels(teamID, userID, offset, limit) if err != nil { return nil, model.NewAppError("GetChannelsUserNotIn", "app.channel.get_more_channels.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1933,7 +1933,7 @@ func (a *App) GetChannelsUserNotIn(c request.CTX, teamID string, userID string, } func (a *App) GetPublicChannelsByIdsForTeam(c request.CTX, teamID string, channelIDs []string) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetPublicChannelsByIdsForTeam(teamID, channelIDs) + list, err := a.Srv().Store().Channel().GetPublicChannelsByIdsForTeam(teamID, channelIDs) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1948,7 +1948,7 @@ func (a *App) GetPublicChannelsByIdsForTeam(c request.CTX, teamID string, channe } func (a *App) GetPublicChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetPublicChannelsForTeam(teamID, offset, limit) + list, err := a.Srv().Store().Channel().GetPublicChannelsForTeam(teamID, offset, limit) if err != nil { return nil, model.NewAppError("GetPublicChannelsForTeam", "app.channel.get_public_channels.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1957,7 +1957,7 @@ func (a *App) GetPublicChannelsForTeam(c request.CTX, teamID string, offset int, } func (a *App) GetPrivateChannelsForTeam(c request.CTX, teamID string, offset int, limit int) (model.ChannelList, *model.AppError) { - list, err := a.Srv().Store.Channel().GetPrivateChannelsForTeam(teamID, offset, limit) + list, err := a.Srv().Store().Channel().GetPrivateChannelsForTeam(teamID, offset, limit) if err != nil { return nil, model.NewAppError("GetPrivateChannelsForTeam", "app.channel.get_private_channels.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1970,7 +1970,7 @@ func (a *App) GetChannelMember(c request.CTX, channelID string, userID string) ( } func (s *Server) getChannelMember(c request.CTX, channelID string, userID string) (*model.ChannelMember, *model.AppError) { - channelMember, err := s.Store.Channel().GetMember(c.Context(), channelID, userID) + channelMember, err := s.Store().Channel().GetMember(c.Context(), channelID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1985,7 +1985,7 @@ func (s *Server) getChannelMember(c request.CTX, channelID string, userID string } func (a *App) GetChannelMembersPage(c request.CTX, channelID string, page, perPage int) (model.ChannelMembers, *model.AppError) { - channelMembers, err := a.Srv().Store.Channel().GetMembers(channelID, page*perPage, perPage) + channelMembers, err := a.Srv().Store().Channel().GetMembers(channelID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersPage", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1994,7 +1994,7 @@ func (a *App) GetChannelMembersPage(c request.CTX, channelID string, page, perPa } func (a *App) GetChannelMembersTimezones(c request.CTX, channelID string) ([]string, *model.AppError) { - membersTimezones, err := a.Srv().Store.Channel().GetChannelMembersTimezones(channelID) + membersTimezones, err := a.Srv().Store().Channel().GetChannelMembersTimezones(channelID) if err != nil { return nil, model.NewAppError("GetChannelMembersTimezones", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2011,7 +2011,7 @@ func (a *App) GetChannelMembersTimezones(c request.CTX, channelID string) ([]str } func (a *App) GetChannelMembersByIds(c request.CTX, channelID string, userIDs []string) (model.ChannelMembers, *model.AppError) { - members, err := a.Srv().Store.Channel().GetMembersByIds(channelID, userIDs) + members, err := a.Srv().Store().Channel().GetMembersByIds(channelID, userIDs) if err != nil { return nil, model.NewAppError("GetChannelMembersByIds", "app.channel.get_members_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2020,7 +2020,7 @@ func (a *App) GetChannelMembersByIds(c request.CTX, channelID string, userIDs [] } func (a *App) GetChannelMembersForUser(c request.CTX, teamID string, userID string) (model.ChannelMembers, *model.AppError) { - channelMembers, err := a.Srv().Store.Channel().GetMembersForUser(teamID, userID) + channelMembers, err := a.Srv().Store().Channel().GetMembersForUser(teamID, userID) if err != nil { return nil, model.NewAppError("GetChannelMembersForUser", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2029,7 +2029,7 @@ func (a *App) GetChannelMembersForUser(c request.CTX, teamID string, userID stri } func (a *App) GetChannelMembersForUserWithPagination(c request.CTX, userID string, page, perPage int) ([]*model.ChannelMember, *model.AppError) { - m, err := a.Srv().Store.Channel().GetMembersForUserWithPagination(userID, page, perPage) + m, err := a.Srv().Store().Channel().GetMembersForUserWithPagination(userID, page, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersForUserWithPagination", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2043,7 +2043,7 @@ func (a *App) GetChannelMembersForUserWithPagination(c request.CTX, userID strin } func (a *App) GetChannelMembersWithTeamDataForUserWithPagination(c request.CTX, userID string, page, perPage int) (model.ChannelMembersWithTeamData, *model.AppError) { - m, err := a.Srv().Store.Channel().GetMembersForUserWithPagination(userID, page, perPage) + m, err := a.Srv().Store().Channel().GetMembersForUserWithPagination(userID, page, perPage) if err != nil { return nil, model.NewAppError("GetChannelMembersForUserWithPagination", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2052,7 +2052,7 @@ func (a *App) GetChannelMembersWithTeamDataForUserWithPagination(c request.CTX, } func (a *App) GetChannelMemberCount(c request.CTX, channelID string) (int64, *model.AppError) { - count, err := a.Srv().Store.Channel().GetMemberCount(channelID, true) + count, err := a.Srv().Store().Channel().GetMemberCount(channelID, true) if err != nil { return 0, model.NewAppError("GetChannelMemberCount", "app.channel.get_member_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2061,7 +2061,7 @@ func (a *App) GetChannelMemberCount(c request.CTX, channelID string) (int64, *mo } func (a *App) GetChannelFileCount(c request.CTX, channelID string) (int64, *model.AppError) { - count, err := a.Srv().Store.Channel().GetFileCount(channelID) + count, err := a.Srv().Store().Channel().GetFileCount(channelID) if err != nil { return 0, model.NewAppError("SqlChannelStore.GetFileCount", "app.channel.get_file_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2070,7 +2070,7 @@ func (a *App) GetChannelFileCount(c request.CTX, channelID string) (int64, *mode } func (a *App) GetChannelGuestCount(c request.CTX, channelID string) (int64, *model.AppError) { - count, err := a.Srv().Store.Channel().GetGuestCount(channelID, true) + count, err := a.Srv().Store().Channel().GetGuestCount(channelID, true) if err != nil { return 0, model.NewAppError("SqlChannelStore.GetGuestCount", "app.channel.get_member_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2079,7 +2079,7 @@ func (a *App) GetChannelGuestCount(c request.CTX, channelID string) (int64, *mod } func (a *App) GetChannelPinnedPostCount(c request.CTX, channelID string) (int64, *model.AppError) { - count, err := a.Srv().Store.Channel().GetPinnedPostCount(channelID, true) + count, err := a.Srv().Store().Channel().GetPinnedPostCount(channelID, true) if err != nil { return 0, model.NewAppError("GetChannelPinnedPostCount", "app.channel.get_pinnedpost_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2088,7 +2088,7 @@ func (a *App) GetChannelPinnedPostCount(c request.CTX, channelID string) (int64, } func (a *App) GetChannelCounts(c request.CTX, teamID string, userID string) (*model.ChannelCounts, *model.AppError) { - counts, err := a.Srv().Store.Channel().GetChannelCounts(teamID, userID) + counts, err := a.Srv().Store().Channel().GetChannelCounts(teamID, userID) if err != nil { return nil, model.NewAppError("SqlChannelStore.GetChannelCounts", "app.channel.get_channel_counts.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2097,7 +2097,7 @@ func (a *App) GetChannelCounts(c request.CTX, teamID string, userID string) (*mo } func (a *App) GetChannelUnread(c request.CTX, channelID, userID string) (*model.ChannelUnread, *model.AppError) { - channelUnread, err := a.Srv().Store.Channel().GetChannelUnread(channelID, userID) + channelUnread, err := a.Srv().Store().Channel().GetChannelUnread(channelID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -2119,12 +2119,12 @@ func (a *App) JoinChannel(c request.CTX, channel *model.Channel, userID string) userChan := make(chan store.StoreResult, 1) memberChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) userChan <- store.StoreResult{Data: user, NErr: err} close(userChan) }() go func() { - member, err := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, userID) + member, err := a.Srv().Store().Channel().GetMember(context.Background(), channel.Id, userID) memberChan <- store.StoreResult{Data: member, NErr: err} close(memberChan) }() @@ -2221,21 +2221,21 @@ func (a *App) postJoinTeamMessage(c request.CTX, user *model.User, channel *mode func (a *App) LeaveChannel(c request.CTX, channelID string, userID string) *model.AppError { sc := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv().Store.Channel().Get(channelID, true) + channel, err := a.Srv().Store().Channel().Get(channelID, true) sc <- store.StoreResult{Data: channel, NErr: err} close(sc) }() uc := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) uc <- store.StoreResult{Data: user, NErr: err} close(uc) }() mcc := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv().Store.Channel().GetMemberCount(channelID, false) + count, err := a.Srv().Store().Channel().GetMemberCount(channelID, false) mcc <- store.StoreResult{Data: count, NErr: err} close(mcc) }() @@ -2400,7 +2400,7 @@ func (a *App) postRemoveFromChannelMessage(c request.CTX, removerUserId string, } func (a *App) removeUserFromChannel(c request.CTX, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError { - user, nErr := a.Srv().Store.User().Get(context.Background(), userIDToRemove) + user, nErr := a.Srv().Store().User().Get(context.Background(), userIDToRemove) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -2433,10 +2433,10 @@ func (a *App) removeUserFromChannel(c request.CTX, userIDToRemove string, remove return err } - if err := a.Srv().Store.Channel().RemoveMember(channel.Id, userIDToRemove); err != nil { + if err := a.Srv().Store().Channel().RemoveMember(channel.Id, userIDToRemove); err != nil { return model.NewAppError("removeUserFromChannel", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.ChannelMemberHistory().LogLeaveEvent(userIDToRemove, channel.Id, model.GetMillis()); err != nil { + if err := a.Srv().Store().ChannelMemberHistory().LogLeaveEvent(userIDToRemove, channel.Id, model.GetMillis()); err != nil { return model.NewAppError("removeUserFromChannel", "app.channel_member_history.log_leave_event.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2520,7 +2520,7 @@ func (a *App) RemoveUserFromChannel(c request.CTX, userIDToRemove string, remove func (a *App) GetNumberOfChannelsOnTeam(c request.CTX, teamID string) (int, *model.AppError) { // Get total number of channels on current team - list, err := a.Srv().Store.Channel().GetTeamChannels(teamID) + list, err := a.Srv().Store().Channel().GetTeamChannels(teamID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -2534,7 +2534,7 @@ func (a *App) GetNumberOfChannelsOnTeam(c request.CTX, teamID string) (int, *mod } func (a *App) SetActiveChannel(c request.CTX, userID string, channelID string) *model.AppError { - status, err := a.GetStatus(userID) + status, err := a.Srv().Platform().GetStatus(userID) oldStatus := model.StatusOffline @@ -2549,10 +2549,10 @@ func (a *App) SetActiveChannel(c request.CTX, userID string, channelID string) * status.LastActivityAt = model.GetMillis() } - a.AddStatusCache(status) + a.Srv().Platform().AddStatusCache(status) if status.Status != oldStatus { - a.BroadcastStatus(status) + a.Srv().Platform().BroadcastStatus(status) } return nil @@ -2568,7 +2568,7 @@ func (a *App) IsCRTEnabledForUser(c request.CTX, userID string) bool { } threadsEnabled := appCRT == model.CollapsedThreadsDefaultOn // check if a participant has overridden collapsed threads settings - if preference, err := a.Srv().Store.Preference().Get(userID, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil { + if preference, err := a.Srv().Store().Preference().Get(userID, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled); err == nil { threadsEnabled = preference.Value == "on" } return threadsEnabled @@ -2594,7 +2594,7 @@ func (a *App) MarkChannelAsUnreadFromPost(c request.CTX, postID string, userID s return nil, err } - channelUnread, nErr := a.Srv().Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, unreadMentionsRoot, true) + channelUnread, nErr := a.Srv().Store().Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, unreadMentionsRoot, true) if nErr != nil { return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2630,7 +2630,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID st // In CRT Supported Client: badge on channel only sums mentions in root posts including and below the post that was marked. // In CRT Unsupported Client: badge on channel sums mentions in all posts (root & replies) including and below the post that was marked unread. if post.RootId == "" { - channelUnread, nErr := a.Srv().Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, unreadMentionsRoot, true) + channelUnread, nErr := a.Srv().Store().Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, unreadMentionsRoot, true) if nErr != nil { return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2650,13 +2650,13 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID st return nil, appErr } - channel, nErr := a.Srv().Store.Channel().Get(post.ChannelId, true) + channel, nErr := a.Srv().Store().Channel().Get(post.ChannelId, true) if nErr != nil { return nil, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } if *a.Config().ServiceSettings.ThreadAutoFollow { - threadMembership, mErr := a.Srv().Store.Thread().GetMembershipForUser(user.Id, threadId) + threadMembership, mErr := a.Srv().Store().Thread().GetMembershipForUser(user.Id, threadId) var errNotFound *store.ErrNotFound if mErr != nil && !errors.As(mErr, &errNotFound) { return nil, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(mErr) @@ -2670,7 +2670,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID st UpdateViewedTimestamp: false, UpdateParticipants: false, } - threadMembership, mErr = a.Srv().Store.Thread().MaintainMembership(user.Id, threadId, opts) + threadMembership, mErr = a.Srv().Store().Thread().MaintainMembership(user.Id, threadId, opts) if mErr != nil { return nil, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(mErr) } @@ -2682,11 +2682,11 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID st if appErr != nil { return nil, appErr } - threadMembership, mErr = a.Srv().Store.Thread().UpdateMembership(threadMembership) + threadMembership, mErr = a.Srv().Store().Thread().UpdateMembership(threadMembership) if mErr != nil { return nil, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(mErr) } - thread, mErr := a.Srv().Store.Thread().GetThreadForUser(channel.TeamId, threadMembership, true) + thread, mErr := a.Srv().Store().Thread().GetThreadForUser(channel.TeamId, threadMembership, true) if mErr != nil { return nil, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(mErr) } @@ -2704,7 +2704,7 @@ func (a *App) markChannelAsUnreadFromPostCRTUnsupported(c request.CTX, postID st } } - channelUnread, nErr := a.Srv().Store.Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, 0, false) + channelUnread, nErr := a.Srv().Store().Channel().UpdateLastViewedAtPost(post, userID, unreadMentions, 0, false) if nErr != nil { return channelUnread, model.NewAppError("MarkChannelAsUnreadFromPost", "app.channel.update_last_viewed_at_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2735,7 +2735,7 @@ func (a *App) AutocompleteChannels(c request.CTX, userID, term string) (model.Ch return nil, appErr } - channelList, err := a.Srv().Store.Channel().Autocomplete(userID, term, includeDeleted, user.IsGuest()) + channelList, err := a.Srv().Store().Channel().Autocomplete(userID, term, includeDeleted, user.IsGuest()) if err != nil { return nil, model.NewAppError("AutocompleteChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2752,7 +2752,7 @@ func (a *App) AutocompleteChannelsForTeam(c request.CTX, teamID, userID, term st return nil, appErr } - channelList, err := a.Srv().Store.Channel().AutocompleteInTeam(teamID, userID, term, includeDeleted, user.IsGuest()) + channelList, err := a.Srv().Store().Channel().AutocompleteInTeam(teamID, userID, term, includeDeleted, user.IsGuest()) if err != nil { return nil, model.NewAppError("AutocompleteChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2765,7 +2765,7 @@ func (a *App) AutocompleteChannelsForSearch(c request.CTX, teamID string, userID term = strings.TrimSpace(term) - channelList, err := a.Srv().Store.Channel().AutocompleteInTeamForSearch(teamID, userID, term, includeDeleted) + channelList, err := a.Srv().Store().Channel().AutocompleteInTeamForSearch(teamID, userID, term, includeDeleted) if err != nil { return nil, model.NewAppError("AutocompleteChannelsForSearch", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2798,7 +2798,7 @@ func (a *App) SearchAllChannels(c request.CTX, term string, opts model.ChannelSe term = strings.TrimSpace(term) - channelList, totalCount, err := a.Srv().Store.Channel().SearchAllChannels(term, storeOpts) + channelList, totalCount, err := a.Srv().Store().Channel().SearchAllChannels(term, storeOpts) if err != nil { return nil, 0, model.NewAppError("SearchAllChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2811,7 +2811,7 @@ func (a *App) SearchChannels(c request.CTX, teamID string, term string) (model.C term = strings.TrimSpace(term) - channelList, err := a.Srv().Store.Channel().SearchInTeam(teamID, term, includeDeleted) + channelList, err := a.Srv().Store().Channel().SearchInTeam(teamID, term, includeDeleted) if err != nil { return nil, model.NewAppError("SearchChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2822,7 +2822,7 @@ func (a *App) SearchChannels(c request.CTX, teamID string, term string) (model.C func (a *App) SearchArchivedChannels(c request.CTX, teamID string, term string, userID string) (model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) - channelList, err := a.Srv().Store.Channel().SearchArchivedInTeam(teamID, term, userID) + channelList, err := a.Srv().Store().Channel().SearchArchivedInTeam(teamID, term, userID) if err != nil { return nil, model.NewAppError("SearchArchivedChannels", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2835,7 +2835,7 @@ func (a *App) SearchChannelsForUser(c request.CTX, userID, teamID, term string) term = strings.TrimSpace(term) - channelList, err := a.Srv().Store.Channel().SearchForUserInTeam(userID, teamID, term, includeDeleted) + channelList, err := a.Srv().Store().Channel().SearchForUserInTeam(userID, teamID, term, includeDeleted) if err != nil { return nil, model.NewAppError("SearchChannelsForUser", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2848,7 +2848,7 @@ func (a *App) SearchGroupChannels(c request.CTX, userID, term string) (model.Cha return model.ChannelList{}, nil } - channelList, err := a.Srv().Store.Channel().SearchGroupChannels(userID, term) + channelList, err := a.Srv().Store().Channel().SearchGroupChannels(userID, term) if err != nil { return nil, model.NewAppError("SearchGroupChannels", "app.channel.search_group_channels.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2857,7 +2857,7 @@ func (a *App) SearchGroupChannels(c request.CTX, userID, term string) (model.Cha func (a *App) SearchChannelsUserNotIn(c request.CTX, teamID string, userID string, term string) (model.ChannelList, *model.AppError) { term = strings.TrimSpace(term) - channelList, err := a.Srv().Store.Channel().SearchMore(userID, teamID, term) + channelList, err := a.Srv().Store().Channel().SearchMore(userID, teamID, term) if err != nil { return nil, model.NewAppError("SearchChannelsUserNotIn", "app.channel.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2870,13 +2870,13 @@ func (a *App) MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID st channelsToClearPushNotifications := []string{} if a.canSendPushNotifications() { for _, channelID := range channelIDs { - channel, errCh := a.Srv().Store.Channel().Get(channelID, true) + channel, errCh := a.Srv().Store().Channel().Get(channelID, true) if errCh != nil { c.Logger().Warn("Failed to get channel", mlog.Err(errCh)) continue } - member, err := a.Srv().Store.Channel().GetMember(context.Background(), channelID, userID) + member, err := a.Srv().Store().Channel().GetMember(context.Background(), channelID, userID) if err != nil { c.Logger().Warn("Failed to get membership", mlog.Err(err)) continue @@ -2892,13 +2892,13 @@ func (a *App) MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID st notify = user.NotifyProps[model.PushNotifyProp] } if notify == model.UserNotifyAll { - if count, err := a.Srv().Store.User().GetAnyUnreadPostCountForChannel(userID, channelID); err == nil { + if count, err := a.Srv().Store().User().GetAnyUnreadPostCountForChannel(userID, channelID); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID) } } } else if notify == model.UserNotifyMention || channel.Type == model.ChannelTypeDirect { - if count, err := a.Srv().Store.User().GetUnreadCountForChannel(userID, channelID); err == nil { + if count, err := a.Srv().Store().User().GetUnreadCountForChannel(userID, channelID); err == nil { if count > 0 { channelsToClearPushNotifications = append(channelsToClearPushNotifications, channelID) } @@ -2910,13 +2910,13 @@ func (a *App) MarkChannelsAsViewed(c request.CTX, channelIDs []string, userID st var err error updateThreads := *a.Config().ServiceSettings.ThreadAutoFollow && (!collapsedThreadsSupported || !a.IsCRTEnabledForUser(c, userID)) if updateThreads { - err = a.Srv().Store.Thread().MarkAllAsReadByChannels(userID, channelIDs) + err = a.Srv().Store().Thread().MarkAllAsReadByChannels(userID, channelIDs) if err != nil { return nil, model.NewAppError("MarkChannelsAsViewed", "app.channel.update_last_viewed_at.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } } - times, err := a.Srv().Store.Channel().UpdateLastViewedAt(channelIDs, userID) + times, err := a.Srv().Store().Channel().UpdateLastViewedAt(channelIDs, userID) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -2973,30 +2973,31 @@ func (a *App) ViewChannel(c request.CTX, view *model.ChannelView, userID string, } func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *model.AppError { - if err := a.Srv().Store.Post().PermanentDeleteByChannel(channel.Id); err != nil { + if err := a.Srv().Store().Post().PermanentDeleteByChannel(channel.Id); err != nil { return model.NewAppError("PermanentDeleteChannel", "app.post.permanent_delete_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { + if err := a.Srv().Store().Channel().PermanentDeleteMembersByChannel(channel.Id); err != nil { return model.NewAppError("PermanentDeleteChannel", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Webhook().PermanentDeleteIncomingByChannel(channel.Id); err != nil { + if err := a.Srv().Store().Webhook().PermanentDeleteIncomingByChannel(channel.Id); err != nil { return model.NewAppError("PermanentDeleteChannel", "app.webhooks.permanent_delete_incoming_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Webhook().PermanentDeleteOutgoingByChannel(channel.Id); err != nil { + if err := a.Srv().Store().Webhook().PermanentDeleteOutgoingByChannel(channel.Id); err != nil { return model.NewAppError("PermanentDeleteChannel", "app.webhooks.permanent_delete_outgoing_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } deleteAt := model.GetMillis() - if nErr := a.Srv().Store.Channel().PermanentDelete(channel.Id); nErr != nil { + if nErr := a.Srv().Store().Channel().PermanentDelete(channel.Id); nErr != nil { return model.NewAppError("PermanentDeleteChannel", "app.channel.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) message := model.NewWebSocketEvent(model.WebsocketEventChannelDeleted, channel.TeamId, "", "", nil, "") + message.Add("channel_id", channel.Id) message.Add("delete_at", deleteAt) a.Publish(message) @@ -3005,7 +3006,7 @@ func (a *App) PermanentDeleteChannel(c request.CTX, channel *model.Channel) *mod } func (a *App) RemoveAllDeactivatedMembersFromChannel(c request.CTX, channel *model.Channel) *model.AppError { - err := a.Srv().Store.Channel().RemoveAllDeactivatedMembers(channel.Id) + err := a.Srv().Store().Channel().RemoveAllDeactivatedMembers(channel.Id) if err != nil { return model.NewAppError("RemoveAllDeactivatedMembersFromChannel", "app.channel.remove_all_deactivated_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3048,7 +3049,7 @@ func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channe } // keep instance of the previous team - previousTeam, nErr := a.Srv().Store.Team().Get(channel.TeamId) + previousTeam, nErr := a.Srv().Store().Team().Get(channel.TeamId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -3059,12 +3060,12 @@ func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channe } } - if nErr := a.Srv().Store.Channel().UpdateSidebarChannelCategoryOnMove(channel, team.Id); nErr != nil { + if nErr := a.Srv().Store().Channel().UpdateSidebarChannelCategoryOnMove(channel, team.Id); nErr != nil { return model.NewAppError("MoveChannel", "app.channel.sidebar_categories.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } channel.TeamId = team.Id - if _, err := a.Srv().Store.Channel().Update(channel); err != nil { + if _, err := a.Srv().Store().Channel().Update(channel); err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput switch { @@ -3083,7 +3084,7 @@ func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channe for _, webhook := range incomingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if _, err := a.Srv().Store.Webhook().UpdateIncoming(webhook); err != nil { + if _, err := a.Srv().Store().Webhook().UpdateIncoming(webhook); err != nil { c.Logger().Warn("Failed to move incoming webhook to new team", mlog.String("webhook id", webhook.Id)) } } @@ -3096,7 +3097,7 @@ func (a *App) MoveChannel(c request.CTX, team *model.Team, channel *model.Channe for _, webhook := range outgoingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if _, err := a.Srv().Store.Webhook().UpdateOutgoing(webhook); err != nil { + if _, err := a.Srv().Store().Webhook().UpdateOutgoing(webhook); err != nil { c.Logger().Warn("Failed to move outgoing webhook to new team.", mlog.String("webhook id", webhook.Id)) } } @@ -3175,7 +3176,7 @@ func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c request.CTX, remover *mode } func (a *App) GetPinnedPosts(c request.CTX, channelID string) (*model.PostList, *model.AppError) { - posts, err := a.Srv().Store.Channel().GetPinnedPosts(channelID) + posts, err := a.Srv().Store().Channel().GetPinnedPosts(channelID) if err != nil { return nil, model.NewAppError("GetPinnedPosts", "app.channel.pinned_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3188,7 +3189,7 @@ func (a *App) GetPinnedPosts(c request.CTX, channelID string) (*model.PostList, } func (a *App) ToggleMuteChannel(c request.CTX, channelID, userID string) (*model.ChannelMember, *model.AppError) { - member, nErr := a.Srv().Store.Channel().GetMember(context.Background(), channelID, userID) + member, nErr := a.Srv().Store().Channel().GetMember(context.Background(), channelID, userID) if nErr != nil { var appErr *model.AppError var nfErr *store.ErrNotFound @@ -3215,7 +3216,7 @@ func (a *App) ToggleMuteChannel(c request.CTX, channelID, userID string) (*model } func (a *App) setChannelsMuted(c request.CTX, channelIDs []string, userID string, muted bool) ([]*model.ChannelMember, *model.AppError) { - members, err := a.Srv().Store.Channel().GetMembersByChannelIds(channelIDs, userID) + members, err := a.Srv().Store().Channel().GetMembersByChannelIds(channelIDs, userID) if err != nil { var appErr *model.AppError switch { @@ -3242,7 +3243,7 @@ func (a *App) setChannelsMuted(c request.CTX, channelIDs []string, userID string return nil, nil } - updated, err := a.Srv().Store.Channel().UpdateMultipleMembers(membersToUpdate) + updated, err := a.Srv().Store().Channel().UpdateMultipleMembers(membersToUpdate) if err != nil { var appErr *model.AppError var nfErr *store.ErrNotFound @@ -3342,7 +3343,7 @@ func (a *App) forEachChannelMember(c request.CTX, channelID string, f func(model page := 0 for { - channelMembers, err := a.Srv().Store.Channel().GetMembers(channelID, page*perPage, perPage) + channelMembers, err := a.Srv().Store().Channel().GetMembers(channelID, page*perPage, perPage) if err != nil { return err } @@ -3383,7 +3384,7 @@ func (a *App) ClearChannelMembersCache(c request.CTX, channelID string) error { } func (a *App) GetMemberCountsByGroup(ctx context.Context, channelID string, includeTimezones bool) ([]*model.ChannelMemberCountByGroup, *model.AppError) { - channelMemberCounts, err := a.Srv().Store.Channel().GetMemberCountsByGroup(ctx, channelID, includeTimezones) + channelMemberCounts, err := a.Srv().Store().Channel().GetMemberCountsByGroup(ctx, channelID, includeTimezones) if err != nil { return nil, model.NewAppError("GetMemberCountsByGroup", "app.channel.get_member_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3396,7 +3397,7 @@ func (a *App) getDirectChannel(c request.CTX, userID, otherUserID string) (*mode } func (s *Server) getDirectChannel(c request.CTX, userID, otherUserID string) (*model.Channel, *model.AppError) { - channel, nErr := s.Store.Channel().GetByName("", model.GetDMNameFromIds(userID, otherUserID), true) + channel, nErr := s.Store().Channel().GetByName("", model.GetDMNameFromIds(userID, otherUserID), true) if nErr != nil { var nfErr *store.ErrNotFound if errors.As(nErr, &nfErr) { @@ -3414,7 +3415,7 @@ func (a *App) GetTopChannelsForTeamSince(c request.CTX, teamID, userID string, o return nil, model.NewAppError("GetTopChannelsForTeamSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topChannels, err := a.Srv().Store.Channel().GetTopChannelsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topChannels, err := a.Srv().Store().Channel().GetTopChannelsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3426,7 +3427,7 @@ func (a *App) GetTopChannelsForUserSince(c request.CTX, userID, teamID string, o return nil, model.NewAppError("GetTopChannelsForUserSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topChannels, err := a.Srv().Store.Channel().GetTopChannelsForUserSince(userID, teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topChannels, err := a.Srv().Store().Channel().GetTopChannelsForUserSince(userID, teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopChannelsForUserSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3442,7 +3443,7 @@ func (a *App) PostCountsByDuration(c request.CTX, channelIDs []string, sinceUnix if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("PostCountsByDuration", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - postCountByDay, err := a.Srv().Store.Channel().PostCountsByDuration(channelIDs, sinceUnixMillis, userID, grouping, groupingLocation) + postCountByDay, err := a.Srv().Store().Channel().PostCountsByDuration(channelIDs, sinceUnixMillis, userID, grouping, groupingLocation) if err != nil { return nil, model.NewAppError("PostCountsByDuration", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3453,7 +3454,7 @@ func (a *App) GetTopInactiveChannelsForTeamSince(c request.CTX, teamID, userID s if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopChannelsForTeamSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topChannels, err := a.Srv().Store.Channel().GetTopInactiveChannelsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topChannels, err := a.Srv().Store().Channel().GetTopInactiveChannelsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopInactiveChannelsForTeamSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -3465,7 +3466,7 @@ func (a *App) GetTopInactiveChannelsForUserSince(c request.CTX, teamID, userID s return nil, model.NewAppError("GetTopChannelsForUserSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topChannels, err := a.Srv().Store.Channel().GetTopInactiveChannelsForUserSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topChannels, err := a.Srv().Store().Channel().GetTopInactiveChannelsForUserSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopInactiveChannelsForUserSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/channel_category.go b/app/channel_category.go index 65f80c8545..4a020542c9 100644 --- a/app/channel_category.go +++ b/app/channel_category.go @@ -15,7 +15,7 @@ import ( ) func (a *App) createInitialSidebarCategories(userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { - categories, nErr := a.Srv().Store.Channel().CreateInitialSidebarCategories(userID, opts) + categories, nErr := a.Srv().Store().Channel().CreateInitialSidebarCategories(userID, opts) if nErr != nil { return nil, model.NewAppError("createInitialSidebarCategories", "app.channel.create_initial_sidebar_categories.internal_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -25,7 +25,7 @@ func (a *App) createInitialSidebarCategories(userID string, opts *store.SidebarC func (a *App) GetSidebarCategoriesForTeamForUser(c request.CTX, userID, teamID string) (*model.OrderedSidebarCategories, *model.AppError) { var appErr *model.AppError - categories, err := a.Srv().Store.Channel().GetSidebarCategoriesForTeamForUser(userID, teamID) + categories, err := a.Srv().Store().Channel().GetSidebarCategoriesForTeamForUser(userID, teamID) if err == nil && len(categories.Categories) == 0 { // A user must always have categories, so migration must not have happened yet, and we should run it ourselves categories, appErr = a.createInitialSidebarCategories(userID, &store.SidebarCategorySearchOpts{ @@ -52,7 +52,7 @@ func (a *App) GetSidebarCategoriesForTeamForUser(c request.CTX, userID, teamID s func (a *App) GetSidebarCategories(c request.CTX, userID string, opts *store.SidebarCategorySearchOpts) (*model.OrderedSidebarCategories, *model.AppError) { var appErr *model.AppError - categories, err := a.Srv().Store.Channel().GetSidebarCategories(userID, opts) + categories, err := a.Srv().Store().Channel().GetSidebarCategories(userID, opts) if err == nil && len(categories.Categories) == 0 { // A user must always have categories, so migration must not have happened yet, and we should run it ourselves categories, appErr = a.createInitialSidebarCategories(userID, opts) @@ -75,7 +75,7 @@ func (a *App) GetSidebarCategories(c request.CTX, userID string, opts *store.Sid } func (a *App) GetSidebarCategoryOrder(c request.CTX, userID, teamID string) ([]string, *model.AppError) { - categories, err := a.Srv().Store.Channel().GetSidebarCategoryOrder(userID, teamID) + categories, err := a.Srv().Store().Channel().GetSidebarCategoryOrder(userID, teamID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -90,7 +90,7 @@ func (a *App) GetSidebarCategoryOrder(c request.CTX, userID, teamID string) ([]s } func (a *App) GetSidebarCategory(c request.CTX, categoryId string) (*model.SidebarCategoryWithChannels, *model.AppError) { - category, err := a.Srv().Store.Channel().GetSidebarCategory(categoryId) + category, err := a.Srv().Store().Channel().GetSidebarCategory(categoryId) if err != nil { var nfErr *store.ErrNotFound switch { @@ -105,7 +105,7 @@ func (a *App) GetSidebarCategory(c request.CTX, categoryId string) (*model.Sideb } func (a *App) CreateSidebarCategory(c request.CTX, userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) { - category, err := a.Srv().Store.Channel().CreateSidebarCategory(userID, teamID, newCategory) + category, err := a.Srv().Store().Channel().CreateSidebarCategory(userID, teamID, newCategory) if err != nil { var nfErr *store.ErrNotFound switch { @@ -122,7 +122,7 @@ func (a *App) CreateSidebarCategory(c request.CTX, userID, teamID string, newCat } func (a *App) UpdateSidebarCategoryOrder(c request.CTX, userID, teamID string, categoryOrder []string) *model.AppError { - err := a.Srv().Store.Channel().UpdateSidebarCategoryOrder(userID, teamID, categoryOrder) + err := a.Srv().Store().Channel().UpdateSidebarCategoryOrder(userID, teamID, categoryOrder) if err != nil { var nfErr *store.ErrNotFound var invErr *store.ErrInvalidInput @@ -142,7 +142,7 @@ func (a *App) UpdateSidebarCategoryOrder(c request.CTX, userID, teamID string, c } func (a *App) UpdateSidebarCategories(c request.CTX, userID, teamID string, categories []*model.SidebarCategoryWithChannels) ([]*model.SidebarCategoryWithChannels, *model.AppError) { - updatedCategories, originalCategories, err := a.Srv().Store.Channel().UpdateSidebarCategories(userID, teamID, categories) + updatedCategories, originalCategories, err := a.Srv().Store().Channel().UpdateSidebarCategories(userID, teamID, categories) if err != nil { return nil, model.NewAppError("UpdateSidebarCategories", "app.channel.sidebar_categories.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -269,7 +269,7 @@ func diffChannelsBetweenCategories(updatedCategories []*model.SidebarCategoryWit } func (a *App) DeleteSidebarCategory(c request.CTX, userID, teamID, categoryId string) *model.AppError { - err := a.Srv().Store.Channel().DeleteSidebarCategory(categoryId) + err := a.Srv().Store().Channel().DeleteSidebarCategory(categoryId) if err != nil { var invErr *store.ErrInvalidInput switch { diff --git a/app/channel_category_test.go b/app/channel_category_test.go index d85ef9d89a..f9759742f6 100644 --- a/app/channel_category_test.go +++ b/app/channel_category_test.go @@ -19,7 +19,7 @@ func TestSidebarCategory(t *testing.T) { basicChannel2 := th.CreateChannel(th.Context, th.BasicTeam) defer th.App.PermanentDeleteChannel(th.Context, basicChannel2) user := th.CreateUser() - defer th.App.Srv().Store.User().PermanentDelete(user.Id) + defer th.App.Srv().Store().User().PermanentDelete(user.Id) th.LinkUserToTeam(user, th.BasicTeam) th.AddUserToChannel(user, basicChannel2) @@ -105,7 +105,7 @@ func TestGetSidebarCategories(t *testing.T) { // Manually add the user to the team without going through the app layer to simulate a pre-existing user/team // relationship that hasn't been migrated yet team := th.CreateTeam() - _, err := th.App.Srv().Store.Team().SaveMember(&model.TeamMember{ + _, err := th.App.Srv().Store().Team().SaveMember(&model.TeamMember{ TeamId: team.Id, UserId: th.BasicUser.Id, SchemeUser: true, diff --git a/app/channel_test.go b/app/channel_test.go index 0657cd337d..260b46d641 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -267,10 +267,10 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi defer th.TearDown() // figure out the initial number of users in town square - channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "town-square", true) + channel, err := th.App.Srv().Store().Channel().GetByName(th.BasicTeam.Id, "town-square", true) require.NoError(t, err) townSquareChannelId := channel.Id - users, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) + users, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) require.NoError(t, nErr) initialNumTownSquareUsers := len(users) @@ -279,7 +279,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId) require.NoError(t, nErr) assert.Len(t, histories, initialNumTownSquareUsers+1) @@ -298,10 +298,10 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing defer th.TearDown() // figure out the initial number of users in off-topic - channel, err := th.App.Srv().Store.Channel().GetByName(th.BasicTeam.Id, "off-topic", true) + channel, err := th.App.Srv().Store().Channel().GetByName(th.BasicTeam.Id, "off-topic", true) require.NoError(t, err) offTopicChannelId := channel.Id - users, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) + users, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) require.NoError(t, nErr) initialNumTownSquareUsers := len(users) @@ -310,7 +310,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "") // there should be a ChannelMemberHistory record for the user - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId) require.NoError(t, nErr) assert.Len(t, histories, initialNumTownSquareUsers+1) @@ -382,7 +382,7 @@ func TestCreateChannelPublicCreatesChannelMemberHistoryRecord(t *testing.T) { publicChannel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypeOpen) // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) + histories, err := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, publicChannel.Id) require.NoError(t, err) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) @@ -397,7 +397,7 @@ func TestCreateChannelPrivateCreatesChannelMemberHistoryRecord(t *testing.T) { privateChannel := th.createChannel(th.Context, th.BasicTeam, model.ChannelTypePrivate) // there should be a ChannelMemberHistory record for the user - histories, err := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) + histories, err := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, privateChannel.Id) require.NoError(t, err) assert.Len(t, histories, 1) assert.Equal(t, th.BasicUser.Id, histories[0].UserId) @@ -485,7 +485,7 @@ func TestCreateGroupChannelCreatesChannelMemberHistoryRecord(t *testing.T) { channel, err := th.App.CreateGroupChannel(th.Context, groupUserIds, th.BasicUser.Id) require.Nil(t, err, "Failed to create group channel.") - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.NoError(t, nErr) assert.Len(t, histories, 3) @@ -510,7 +510,7 @@ func TestCreateDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { channel, err := th.App.GetOrCreateDirectChannel(th.Context, user1.Id, user2.Id) require.Nil(t, err, "Failed to create direct channel.") - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.NoError(t, nErr) assert.Len(t, histories, 2) @@ -538,7 +538,7 @@ func TestGetDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) { require.Nil(t, err, "Failed to create direct channel.") // there should be a ChannelMemberHistory record for both users - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.NoError(t, nErr) assert.Len(t, histories, 2) @@ -573,7 +573,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) { require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.NoError(t, nErr) assert.Len(t, histories, 2) channelMemberHistoryUserIds := make([]string, 0) @@ -660,7 +660,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { require.Nil(t, err, "Failed to add user to channel.") // there should be a ChannelMemberHistory record for the user - histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) + histories, nErr := th.App.Srv().Store().ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id) require.NoError(t, nErr) assert.Len(t, histories, 2) channelMemberHistoryUserIds := make([]string, 0) @@ -670,7 +670,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) { } assert.Equal(t, groupUserIds, channelMemberHistoryUserIds) - postList, nErr := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) + postList, nErr := th.App.Srv().Store().Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) require.NoError(t, nErr) if assert.Len(t, postList.Order, 1) { @@ -2036,7 +2036,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Get", context.Background(), "userID").Return(nil, model.NewAppError("SqlUserStore.Get", "app.user.get.app_error", nil, "user_id=userID", http.StatusInternalServerError)) mockChannelStore := mocks.ChannelStore{} @@ -2076,7 +2076,7 @@ func TestClearChannelMembersCache(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockChannelStore := mocks.ChannelStore{} cms := model.ChannelMembers{} for i := 0; i < 200; i++ { @@ -2099,7 +2099,7 @@ func TestGetMemberCountsByGroup(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockChannelStore := mocks.ChannelStore{} cmc := []*model.ChannelMemberCountByGroup{} for i := 0; i < 5; i++ { @@ -2143,7 +2143,7 @@ func TestViewChannelCollapsedThreadsTurnedOff(t *testing.T) { } var preferences model.Preferences preferences = append(preferences, preference) - err := th.App.Srv().Store.Preference().Save(preferences) + err := th.App.Srv().Store().Preference().Save(preferences) require.NoError(t, err) // mention the user in a root post @@ -2219,7 +2219,7 @@ func TestMarkChannelAsUnreadFromPostCollapsedThreadsTurnedOff(t *testing.T) { } var preferences model.Preferences preferences = append(preferences, preference) - err := th.App.Srv().Store.Preference().Save(preferences) + err := th.App.Srv().Store().Preference().Save(preferences) require.NoError(t, err) // user2: first root mention @user1 @@ -2392,7 +2392,7 @@ func TestIsCRTEnabledForUser(t *testing.T) { th.App.Config().ServiceSettings.CollapsedThreads = &tc.appCRT - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockPreferenceStore := mocks.PreferenceStore{} mockPreferenceStore.On("Get", mock.Anything, model.PreferenceCategoryDisplaySettings, model.PreferenceNameCollapsedThreadsEnabled).Return(&model.Preference{Value: tc.pref.val}, tc.pref.err) mockStore.On("Preference").Return(&mockPreferenceStore) @@ -2411,7 +2411,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { channel2 := th.CreateChannel(th.Context, th.BasicTeam) // add a bot post to ensure it's not counted - _, err := th.Server.Store.Post().Save(&model.Post{ + _, err := th.Server.Store().Post().Save(&model.Post{ Message: "hello from a bot", ChannelId: channel2.Id, UserId: th.BasicUser.Id, @@ -2424,7 +2424,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam) // add a webhook post to ensure it's not counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from a webhook", ChannelId: channel3.Id, UserId: th.BasicUser.Id, @@ -2435,7 +2435,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { require.NoError(t, err) // add an oauth app post to ensure it's not counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from an ouath app", ChannelId: channel3.Id, UserId: th.BasicUser.Id, @@ -2446,7 +2446,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { require.NoError(t, err) // add a plugin post to ensure it's not counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from a plugin", ChannelId: channel3.Id, UserId: th.BasicUser.Id, @@ -2457,7 +2457,7 @@ func TestGetTopChannelsForTeamSince(t *testing.T) { require.NoError(t, err) // add a system post to ensure it's not counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "system message", Type: "system_join_channel", ChannelId: channel3.Id, @@ -2523,7 +2523,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { channel2 := th.CreateChannel(th.Context, th.BasicTeam) // add a bot post to ensure it's not counted - _, err := th.Server.Store.Post().Save(&model.Post{ + _, err := th.Server.Store().Post().Save(&model.Post{ Message: "hello from a bot", ChannelId: channel2.Id, UserId: th.BasicUser.Id, @@ -2536,7 +2536,7 @@ func TestGetTopChannelsForUserSince(t *testing.T) { channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam) // add a webhook post to ensure it's not counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from a webhook", ChannelId: channel3.Id, UserId: th.BasicUser.Id, @@ -2745,7 +2745,7 @@ func TestGetTopInactiveChannelsForTeamSince(t *testing.T) { require.Nil(t, appErr) // add a bot post to ensure it's counted - _, err := th.Server.Store.Post().Save(&model.Post{ + _, err := th.Server.Store().Post().Save(&model.Post{ Message: "hello from a bot", ChannelId: channel2.Id, UserId: th.BasicUser.Id, @@ -2756,7 +2756,7 @@ func TestGetTopInactiveChannelsForTeamSince(t *testing.T) { require.NoError(t, err) // add a webhook post to ensure it's counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from a webhook", ChannelId: channel3.Id, UserId: th.BasicUser.Id, @@ -2832,7 +2832,7 @@ func TestGetTopInactiveChannelsForUserSince(t *testing.T) { channel2 := th.CreateChannel(th.Context, th.BasicTeam, WithCreateAt(1)) // add a bot post to ensure it's counted - _, err := th.Server.Store.Post().Save(&model.Post{ + _, err := th.Server.Store().Post().Save(&model.Post{ Message: "hello from a bot", ChannelId: channel2.Id, UserId: th.BasicUser.Id, @@ -2845,7 +2845,7 @@ func TestGetTopInactiveChannelsForUserSince(t *testing.T) { channel3 := th.CreatePrivateChannel(th.Context, th.BasicTeam, WithCreateAt(1)) // add a webhook post to ensure it's counted - _, err = th.Server.Store.Post().Save(&model.Post{ + _, err = th.Server.Store().Post().Save(&model.Post{ Message: "hello from a webhook", ChannelId: channel3.Id, UserId: th.BasicUser.Id, diff --git a/app/channels.go b/app/channels.go index ea08ac8086..0b728a3cbc 100644 --- a/app/channels.go +++ b/app/channels.go @@ -8,7 +8,6 @@ import ( "runtime" "strings" "sync" - "sync/atomic" "github.com/pkg/errors" @@ -49,11 +48,6 @@ type Channels struct { imageProxy *imageproxy.ImageProxy - asymmetricSigningKey atomic.Value - clientConfig atomic.Value - clientConfigHash atomic.Value - limitedClientConfig atomic.Value - // cached counts that are used during notice condition validation cachedPostCount int64 cachedUserCount int64 @@ -267,7 +261,8 @@ func (ch *Channels) Start() error { }) - if err := ch.ensureAsymmetricSigningKey(); err != nil { + // TODO: This should be moved to the platform service. + if err := ch.srv.platform.EnsureAsymmetricSigningKey(); err != nil { return errors.Wrapf(err, "unable to ensure asymmetric signing key") } diff --git a/app/cluster.go b/app/cluster.go index ae9e98fa8e..83279f39c3 100644 --- a/app/cluster.go +++ b/app/cluster.go @@ -3,96 +3,18 @@ package app -import ( - "fmt" - - "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/product" -) - -// ensure cluster service wrapper implements `product.ClusterService` -var _ product.ClusterService = (*clusterWrapper)(nil) - -// clusterWrapper provides an implementation of `product.ClusterService` for use by products. -type clusterWrapper struct { - srv *Server -} - -func (s *clusterWrapper) PublishPluginClusterEvent(productID string, ev model.PluginClusterEvent, - opts model.PluginClusterEventSendOptions) error { - if s.srv.Cluster == nil { - return nil - } - - msg := &model.ClusterMessage{ - Event: model.ClusterEventPluginEvent, - SendType: opts.SendType, - WaitForAllToSend: false, - Props: map[string]string{ - "ProductID": productID, - "EventID": ev.Id, - }, - Data: ev.Data, - } - - // If TargetId is empty we broadcast to all other cluster nodes. - if opts.TargetId == "" { - s.srv.Cluster.SendClusterMessage(msg) - } else { - if err := s.srv.Cluster.SendClusterMessageToNode(opts.TargetId, msg); err != nil { - return fmt.Errorf("failed to send message to cluster node %q: %w", opts.TargetId, err) - } - } - - return nil -} - -func (s *clusterWrapper) PublishWebSocketEvent(productID string, event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { - ev := model.NewWebSocketEvent(fmt.Sprintf("custom_%v_%v", productID, event), "", "", "", nil, "") - ev = ev.SetBroadcast(broadcast).SetData(payload) - s.srv.Publish(ev) -} - -func (s *clusterWrapper) SetPluginKeyWithOptions(productID string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) { - return s.srv.setPluginKeyWithOptions(productID, key, value, options) -} - -func (s *clusterWrapper) KVGet(productID, key string) ([]byte, *model.AppError) { - return s.srv.getPluginKey(productID, key) -} - -func (s *clusterWrapper) KVDelete(productID, key string) *model.AppError { - return s.srv.deletePluginKey(productID, key) -} - -func (s *clusterWrapper) KVList(productID string, page, perPage int) ([]string, *model.AppError) { - return s.srv.listPluginKeys(productID, page, perPage) -} - // Registers a given function to be called when the cluster leader may have changed. Returns a unique ID for the // listener which can later be used to remove it. If clustering is not enabled in this build, the callback will never // be called. func (s *Server) AddClusterLeaderChangedListener(listener func()) string { - id := model.NewId() - s.clusterLeaderListeners.Store(id, listener) - return id + return s.platform.AddClusterLeaderChangedListener(listener) } // Removes a listener function by the unique ID returned when AddConfigListener was called func (s *Server) RemoveClusterLeaderChangedListener(id string) { - s.clusterLeaderListeners.Delete(id) + s.platform.RemoveClusterLeaderChangedListener(id) } func (s *Server) InvokeClusterLeaderChangedListeners() { - s.Log().Info("Cluster leader changed. Invoking ClusterLeaderChanged listeners.") - // This needs to be run in a separate goroutine otherwise a recursive lock happens - // because the listener function eventually ends up calling .IsLeader(). - // Fixing this would require the changed event to pass the leader directly, but that - // requires a lot of work. - s.Go(func() { - s.clusterLeaderListeners.Range(func(_, listener any) bool { - listener.(func())() - return true - }) - }) + s.platform.InvokeClusterLeaderChangedListeners() } diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index 9ae26038d4..a706c4250e 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -3,90 +3,8 @@ package app -import ( - "time" - - "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/shared/mlog" -) - -const ( - DiscoveryServiceWritePing = 60 * time.Second -) - -type ClusterDiscoveryService struct { - model.ClusterDiscovery - srv *Server - stop chan bool -} - -func (s *Server) NewClusterDiscoveryService() *ClusterDiscoveryService { - ds := &ClusterDiscoveryService{ - ClusterDiscovery: model.ClusterDiscovery{}, - srv: s, - stop: make(chan bool), - } - - return ds -} - -func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService { - return a.Srv().NewClusterDiscoveryService() -} - -func (cds *ClusterDiscoveryService) Start() { - err := cds.srv.Store.ClusterDiscovery().Cleanup() - if err != nil { - mlog.Warn("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err)) - } - - exists, err := cds.srv.Store.ClusterDiscovery().Exists(&cds.ClusterDiscovery) - if err != nil { - mlog.Warn("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) - } else if exists { - if _, err := cds.srv.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil { - mlog.Warn("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) - } - } - - if err := cds.srv.Store.ClusterDiscovery().Save(&cds.ClusterDiscovery); err != nil { - mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) - return - } - - go func() { - mlog.Debug("ClusterDiscoveryService ping writer started", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id)) - ticker := time.NewTicker(DiscoveryServiceWritePing) - defer func() { - ticker.Stop() - if _, err := cds.srv.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil { - mlog.Warn("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) - } - mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id)) - }() - - for { - select { - case <-ticker.C: - if err := cds.srv.Store.ClusterDiscovery().SetLastPingAt(&cds.ClusterDiscovery); err != nil { - mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) - } - case <-cds.stop: - return - } - } - }() -} - -func (cds *ClusterDiscoveryService) Stop() { - cds.stop <- true -} - func (s *Server) IsLeader() bool { - if s.License() != nil && *s.platform.Config().ClusterSettings.Enable && s.Cluster != nil { - return s.Cluster.IsLeader() - } - return true + return s.platform.IsLeader() } func (a *App) IsLeader() bool { @@ -94,9 +12,6 @@ func (a *App) IsLeader() bool { } func (a *App) GetClusterId() string { - if a.Cluster() == nil { - return "" - } - return a.Cluster().GetClusterId() + return a.Srv().Platform().GetClusterId() } diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index 242875e9c5..beb8f71c73 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -4,7 +4,6 @@ package app import ( - "bytes" "encoding/json" "github.com/mattermost/mattermost-server/v6/model" @@ -62,104 +61,10 @@ func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) { // The cluster event handlers are spread across this function and NewLocalCacheLayer. // Be careful to not have duplicated handlers here and there. func (s *Server) registerClusterHandlers() { - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPublish, s.clusterPublishHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventUpdateStatus, s.clusterUpdateStatusHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateAllCaches, s.clusterInvalidateAllCachesHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, s.clusterInvalidateCacheForChannelMembersNotifyPropHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelByName, s.clusterInvalidateCacheForChannelByNameHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUser, s.clusterInvalidateCacheForUserHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUserTeams, s.clusterInvalidateCacheForUserTeamsHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventBusyStateChanged, s.clusterBusyStateChgHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForUser, s.clusterClearSessionCacheForUserHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForAllUsers, s.clusterClearSessionCacheForAllUsersHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventInstallPlugin, s.clusterInstallPluginHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventRemovePlugin, s.clusterRemovePluginHandler) - s.Cluster.RegisterClusterMessageHandler(model.ClusterEventPluginEvent, s.clusterPluginEventHandler) -} -func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) { - event, err := model.WebSocketEventFromJSON(bytes.NewReader(msg.Data)) - if err != nil { - mlog.Warn("Failed to decode event from JSON", mlog.Err(err)) - return - } - s.PublishSkipClusterSend(event) -} + s.platform.RegisterClusterMessageHandler(model.ClusterEventInstallPlugin, s.clusterInstallPluginHandler) + s.platform.RegisterClusterMessageHandler(model.ClusterEventRemovePlugin, s.clusterRemovePluginHandler) + s.platform.RegisterClusterMessageHandler(model.ClusterEventPluginEvent, s.clusterPluginEventHandler) -func (s *Server) clusterUpdateStatusHandler(msg *model.ClusterMessage) { - var status model.Status - if jsonErr := json.Unmarshal(msg.Data, &status); jsonErr != nil { - mlog.Warn("Failed to decode status from JSON") - } - s.statusCache.Set(status.UserId, status) -} - -func (s *Server) clusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { - s.InvalidateAllCachesSkipSend() -} - -func (s *Server) clusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { - s.invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(string(msg.Data)) -} - -func (s *Server) clusterInvalidateCacheForChannelByNameHandler(msg *model.ClusterMessage) { - s.invalidateCacheForChannelByNameSkipClusterSend(msg.Props["id"], msg.Props["name"]) -} - -func (s *Server) clusterInvalidateCacheForUserHandler(msg *model.ClusterMessage) { - s.invalidateCacheForUserSkipClusterSend(string(msg.Data)) -} - -func (s *Server) clusterInvalidateCacheForUserTeamsHandler(msg *model.ClusterMessage) { - s.invalidateWebConnSessionCacheForUser(string(msg.Data)) -} - -func (s *Server) clearSessionCacheForUserSkipClusterSend(userID string) { - s.userService.ClearUserSessionCacheLocal(userID) - s.invalidateWebConnSessionCacheForUser(userID) -} - -func (s *Server) clearSessionCacheForAllUsersSkipClusterSend() { - mlog.Info("Purging sessions cache") - s.userService.ClearAllUsersSessionCacheLocal() -} - -func (s *Server) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) { - s.clearSessionCacheForUserSkipClusterSend(string(msg.Data)) -} - -func (s *Server) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) { - s.clearSessionCacheForAllUsersSkipClusterSend() -} - -func (s *Server) clusterBusyStateChgHandler(msg *model.ClusterMessage) { - var sbs model.ServerBusyState - if jsonErr := json.Unmarshal(msg.Data, &sbs); jsonErr != nil { - mlog.Warn("Failed to decode server busy state from JSON", mlog.Err(jsonErr)) - } - s.serverBusyStateChanged(&sbs) -} - -func (s *Server) invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelID string) { - s.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelID) -} - -func (s *Server) invalidateCacheForChannelByNameSkipClusterSend(teamID, name string) { - if teamID == "" { - teamID = "dm" - } - - s.Store.Channel().InvalidateChannelByName(teamID, name) -} - -func (s *Server) invalidateCacheForUserSkipClusterSend(userID string) { - s.Store.Channel().InvalidateAllChannelMembersForUser(userID) - s.invalidateWebConnSessionCacheForUser(userID) -} - -func (s *Server) invalidateWebConnSessionCacheForUser(userID string) { - hub := s.GetHubForUserId(userID) - if hub != nil { - hub.InvalidateUser(userID) - } + s.platform.RegisterClusterHandlers() } diff --git a/app/command.go b/app/command.go index 1f158a15e6..1c8aeaeb9c 100644 --- a/app/command.go +++ b/app/command.go @@ -99,7 +99,7 @@ func (a *App) ListAutocompleteCommands(teamID string, T i18n.TranslateFunc) ([]* } if *a.Config().ServiceSettings.EnableCommands { - teamCmds, err := a.Srv().Store.Command().GetByTeam(teamID) + teamCmds, err := a.Srv().Store().Command().GetByTeam(teamID) if err != nil { return nil, model.NewAppError("ListAutocompleteCommands", "app.command.listautocompletecommands.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -132,7 +132,7 @@ func (a *App) ListTeamCommands(teamID string) ([]*model.Command, *model.AppError return nil, model.NewAppError("ListTeamCommands", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - teamCmds, err := a.Srv().Store.Command().GetByTeam(teamID) + teamCmds, err := a.Srv().Store().Command().GetByTeam(teamID) if err != nil { return nil, model.NewAppError("ListTeamCommands", "app.command.listteamcommands.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -162,7 +162,7 @@ func (a *App) ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Com } if *a.Config().ServiceSettings.EnableCommands { - teamCmds, err := a.Srv().Store.Command().GetByTeam(teamID) + teamCmds, err := a.Srv().Store().Command().GetByTeam(teamID) if err != nil { return nil, model.NewAppError("ListAllCommands", "app.command.listallcommands.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -248,7 +248,7 @@ func (a *App) MentionsToTeamMembers(c request.CTX, message, teamID string) model wg.Add(1) go func(mention string) { defer wg.Done() - user, nErr := a.Srv().Store.User().GetByUsername(mention) + user, nErr := a.Srv().Store().User().GetByUsername(mention) var nfErr *store.ErrNotFound if nErr != nil && !errors.As(nErr, &nfErr) { @@ -261,7 +261,7 @@ func (a *App) MentionsToTeamMembers(c request.CTX, message, teamID string) model if nErr != nil { trimmed, ok := trimUsernameSpecialChar(mention) for ; ok; trimmed, ok = trimUsernameSpecialChar(trimmed) { - userFromTrimmed, nErr := a.Srv().Store.User().GetByUsername(trimmed) + userFromTrimmed, nErr := a.Srv().Store().User().GetByUsername(trimmed) if nErr != nil && !errors.As(nErr, &nfErr) { return } @@ -370,26 +370,26 @@ func (a *App) tryExecuteCustomCommand(c request.CTX, args *model.CommandArgs, tr chanChan := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv().Store.Channel().Get(args.ChannelId, true) + channel, err := a.Srv().Store().Channel().Get(args.ChannelId, true) chanChan <- store.StoreResult{Data: channel, NErr: err} close(chanChan) }() teamChan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(args.TeamId) + team, err := a.Srv().Store().Team().Get(args.TeamId) teamChan <- store.StoreResult{Data: team, NErr: err} close(teamChan) }() userChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), args.UserId) + user, err := a.Srv().Store().User().Get(context.Background(), args.UserId) userChan <- store.StoreResult{Data: user, NErr: err} close(userChan) }() - teamCmds, err := a.Srv().Store.Command().GetByTeam(args.TeamId) + teamCmds, err := a.Srv().Store().Command().GetByTeam(args.TeamId) if err != nil { return nil, nil, model.NewAppError("tryExecuteCustomCommand", "app.command.tryexecutecustomcommand.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -638,7 +638,7 @@ func (a *App) CreateCommand(cmd *model.Command) (*model.Command, *model.AppError func (a *App) createCommand(cmd *model.Command) (*model.Command, *model.AppError) { cmd.Trigger = strings.ToLower(cmd.Trigger) - teamCmds, err := a.Srv().Store.Command().GetByTeam(cmd.TeamId) + teamCmds, err := a.Srv().Store().Command().GetByTeam(cmd.TeamId) if err != nil { return nil, model.NewAppError("CreateCommand", "app.command.createcommand.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -656,7 +656,7 @@ func (a *App) createCommand(cmd *model.Command) (*model.Command, *model.AppError } } - command, nErr := a.Srv().Store.Command().Save(cmd) + command, nErr := a.Srv().Store().Command().Save(cmd) if nErr != nil { var appErr *model.AppError switch { @@ -675,7 +675,7 @@ func (a *App) GetCommand(commandID string) (*model.Command, *model.AppError) { return nil, model.NewAppError("GetCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - command, err := a.Srv().Store.Command().Get(commandID) + command, err := a.Srv().Store().Command().Get(commandID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -703,7 +703,7 @@ func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, updatedCmd.PluginId = oldCmd.PluginId updatedCmd.TeamId = oldCmd.TeamId - command, err := a.Srv().Store.Command().Update(updatedCmd) + command, err := a.Srv().Store().Command().Update(updatedCmd) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -723,7 +723,7 @@ func (a *App) UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, func (a *App) MoveCommand(team *model.Team, command *model.Command) *model.AppError { command.TeamId = team.Id - _, err := a.Srv().Store.Command().Update(command) + _, err := a.Srv().Store().Command().Update(command) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -747,7 +747,7 @@ func (a *App) RegenCommandToken(cmd *model.Command) (*model.Command, *model.AppE cmd.Token = model.NewId() - command, err := a.Srv().Store.Command().Update(cmd) + command, err := a.Srv().Store().Command().Update(cmd) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -769,7 +769,7 @@ func (a *App) DeleteCommand(commandID string) *model.AppError { return model.NewAppError("DeleteCommand", "api.command.disabled.app_error", nil, "", http.StatusNotImplemented) } - err := a.Srv().Store.Command().Delete(commandID, model.GetMillis()) + err := a.Srv().Store().Command().Delete(commandID, model.GetMillis()) if err != nil { return model.NewAppError("DeleteCommand", "app.command.deletecommand.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/compliance.go b/app/compliance.go index b1da64e8d6..9a22288684 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -18,7 +18,7 @@ func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - compliances, err := a.Srv().Store.Compliance().GetAll(page*perPage, perPage) + compliances, err := a.Srv().Store().Compliance().GetAll(page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetComplianceReports", "app.compliance.get.finding.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -33,7 +33,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m job.Type = model.ComplianceTypeAdhoc - job, err := a.Srv().Store.Compliance().Save(job) + job, err := a.Srv().Store().Compliance().Save(job) if err != nil { var appErr *model.AppError switch { @@ -60,7 +60,7 @@ func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.Ap return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } - compliance, err := a.Srv().Store.Compliance().Get(reportId) + compliance, err := a.Srv().Store().Compliance().Get(reportId) if err != nil { var nfErr *store.ErrNotFound switch { diff --git a/app/config.go b/app/config.go index 1c66654039..debabbd4ce 100644 --- a/app/config.go +++ b/app/config.go @@ -5,13 +5,8 @@ package app import ( "crypto/ecdsa" - "crypto/elliptic" - "crypto/md5" "crypto/rand" - "crypto/x509" - "encoding/base64" "encoding/json" - "fmt" "net/url" "reflect" "strconv" @@ -19,7 +14,6 @@ import ( "github.com/pkg/errors" - "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mail" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -51,7 +45,7 @@ func (a *App) ReloadConfig() error { } func (a *App) ClientConfig() map[string]string { - return a.ch.clientConfig.Load().(map[string]string) + return a.ch.srv.platform.ClientConfig() } func (a *App) ClientConfigHash() string { @@ -59,7 +53,7 @@ func (a *App) ClientConfigHash() string { } func (a *App) LimitedClientConfig() map[string]string { - return a.ch.limitedClientConfig.Load().(map[string]string) + return a.ch.srv.platform.LimitedClientConfig() } func (a *App) AddConfigListener(listener func(*model.Config, *model.Config)) string { @@ -81,7 +75,7 @@ func (ch *Channels) ensurePostActionCookieSecret() error { var secret *model.SystemPostActionCookieSecret - value, err := ch.srv.Store.System().GetByName(model.SystemPostActionCookieSecretKey) + value, err := ch.srv.Store().System().GetByName(model.SystemPostActionCookieSecretKey) if err == nil { if err := json.Unmarshal([]byte(value.Value), &secret); err != nil { return err @@ -107,7 +101,7 @@ func (ch *Channels) ensurePostActionCookieSecret() error { } system.Value = string(v) // If we were able to save the key, use it, otherwise log the error. - if err = ch.srv.Store.System().Save(system); err != nil { + if err = ch.srv.Store().System().Save(system); err != nil { mlog.Warn("Failed to save PostActionCookieSecret", mlog.Err(err)) } else { secret = newSecret @@ -117,7 +111,7 @@ func (ch *Channels) ensurePostActionCookieSecret() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if secret == nil { - value, err := ch.srv.Store.System().GetByName(model.SystemPostActionCookieSecretKey) + value, err := ch.srv.Store().System().GetByName(model.SystemPostActionCookieSecretKey) if err != nil { return err } @@ -131,91 +125,13 @@ func (ch *Channels) ensurePostActionCookieSecret() error { return nil } -// ensureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to -// AsymmetricSigningKey will always return a valid signing key. -func (ch *Channels) ensureAsymmetricSigningKey() error { - if ch.AsymmetricSigningKey() != nil { - return nil - } - - var key *model.SystemAsymmetricSigningKey - - value, err := ch.srv.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) - if err == nil { - if err := json.Unmarshal([]byte(value.Value), &key); err != nil { - return err - } - } - - // If we don't already have a key, try to generate one. - if key == nil { - newECDSAKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - return err - } - newKey := &model.SystemAsymmetricSigningKey{ - ECDSAKey: &model.SystemECDSAKey{ - Curve: "P-256", - X: newECDSAKey.X, - Y: newECDSAKey.Y, - D: newECDSAKey.D, - }, - } - system := &model.System{ - Name: model.SystemAsymmetricSigningKeyKey, - } - v, err := json.Marshal(newKey) - if err != nil { - return err - } - system.Value = string(v) - // If we were able to save the key, use it, otherwise log the error. - if err = ch.srv.Store.System().Save(system); err != nil { - mlog.Warn("Failed to save AsymmetricSigningKey", mlog.Err(err)) - } else { - key = newKey - } - } - - // If we weren't able to save a new key above, another server must have beat us to it. Get the - // key from the database, and if that fails, error out. - if key == nil { - value, err := ch.srv.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) - if err != nil { - return err - } - - if err := json.Unmarshal([]byte(value.Value), &key); err != nil { - return err - } - } - - var curve elliptic.Curve - switch key.ECDSAKey.Curve { - case "P-256": - curve = elliptic.P256() - default: - return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve) - } - ch.asymmetricSigningKey.Store(&ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: curve, - X: key.ECDSAKey.X, - Y: key.ECDSAKey.Y, - }, - D: key.ECDSAKey.D, - }) - ch.regenerateClientConfig() - return nil -} - func (s *Server) ensureInstallationDate() error { - _, appErr := s.getSystemInstallDate() + _, appErr := s.platform.GetSystemInstallDate() if appErr == nil { return nil } - installDate, nErr := s.Store.User().InferSystemInstallDate() + installDate, nErr := s.Store().User().InferSystemInstallDate() var installationDate int64 if nErr == nil && installDate > 0 { installationDate = installDate @@ -223,7 +139,7 @@ func (s *Server) ensureInstallationDate() error { installationDate = utils.MillisFromTime(time.Now()) } - if err := s.Store.System().SaveOrUpdate(&model.System{ + if err := s.Store().System().SaveOrUpdate(&model.System{ Name: model.SystemInstallationDateKey, Value: strconv.FormatInt(installationDate, 10), }); err != nil { @@ -238,7 +154,7 @@ func (s *Server) ensureFirstServerRunTimestamp() error { return nil } - if err := s.Store.System().SaveOrUpdate(&model.System{ + if err := s.Store().System().SaveOrUpdate(&model.System{ Name: model.SystemFirstServerRunTimestampKey, Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10), }); err != nil { @@ -249,10 +165,7 @@ func (s *Server) ensureFirstServerRunTimestamp() error { // AsymmetricSigningKey will return a private key that can be used for asymmetric signing. func (ch *Channels) AsymmetricSigningKey() *ecdsa.PrivateKey { - if key := ch.asymmetricSigningKey.Load(); key != nil { - return key.(*ecdsa.PrivateKey) - } - return nil + return ch.srv.platform.AsymmetricSigningKey() } func (a *App) AsymmetricSigningKey() *ecdsa.PrivateKey { @@ -267,32 +180,6 @@ func (a *App) PostActionCookieSecret() []byte { return a.ch.PostActionCookieSecret() } -func (ch *Channels) regenerateClientConfig() { - clientConfig := config.GenerateClientConfig(ch.cfgSvc.Config(), ch.srv.TelemetryId(), ch.srv.License()) - limitedClientConfig := config.GenerateLimitedClientConfig(ch.cfgSvc.Config(), ch.srv.TelemetryId(), ch.srv.License()) - - if clientConfig["EnableCustomTermsOfService"] == "true" { - termsOfService, err := ch.srv.Store.TermsOfService().GetLatest(true) - if err != nil { - mlog.Err(err) - } else { - clientConfig["CustomTermsOfServiceId"] = termsOfService.Id - limitedClientConfig["CustomTermsOfServiceId"] = termsOfService.Id - } - } - - if key := ch.AsymmetricSigningKey(); key != nil { - der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) - clientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) - limitedClientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) - } - - clientConfigJSON, _ := json.Marshal(clientConfig) - ch.clientConfig.Store(clientConfig) - ch.limitedClientConfig.Store(limitedClientConfig) - ch.clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON))) -} - func (a *App) GetCookieDomain() string { if *a.Config().ServiceSettings.AllowCookiesForSubdomains { if siteURL, err := url.Parse(*a.Config().ServiceSettings.SiteURL); err == nil { @@ -306,45 +193,6 @@ func (a *App) GetSiteURL() string { return *a.Config().ServiceSettings.SiteURL } -// ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. -func (a *App) ClientConfigWithComputed() map[string]string { - respCfg := map[string]string{} - for k, v := range a.ch.clientConfig.Load().(map[string]string) { - respCfg[k] = v - } - - // These properties are not configurable, but nevertheless represent configuration expected - // by the client. - respCfg["NoAccounts"] = strconv.FormatBool(a.ch.srv.userService.IsFirstUserAccount()) - respCfg["MaxPostSize"] = strconv.Itoa(a.ch.srv.MaxPostSize()) - respCfg["UpgradedFromTE"] = strconv.FormatBool(a.ch.srv.isUpgradedFromTE()) - respCfg["InstallationDate"] = "" - if installationDate, err := a.ch.srv.getSystemInstallDate(); err == nil { - respCfg["InstallationDate"] = strconv.FormatInt(installationDate, 10) - } - if ver, err := a.ch.srv.Store.GetDBSchemaVersion(); err != nil { - mlog.Error("Could not get the schema version", mlog.Err(err)) - } else { - respCfg["SchemaVersion"] = strconv.Itoa(ver) - } - - return respCfg -} - -// LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. -func (a *App) LimitedClientConfigWithComputed() map[string]string { - respCfg := map[string]string{} - for k, v := range a.LimitedClientConfig() { - respCfg[k] = v - } - - // These properties are not configurable, but nevertheless represent configuration expected - // by the client. - respCfg["NoAccounts"] = strconv.FormatBool(a.IsFirstUserAccount()) - - return respCfg -} - // GetConfigFile proxies access to the given configuration file to the underlying config store. func (a *App) GetConfigFile(name string) ([]byte, error) { data, err := a.Srv().platform.GetConfigFile(name) diff --git a/app/config_test.go b/app/config_test.go index aa019e4281..7f27d3f0a0 100644 --- a/app/config_test.go +++ b/app/config_test.go @@ -33,7 +33,7 @@ func TestClientConfigWithComputed(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -46,7 +46,7 @@ func TestClientConfigWithComputed(t *testing.T) { mockStore.On("System").Return(&mockSystemStore) mockStore.On("GetDBSchemaVersion").Return(1, nil) - config := th.App.ClientConfigWithComputed() + config := th.App.Srv().Platform().ClientConfigWithComputed() _, ok := config["NoAccounts"] assert.True(t, ok, "expected NoAccounts in returned config") _, ok = config["MaxPostSize"] @@ -104,9 +104,9 @@ func TestEnsureInstallationDate(t *testing.T) { } if tc.PrevInstallationDate == nil { - th.App.Srv().Store.System().PermanentDeleteByName(model.SystemInstallationDateKey) + th.App.Srv().Store().System().PermanentDeleteByName(model.SystemInstallationDateKey) } else { - th.App.Srv().Store.System().SaveOrUpdate(&model.System{ + th.App.Srv().Store().System().SaveOrUpdate(&model.System{ Name: model.SystemInstallationDateKey, Value: strconv.FormatInt(*tc.PrevInstallationDate, 10), }) @@ -119,7 +119,7 @@ func TestEnsureInstallationDate(t *testing.T) { } else { assert.NoError(t, err) - data, err := th.App.Srv().Store.System().GetByName(model.SystemInstallationDateKey) + data, err := th.App.Srv().Store().System().GetByName(model.SystemInstallationDateKey) assert.NoError(t, err) value, _ := strconv.ParseInt(data.Value, 10, 64) assert.True(t, *tc.ExpectedInstallationDate <= value && *tc.ExpectedInstallationDate+1000 >= value) diff --git a/app/emoji.go b/app/emoji.go index 25f1d6bece..75376794be 100644 --- a/app/emoji.go +++ b/app/emoji.go @@ -60,7 +60,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, model.NewAppError("createEmoji", "api.emoji.create.other_user.app_error", nil, "", http.StatusForbidden) } - if existingEmoji, err := a.Srv().Store.Emoji().GetByName(context.Background(), emoji.Name, true); err == nil && existingEmoji != nil { + if existingEmoji, err := a.Srv().Store().Emoji().GetByName(context.Background(), emoji.Name, true); err == nil && existingEmoji != nil { return nil, model.NewAppError("createEmoji", "api.emoji.create.duplicate.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -73,7 +73,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma return nil, appErr } - emoji, err := a.Srv().Store.Emoji().Save(emoji) + emoji, err := a.Srv().Store().Emoji().Save(emoji) if err != nil { return nil, model.NewAppError("CreateEmoji", "app.emoji.create.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -89,7 +89,7 @@ func (a *App) CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartIma } func (a *App) GetEmojiList(page, perPage int, sort string) ([]*model.Emoji, *model.AppError) { - list, err := a.Srv().Store.Emoji().GetList(page*perPage, perPage, sort) + list, err := a.Srv().Store().Emoji().GetList(page*perPage, perPage, sort) if err != nil { return nil, model.NewAppError("GetEmojiList", "app.emoji.get_list.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -167,7 +167,7 @@ func (a *App) UploadEmojiImage(id string, imageData *multipart.FileHeader) *mode } func (a *App) DeleteEmoji(emoji *model.Emoji) *model.AppError { - if err := a.Srv().Store.Emoji().Delete(emoji, model.GetMillis()); err != nil { + if err := a.Srv().Store().Emoji().Delete(emoji, model.GetMillis()); err != nil { var nfErr *store.ErrNotFound switch { case errors.As(err, &nfErr): @@ -191,7 +191,7 @@ func (a *App) GetEmoji(emojiId string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmoji", "api.emoji.storage.app_error", nil, "", http.StatusForbidden) } - emoji, err := a.Srv().Store.Emoji().Get(context.Background(), emojiId, true) + emoji, err := a.Srv().Store().Emoji().Get(context.Background(), emojiId, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -214,7 +214,7 @@ func (a *App) GetEmojiByName(emojiName string) (*model.Emoji, *model.AppError) { return nil, model.NewAppError("GetEmojiByName", "api.emoji.storage.app_error", nil, "", http.StatusForbidden) } - emoji, err := a.Srv().Store.Emoji().GetByName(context.Background(), emojiName, true) + emoji, err := a.Srv().Store().Emoji().GetByName(context.Background(), emojiName, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -233,7 +233,7 @@ func (a *App) GetMultipleEmojiByName(names []string) ([]*model.Emoji, *model.App return nil, model.NewAppError("GetMultipleEmojiByName", "api.emoji.disabled.app_error", nil, "", http.StatusForbidden) } - emoji, err := a.Srv().Store.Emoji().GetMultipleByName(names) + emoji, err := a.Srv().Store().Emoji().GetMultipleByName(names) if err != nil { return nil, model.NewAppError("GetMultipleEmojiByName", "app.emoji.get_by_name.app_error", nil, fmt.Sprintf("names=%v, %v", names, err.Error()), http.StatusInternalServerError) } @@ -242,7 +242,7 @@ func (a *App) GetMultipleEmojiByName(names []string) ([]*model.Emoji, *model.App } func (a *App) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) { - _, storeErr := a.Srv().Store.Emoji().Get(context.Background(), emojiId, true) + _, storeErr := a.Srv().Store().Emoji().Get(context.Background(), emojiId, true) if storeErr != nil { var nfErr *store.ErrNotFound switch { @@ -271,7 +271,7 @@ func (a *App) SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emo return nil, model.NewAppError("SearchEmoji", "api.emoji.disabled.app_error", nil, "", http.StatusForbidden) } - list, err := a.Srv().Store.Emoji().Search(name, prefixOnly, limit) + list, err := a.Srv().Store().Emoji().Search(name, prefixOnly, limit) if err != nil { return nil, model.NewAppError("SearchEmoji", "app.emoji.get_by_name.app_error", nil, "name="+name+", "+err.Error(), http.StatusInternalServerError) } @@ -288,7 +288,7 @@ func (a *App) GetEmojiStaticURL(emojiName string) (string, *model.AppError) { return path.Join(subPath, "/static/emoji", id+".png"), nil } - emoji, err := a.Srv().Store.Emoji().GetByName(context.Background(), emojiName, true) + emoji, err := a.Srv().Store().Emoji().GetByName(context.Background(), emojiName, true) if err == nil { return path.Join(subPath, "/api/v4/emoji", emoji.Id, "image"), nil } @@ -349,7 +349,7 @@ func (a *App) deleteEmojiImage(id string) { } func (a *App) deleteReactionsForEmoji(emojiName string) { - if err := a.Srv().Store.Reaction().DeleteAllWithEmojiName(emojiName); err != nil { + if err := a.Srv().Store().Reaction().DeleteAllWithEmojiName(emojiName); err != nil { mlog.Warn("Unable to delete reactions when deleting emoji", mlog.String("emoji_name", emojiName), mlog.Err(err)) } } diff --git a/app/enterprise.go b/app/enterprise.go index 956d220d1e..7f85fe355e 100644 --- a/app/enterprise.go +++ b/app/enterprise.go @@ -6,7 +6,6 @@ package app import ( "github.com/mattermost/mattermost-server/v6/einterfaces" ejobs "github.com/mattermost/mattermost-server/v6/einterfaces/jobs" - "github.com/mattermost/mattermost-server/v6/services/searchengine" ) var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface @@ -15,12 +14,6 @@ func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigration accountMigrationInterface = f } -var clusterInterface func(*Server) einterfaces.ClusterInterface - -func RegisterClusterInterface(f func(*Server) einterfaces.ClusterInterface) { - clusterInterface = f -} - var complianceInterface func(*App) einterfaces.ComplianceInterface func RegisterComplianceInterface(f func(*App) einterfaces.ComplianceInterface) { @@ -33,12 +26,6 @@ func RegisterDataRetentionInterface(f func(*App) einterfaces.DataRetentionInterf dataRetentionInterface = f } -var elasticsearchInterface func(*Server) searchengine.SearchEngineInterface - -func RegisterElasticsearchInterface(f func(*Server) searchengine.SearchEngineInterface) { - elasticsearchInterface = f -} - var jobsDataRetentionJobInterface func(*Server) ejobs.DataRetentionJobInterface func RegisterJobsDataRetentionJobInterface(f func(*Server) ejobs.DataRetentionJobInterface) { @@ -87,12 +74,6 @@ func RegisterCloudInterface(f func(*Server) einterfaces.CloudInterface) { cloudInterface = f } -var metricsInterface func(*Server, string, string) einterfaces.MetricsInterface - -func RegisterMetricsInterface(f func(*Server, string, string) einterfaces.MetricsInterface) { - metricsInterface = f -} - var samlInterfaceNew func(*App) einterfaces.SamlInterface func RegisterNewSamlInterface(f func(*App) einterfaces.SamlInterface) { @@ -105,25 +86,7 @@ func RegisterNotificationInterface(f func(*App) einterfaces.NotificationInterfac notificationInterface = f } -var licenseInterface func(*Server) einterfaces.LicenseInterface - -func RegisterLicenseInterface(f func(*Server) einterfaces.LicenseInterface) { - licenseInterface = f -} - func (s *Server) initEnterprise() { - if clusterInterface != nil && s.Cluster == nil { - s.Cluster = clusterInterface(s) - s.platform.SetCluster(s.Cluster) - } - if elasticsearchInterface != nil { - s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s)) - } - - if licenseInterface != nil { - s.LicenseManager = licenseInterface(s) - } - if cloudInterface != nil { s.Cloud = cloudInterface(s) } diff --git a/app/enterprise_test.go b/app/enterprise_test.go index be2e6d87de..d0cd01daff 100644 --- a/app/enterprise_test.go +++ b/app/enterprise_test.go @@ -68,7 +68,7 @@ func TestSAMLSettings(t *testing.T) { defer th.TearDown() - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockUserStore := storemocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := storemocks.PostStore{} diff --git a/app/expirynotify.go b/app/expirynotify.go index a10f3f0fe5..00e96aa156 100644 --- a/app/expirynotify.go +++ b/app/expirynotify.go @@ -22,7 +22,7 @@ func (a *App) NotifySessionsExpired() error { } // Get all mobile sessions that expired within the last hour. - sessions, err := a.ch.srv.Store.Session().GetSessionsExpired(OneHourMillis, true, true) + sessions, err := a.ch.srv.Store().Session().GetSessionsExpired(OneHourMillis, true, true) if err != nil { return model.NewAppError("NotifySessionsExpired", "app.session.analytics_session_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -62,7 +62,7 @@ func (a *App) NotifySessionsExpired() error { a.Metrics().IncrementPostSentPush() } - err = a.ch.srv.Store.Session().UpdateExpiredNotify(session.Id, true) + err = a.ch.srv.Store().Session().UpdateExpiredNotify(session.Id, true) if err != nil { mlog.Error("Failed to update ExpiredNotify flag", mlog.String("sessionid", session.Id), mlog.Err(err)) } diff --git a/app/export.go b/app/export.go index fb080f0315..f90945885d 100644 --- a/app/export.go +++ b/app/export.go @@ -169,7 +169,7 @@ func (a *App) exportAllTeams(writer io.Writer) (map[string]bool, *model.AppError afterId := strings.Repeat("0", 26) teamNames := make(map[string]bool) for { - teams, err := a.Srv().Store.Team().GetAllForExportAfter(1000, afterId) + teams, err := a.Srv().Store().Team().GetAllForExportAfter(1000, afterId) if err != nil { return nil, model.NewAppError("exportAllTeams", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -200,7 +200,7 @@ func (a *App) exportAllTeams(writer io.Writer) (map[string]bool, *model.AppError func (a *App) exportAllChannels(writer io.Writer, teamNames map[string]bool) *model.AppError { afterId := strings.Repeat("0", 26) for { - channels, err := a.Srv().Store.Channel().GetAllChannelsForExportAfter(1000, afterId) + channels, err := a.Srv().Store().Channel().GetAllChannelsForExportAfter(1000, afterId) if err != nil { return model.NewAppError("exportAllChannels", "app.channel.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -235,7 +235,7 @@ func (a *App) exportAllChannels(writer io.Writer, teamNames map[string]bool) *mo func (a *App) exportAllUsers(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - users, err := a.Srv().Store.User().GetAllAfter(1000, afterId) + users, err := a.Srv().Store().User().GetAllAfter(1000, afterId) if err != nil { return model.NewAppError("exportAllUsers", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -310,7 +310,7 @@ func (a *App) exportAllUsers(writer io.Writer) *model.AppError { func (a *App) buildUserTeamAndChannelMemberships(userID string) (*[]imports.UserTeamImportData, *model.AppError) { var memberships []imports.UserTeamImportData - members, err := a.Srv().Store.Team().GetTeamMembersForExport(userID) + members, err := a.Srv().Store().Team().GetTeamMembersForExport(userID) if err != nil { return nil, model.NewAppError("buildUserTeamAndChannelMemberships", "app.team.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -331,7 +331,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userID string) (*[]imports.User } // Get the user theme - themePreference, nErr := a.Srv().Store.Preference().Get(member.UserId, model.PreferenceCategoryTheme, member.TeamId) + themePreference, nErr := a.Srv().Store().Preference().Get(member.UserId, model.PreferenceCategoryTheme, member.TeamId) if nErr == nil { memberData.Theme = &themePreference.Value } @@ -347,7 +347,7 @@ func (a *App) buildUserTeamAndChannelMemberships(userID string) (*[]imports.User func (a *App) buildUserChannelMemberships(userID string, teamID string) (*[]imports.UserChannelImportData, *model.AppError) { var memberships []imports.UserChannelImportData - members, nErr := a.Srv().Store.Channel().GetChannelMembersForExport(userID, teamID) + members, nErr := a.Srv().Store().Channel().GetChannelMembersForExport(userID, teamID) if nErr != nil { return nil, model.NewAppError("buildUserChannelMemberships", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -390,7 +390,7 @@ func (a *App) exportAllPosts(ctx request.CTX, writer io.Writer, withAttachments afterId := strings.Repeat("0", 26) for { - posts, nErr := a.Srv().Store.Post().GetParentsForExportAfter(1000, afterId) + posts, nErr := a.Srv().Store().Post().GetParentsForExportAfter(1000, afterId) if nErr != nil { return nil, model.NewAppError("exportAllPosts", "app.post.get_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -450,7 +450,7 @@ func (a *App) buildPostReplies(ctx request.CTX, postID string, withAttachments b var replies []imports.ReplyImportData var attachments []imports.AttachmentImportData - replyPosts, nErr := a.Srv().Store.Post().GetRepliesForExport(postID) + replyPosts, nErr := a.Srv().Store().Post().GetRepliesForExport(postID) if nErr != nil { return nil, nil, model.NewAppError("buildPostReplies", "app.post.get_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -484,13 +484,13 @@ func (a *App) buildPostReplies(ctx request.CTX, postID string, withAttachments b func (a *App) BuildPostReactions(ctx request.CTX, postID string) (*[]ReactionImportData, *model.AppError) { var reactionsOfPost []imports.ReactionImportData - reactions, nErr := a.Srv().Store.Reaction().GetForPost(postID, true) + reactions, nErr := a.Srv().Store().Reaction().GetForPost(postID, true) if nErr != nil { return nil, model.NewAppError("BuildPostReactions", "app.reaction.get_for_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } for _, reaction := range reactions { - user, err := a.Srv().Store.User().Get(context.Background(), reaction.UserId) + user, err := a.Srv().Store().User().Get(context.Background(), reaction.UserId) if err != nil { var nfErr *store.ErrNotFound if errors.As(err, &nfErr) { // this is a valid case, the user that reacted might've been deleted by now @@ -507,7 +507,7 @@ func (a *App) BuildPostReactions(ctx request.CTX, postID string) (*[]ReactionImp } func (a *App) buildPostAttachments(postID string) ([]imports.AttachmentImportData, *model.AppError) { - infos, nErr := a.Srv().Store.FileInfo().GetForPost(postID, false, false, false) + infos, nErr := a.Srv().Store().FileInfo().GetForPost(postID, false, false, false) if nErr != nil { return nil, model.NewAppError("buildPostAttachments", "app.file_info.get_for_post.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -604,7 +604,7 @@ func (a *App) copyEmojiImages(emojiId string, emojiImagePath string, pathToDir s func (a *App) exportAllDirectChannels(writer io.Writer) *model.AppError { afterId := strings.Repeat("0", 26) for { - channels, err := a.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, afterId) + channels, err := a.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, afterId) if err != nil { return model.NewAppError("exportAllDirectChannels", "app.channel.get_all_direct.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -640,7 +640,7 @@ func (a *App) exportAllDirectPosts(ctx request.CTX, writer io.Writer, withAttach var attachments []imports.AttachmentImportData afterId := strings.Repeat("0", 26) for { - posts, err := a.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, afterId) + posts, err := a.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, afterId) if err != nil { return nil, model.NewAppError("exportAllDirectPosts", "app.post.get_direct_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/export_test.go b/app/export_test.go index 3ed17d9547..8cc4567f2d 100644 --- a/app/export_test.go +++ b/app/export_test.go @@ -93,7 +93,7 @@ func TestExportUserChannels(t *testing.T) { } var preferences model.Preferences preferences = append(preferences, preference) - err := th.App.Srv().Store.Preference().Save(preferences) + err := th.App.Srv().Store().Preference().Save(preferences) require.NoError(t, err) th.App.UpdateChannelMemberNotifyProps(th.Context, notifyProps, channel.Id, user.Id) @@ -229,14 +229,14 @@ func TestExportDMChannel(t *testing.T) { err := th1.App.BulkExport(th1.Context, &b, "somePath", model.BulkExportOpts{}) require.Nil(t, err) - channels, nErr := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr := th1.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) th2 := Setup(t).InitBasic() defer th2.TearDown() - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 0, len(channels)) @@ -246,7 +246,7 @@ func TestExportDMChannel(t *testing.T) { assert.Equal(t, 0, i) // Ensure the Members of the imported DM channel is the same was from the exported - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) require.Equal(t, 1, len(channels)) assert.ElementsMatch(t, []string{th1.BasicUser.Username, th1.BasicUser2.Username}, *channels[0].Members) @@ -259,7 +259,7 @@ func TestExportDMChannel(t *testing.T) { // DM Channel th1.CreateDmChannel(th1.BasicUser2) - channels, nErr := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr := th1.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) @@ -277,7 +277,7 @@ func TestExportDMChannel(t *testing.T) { err, _ = th2.App.BulkImport(th2.Context, &b, nil, true, 5) require.Nil(t, err) - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Empty(t, channels) }) @@ -294,14 +294,14 @@ func TestExportDMChannelToSelf(t *testing.T) { err := th1.App.BulkExport(th1.Context, &b, "somePath", model.BulkExportOpts{}) require.Nil(t, err) - channels, nErr := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr := th1.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) th2 := Setup(t) defer th2.TearDown() - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 0, len(channels)) @@ -310,7 +310,7 @@ func TestExportDMChannelToSelf(t *testing.T) { assert.Nil(t, err) assert.Equal(t, 0, i) - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) assert.Equal(t, 1, len((*channels[0].Members))) @@ -332,7 +332,7 @@ func TestExportGMChannel(t *testing.T) { err := th1.App.BulkExport(th1.Context, &b, "somePath", model.BulkExportOpts{}) require.Nil(t, err) - channels, nErr := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr := th1.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 1, len(channels)) @@ -341,7 +341,7 @@ func TestExportGMChannel(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 0, len(channels)) } @@ -364,7 +364,7 @@ func TestExportGMandDMChannels(t *testing.T) { err := th1.App.BulkExport(th1.Context, &b, "somePath", model.BulkExportOpts{}) require.Nil(t, err) - channels, nErr := th1.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr := th1.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 2, len(channels)) @@ -373,7 +373,7 @@ func TestExportGMandDMChannels(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) assert.Equal(t, 0, len(channels)) @@ -383,7 +383,7 @@ func TestExportGMandDMChannels(t *testing.T) { assert.Equal(t, 0, i) // Ensure the Members of the imported GM channel is the same was from the exported - channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") + channels, nErr = th2.App.Srv().Store().Channel().GetAllDirectChannelsForExportAfter(1000, "00000000") require.NoError(t, nErr) // Adding some determinism so its possible to assert on slice index @@ -439,7 +439,7 @@ func TestExportDMandGMPost(t *testing.T) { } th1.App.CreatePost(th1.Context, p4, gmChannel, false, true) - posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err := th1.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) assert.Equal(t, 4, len(posts)) @@ -452,7 +452,7 @@ func TestExportDMandGMPost(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) assert.Equal(t, 0, len(posts)) @@ -461,7 +461,7 @@ func TestExportDMandGMPost(t *testing.T) { assert.Nil(t, appErr) assert.Equal(t, 0, i) - posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) // Adding some determinism so its possible to assert on slice index @@ -512,7 +512,7 @@ func TestExportPostWithProps(t *testing.T) { } th1.App.CreatePost(th1.Context, p2, gmChannel, false, true) - posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err := th1.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) assert.Len(t, posts, 2) require.NotEmpty(t, posts[0].Props) @@ -527,7 +527,7 @@ func TestExportPostWithProps(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) assert.Len(t, posts, 0) @@ -536,7 +536,7 @@ func TestExportPostWithProps(t *testing.T) { assert.Nil(t, appErr) assert.Equal(t, 0, i) - posts, err = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, err = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, err) // Adding some determinism so its possible to assert on slice index @@ -560,7 +560,7 @@ func TestExportDMPostWithSelf(t *testing.T) { err := th1.App.BulkExport(th1.Context, &b, "somePath", model.BulkExportOpts{}) require.Nil(t, err) - posts, nErr := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, nErr := th1.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, nErr) assert.Equal(t, 1, len(posts)) @@ -569,7 +569,7 @@ func TestExportDMPostWithSelf(t *testing.T) { th2 := Setup(t) defer th2.TearDown() - posts, nErr = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, nErr = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, nErr) assert.Equal(t, 0, len(posts)) @@ -578,7 +578,7 @@ func TestExportDMPostWithSelf(t *testing.T) { assert.Nil(t, err) assert.Equal(t, 0, i) - posts, nErr = th2.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000") + posts, nErr = th2.App.Srv().Store().Post().GetDirectPostParentsForExportAfter(1000, "0000000") require.NoError(t, nErr) assert.Equal(t, 1, len(posts)) assert.Equal(t, 1, len((*posts[0].ChannelMembers))) @@ -646,7 +646,7 @@ func TestBuildPostReplies(t *testing.T) { createPostWithAttachments := func(th *TestHelper, n int, rootID string) *model.Post { var fileIDs []string for i := 0; i < n; i++ { - info, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + info, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Name: fmt.Sprintf("file%d", i), Path: fmt.Sprintf("/data/file%d", i), diff --git a/app/file.go b/app/file.go index d2520c5f62..b0e68f4921 100644 --- a/app/file.go +++ b/app/file.go @@ -277,7 +277,7 @@ func (a *App) findTeamIdForFilename(post *model.Post, id, filename string) strin name, _ := url.QueryUnescape(filename) // This post is in a direct channel so we need to figure out what team the files are stored under. - teams, err := a.Srv().Store.Team().GetTeamsByUserId(post.UserId) + teams, err := a.Srv().Store().Team().GetTeamsByUserId(post.UserId) if err != nil { mlog.Error("Unable to get teams when migrating post to use FileInfo", mlog.Err(err), mlog.String("post_id", post.Id)) return "" @@ -329,7 +329,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { return []*model.FileInfo{} } - channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) + channel, errCh := a.Srv().Store().Channel().Get(post.ChannelId, true) // There's a weird bug that rarely happens where a post ends up with duplicate Filenames so remove those filenames := utils.RemoveDuplicatesFromStringArray(post.Filenames) if errCh != nil { @@ -382,7 +382,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { fileMigrationLock.Lock() defer fileMigrationLock.Unlock() - result, nErr := a.Srv().Store.Post().Get(context.Background(), post.Id, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) + result, nErr := a.Srv().Store().Post().Get(context.Background(), post.Id, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) if nErr != nil { mlog.Error("Unable to get post when migrating post to use FileInfos", mlog.Err(nErr), mlog.String("post_id", post.Id)) return []*model.FileInfo{} @@ -391,7 +391,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { if newPost := result.Posts[post.Id]; len(newPost.Filenames) != len(post.Filenames) { // Another thread has already created FileInfos for this post, so just return those var fileInfos []*model.FileInfo - fileInfos, nErr = a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, false) + fileInfos, nErr = a.Srv().Store().FileInfo().GetForPost(post.Id, true, false, false) if nErr != nil { mlog.Error("Unable to get FileInfos for migrated post", mlog.Err(nErr), mlog.String("post_id", post.Id)) return []*model.FileInfo{} @@ -406,7 +406,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { savedInfos := make([]*model.FileInfo, 0, len(infos)) fileIDs := make([]string, 0, len(filenames)) for _, info := range infos { - if _, nErr = a.Srv().Store.FileInfo().Save(info); nErr != nil { + if _, nErr = a.Srv().Store().FileInfo().Save(info); nErr != nil { mlog.Error( "Unable to save file info when migrating post to use FileInfos", mlog.String("post_id", post.Id), @@ -428,7 +428,7 @@ func (a *App) MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { newPost.FileIds = fileIDs // Update Posts to clear Filenames and set FileIds - if _, nErr = a.Srv().Store.Post().Update(newPost, post); nErr != nil { + if _, nErr = a.Srv().Store().Post().Update(newPost, post); nErr != nil { mlog.Error( "Unable to save migrated post when migrating to use FileInfos", mlog.String("new_file_ids", strings.Join(newPost.FileIds, ",")), @@ -597,7 +597,7 @@ func (t *UploadFileTask) init(a *App) { t.pluginsEnvironment = a.GetPluginsEnvironment() t.writeFile = a.WriteFile - t.saveToDatabase = a.Srv().Store.FileInfo().Save + t.saveToDatabase = a.Srv().Store().FileInfo().Save } // UploadFileX uploads a single file as specified in t. It applies the upload @@ -922,7 +922,7 @@ func (a *App) DoUploadFileExpectModification(c request.CTX, now time.Time, rawTe return nil, data, err } - if _, err := a.Srv().Store.FileInfo().Save(info); err != nil { + if _, err := a.Srv().Store().FileInfo().Save(info); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -1048,10 +1048,10 @@ func (a *App) generateMiniPreview(fi *model.FileInfo) { } else { fi.MiniPreview = &miniPreview } - if _, err = a.Srv().Store.FileInfo().Upsert(fi); err != nil { + if _, err = a.Srv().Store().FileInfo().Upsert(fi); err != nil { mlog.Debug("creating mini preview failed", mlog.Err(err)) } else { - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(fi.PostId, false) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(fi.PostId, false) } } } @@ -1070,7 +1070,7 @@ func (a *App) generateMiniPreviewForInfos(fileInfos []*model.FileInfo) { } func (s *Server) getFileInfo(fileID string) (*model.FileInfo, *model.AppError) { - fileInfo, err := s.Store.FileInfo().Get(fileID) + fileInfo, err := s.Store().FileInfo().Get(fileID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1111,7 +1111,7 @@ func (a *App) getFileInfoIgnoreCloudLimit(fileID string) (*model.FileInfo, *mode } func (a *App) GetFileInfos(page, perPage int, opt *model.GetFileInfosOptions) ([]*model.FileInfo, *model.AppError) { - fileInfos, err := a.Srv().Store.FileInfo().GetWithOptions(page, perPage, opt) + fileInfos, err := a.Srv().Store().FileInfo().GetWithOptions(page, perPage, opt) if err != nil { var invErr *store.ErrInvalidInput var ltErr *store.ErrLimitExceeded @@ -1174,7 +1174,7 @@ func (a *App) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.A now := model.GetMillis() for _, fileID := range fileIDs { - fileInfo, err := a.Srv().Store.FileInfo().Get(fileID) + fileInfo, err := a.Srv().Store().FileInfo().Get(fileID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1191,7 +1191,7 @@ func (a *App) CopyFileInfos(userID string, fileIDs []string) ([]string, *model.A fileInfo.UpdateAt = now fileInfo.PostId = "" - if _, err := a.Srv().Store.FileInfo().Save(fileInfo); err != nil { + if _, err := a.Srv().Store().FileInfo().Save(fileInfo); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -1286,7 +1286,7 @@ func (a *App) SearchFilesInTeamForUser(c *request.Context, terms string, userId return model.NewFileInfoList(), nil } - fileInfoSearchResults, nErr := a.Srv().Store.FileInfo().Search(finalParamsList, userId, teamId, page, perPage) + fileInfoSearchResults, nErr := a.Srv().Store().FileInfo().Search(finalParamsList, userId, teamId, page, perPage) if nErr != nil { var appErr *model.AppError switch { @@ -1321,14 +1321,14 @@ func (a *App) ExtractContentFromFileInfo(fileInfo *model.FileInfo) error { if len(text) > maxContentExtractionSize { text = text[0:maxContentExtractionSize] } - if storeErr := a.Srv().Store.FileInfo().SetContent(fileInfo.Id, text); storeErr != nil { + if storeErr := a.Srv().Store().FileInfo().SetContent(fileInfo.Id, text); storeErr != nil { return errors.Wrap(storeErr, "failed to save the extracted file content") } - reloadFileInfo, storeErr := a.Srv().Store.FileInfo().Get(fileInfo.Id) + reloadFileInfo, storeErr := a.Srv().Store().FileInfo().Get(fileInfo.Id) if storeErr != nil { mlog.Warn("Failed to invalidate the fileInfo cache.", mlog.Err(storeErr), mlog.String("file_info_id", fileInfo.Id)) } else { - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(reloadFileInfo.PostId, false) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(reloadFileInfo.PostId, false) } } return nil @@ -1341,7 +1341,7 @@ func (a *App) GetLastAccessibleFileTime() (int64, *model.AppError) { return 0, nil } - system, err := a.Srv().Store.System().GetByName(model.SystemLastAccessibleFileTime) + system, err := a.Srv().Store().System().GetByName(model.SystemLastAccessibleFileTime) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1378,7 +1378,7 @@ func (a *App) ComputeLastAccessibleFileTime() error { } // Update Cache - err = a.Srv().Store.System().SaveOrUpdate(&model.System{ + err = a.Srv().Store().System().SaveOrUpdate(&model.System{ Name: model.SystemLastAccessibleFileTime, Value: strconv.FormatInt(createdAt, 10), }) diff --git a/app/file_bench_test.go b/app/file_bench_test.go index 608bd1eb31..2ab58f51aa 100644 --- a/app/file_bench_test.go +++ b/app/file_bench_test.go @@ -87,7 +87,7 @@ func BenchmarkUploadFile(b *testing.B) { if err != nil { b.Fatal(err) } - th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }, @@ -106,7 +106,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -124,7 +124,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -141,7 +141,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, @@ -158,7 +158,7 @@ func BenchmarkUploadFile(b *testing.B) { if aerr != nil { b.Fatal(aerr) } - th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }, }, diff --git a/app/file_helper_test.go b/app/file_helper_test.go index 57842ccdbb..c426132fef 100644 --- a/app/file_helper_test.go +++ b/app/file_helper_test.go @@ -14,7 +14,7 @@ import ( func TestFilterInaccessibleFiles(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessibleFileTime, Value: "2", }) @@ -116,7 +116,7 @@ func TestFilterInaccessibleFiles(t *testing.T) { func TestGetFilteredAccessibleFiles(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessibleFileTime, Value: "2", }) @@ -157,7 +157,7 @@ func TestGetFilteredAccessibleFiles(t *testing.T) { func TestIsInaccessibleFile(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessibleFileTime, Value: "2", }) @@ -178,7 +178,7 @@ func TestIsInaccessibleFile(t *testing.T) { func TestRemoveInaccessibleContentFromFilesSlice(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessibleFileTime, Value: "2", }) diff --git a/app/file_test.go b/app/file_test.go index c30a2df471..599c4c6da1 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -56,7 +56,7 @@ func TestDoUploadFile(t *testing.T) { info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -66,7 +66,7 @@ func TestDoUploadFile(t *testing.T) { info2, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info2.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info2.Id) th.App.RemoveFile(info2.Path) }() @@ -76,7 +76,7 @@ func TestDoUploadFile(t *testing.T) { info3, err := th.App.DoUploadFile(th.Context, time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info3.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info3.Id) th.App.RemoveFile(info3.Path) }() @@ -86,7 +86,7 @@ func TestDoUploadFile(t *testing.T) { info4, err := th.App.DoUploadFile(th.Context, time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamID, "../../"+channelID, "../../"+userID, "../../"+filename, data) require.Nil(t, err, "DoUploadFile should succeed with valid data") defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info4.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info4.Id) th.App.RemoveFile(info4.Path) }() @@ -113,7 +113,7 @@ func TestUploadFile(t *testing.T) { info1, err = th.App.UploadFile(th.Context, data, channelID, filename) require.Nil(t, err, "UploadFile should succeed with valid data") defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -309,7 +309,7 @@ func TestCopyFileInfos(t *testing.T) { info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -319,7 +319,7 @@ func TestCopyFileInfos(t *testing.T) { info2, err := th.App.GetFileInfo(infoIds[0]) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info2.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info2.Id) th.App.RemoveFile(info2.Path) }() @@ -365,7 +365,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) { fileInfos := make([]*model.FileInfo, 7) for i := 0; i < cap(fileInfos); i++ { - fileInfo, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + fileInfo, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, PostId: th.BasicPost.Id, Name: searchTerm, @@ -448,9 +448,9 @@ func TestSearchFilesInTeamForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierFiles) @@ -476,9 +476,9 @@ func TestSearchFilesInTeamForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierFiles) @@ -501,9 +501,9 @@ func TestSearchFilesInTeamForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierFiles) @@ -534,9 +534,9 @@ func TestSearchFilesInTeamForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierFiles) @@ -567,7 +567,7 @@ func TestGetLastAccessibleFileTime(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockSystemStore := storemocks.SystemStore{} mockStore.On("System").Return(&mockSystemStore) @@ -605,7 +605,7 @@ func TestComputeLastAccessibleFileTime(t *testing.T) { }, }, nil) - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockFileStore := storemocks.FileInfoStore{} mockFileStore.On("GetUptoNSizeFileTime", mock.Anything).Return(int64(1), nil) mockSystemStore := storemocks.SystemStore{} diff --git a/app/group.go b/app/group.go index 4a1829cef4..beead51982 100644 --- a/app/group.go +++ b/app/group.go @@ -14,7 +14,7 @@ import ( ) func (a *App) GetGroup(id string, opts *model.GetGroupOpts) (*model.Group, *model.AppError) { - group, err := a.Srv().Store.Group().Get(id) + group, err := a.Srv().Store().Group().Get(id) if err != nil { var nfErr *store.ErrNotFound switch { @@ -26,7 +26,7 @@ func (a *App) GetGroup(id string, opts *model.GetGroupOpts) (*model.Group, *mode } if opts != nil && opts.IncludeMemberCount { - memberCount, err := a.Srv().Store.Group().GetMemberCount(id) + memberCount, err := a.Srv().Store().Group().GetMemberCount(id) if err != nil { return nil, model.NewAppError("GetGroup", "app.member_count", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -37,7 +37,7 @@ func (a *App) GetGroup(id string, opts *model.GetGroupOpts) (*model.Group, *mode } func (a *App) GetGroupByName(name string, opts model.GroupSearchOpts) (*model.Group, *model.AppError) { - group, err := a.Srv().Store.Group().GetByName(name, opts) + group, err := a.Srv().Store().Group().GetByName(name, opts) if err != nil { var nfErr *store.ErrNotFound switch { @@ -52,7 +52,7 @@ func (a *App) GetGroupByName(name string, opts model.GroupSearchOpts) (*model.Gr } func (a *App) GetGroupByRemoteID(remoteID string, groupSource model.GroupSource) (*model.Group, *model.AppError) { - group, err := a.Srv().Store.Group().GetByRemoteID(remoteID, groupSource) + group, err := a.Srv().Store().Group().GetByRemoteID(remoteID, groupSource) if err != nil { var nfErr *store.ErrNotFound switch { @@ -67,7 +67,7 @@ func (a *App) GetGroupByRemoteID(remoteID string, groupSource model.GroupSource) } func (a *App) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) { - groups, err := a.Srv().Store.Group().GetAllBySource(groupSource) + groups, err := a.Srv().Store().Group().GetAllBySource(groupSource) if err != nil { return nil, model.NewAppError("GetGroupsBySource", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -76,7 +76,7 @@ func (a *App) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, } func (a *App) GetGroupsByUserId(userID string) ([]*model.Group, *model.AppError) { - groups, err := a.Srv().Store.Group().GetByUser(userID) + groups, err := a.Srv().Store().Group().GetByUser(userID) if err != nil { return nil, model.NewAppError("GetGroupsByUserId", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -90,7 +90,7 @@ func (a *App) CreateGroup(group *model.Group) (*model.Group, *model.AppError) { return nil, err } - group, err := a.Srv().Store.Group().Create(group) + group, err := a.Srv().Store().Group().Create(group) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -112,7 +112,7 @@ func (a *App) isUniqueToUsernames(val string) *model.AppError { return nil } var notFoundErr *store.ErrNotFound - user, err := a.Srv().Store.User().GetByUsername(val) + user, err := a.Srv().Store().User().GetByUsername(val) if err != nil && !errors.As(err, ¬FoundErr) { return model.NewAppError("isUniqueToUsernames", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -128,7 +128,7 @@ func (a *App) CreateGroupWithUserIds(group *model.GroupWithUserIds) (*model.Grou return nil, appErr } - newGroup, err := a.Srv().Store.Group().CreateWithUserIds(group) + newGroup, err := a.Srv().Store().Group().CreateWithUserIds(group) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -146,7 +146,8 @@ func (a *App) CreateGroupWithUserIds(group *model.GroupWithUserIds) (*model.Grou } messageWs := model.NewWebSocketEvent(model.WebsocketEventReceivedGroup, "", "", "", nil, "") - count, err := a.Srv().Store.Group().GetMemberCount(newGroup.Id) + count, err := a.Srv().Store().Group().GetMemberCount(newGroup.Id) + if err != nil { return nil, model.NewAppError("CreateGroupWithUserIds", "app.group.id.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -167,7 +168,7 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) { return nil, appErr } - updatedGroup, err := a.Srv().Store.Group().Update(group) + updatedGroup, err := a.Srv().Store().Group().Update(group) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -184,7 +185,7 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) { } } - count, err := a.Srv().Store.Group().GetMemberCount(updatedGroup.Id) + count, err := a.Srv().Store().Group().GetMemberCount(updatedGroup.Id) if err != nil { return nil, model.NewAppError("UpdateGroup", "app.group.id.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -203,7 +204,7 @@ func (a *App) UpdateGroup(group *model.Group) (*model.Group, *model.AppError) { } func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) { - deletedGroup, err := a.Srv().Store.Group().Delete(groupID) + deletedGroup, err := a.Srv().Store().Group().Delete(groupID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -218,7 +219,7 @@ func (a *App) DeleteGroup(groupID string) (*model.Group, *model.AppError) { } func (a *App) GetGroupMemberCount(groupID string) (int64, *model.AppError) { - count, err := a.Srv().Store.Group().GetMemberCount(groupID) + count, err := a.Srv().Store().Group().GetMemberCount(groupID) if err != nil { return 0, model.NewAppError("GetGroupMemberCount", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -227,7 +228,7 @@ func (a *App) GetGroupMemberCount(groupID string) (int64, *model.AppError) { } func (a *App) GetGroupMemberUsers(groupID string) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.Group().GetMemberUsers(groupID) + users, err := a.Srv().Store().Group().GetMemberUsers(groupID) if err != nil { return nil, model.NewAppError("GetGroupMemberUsers", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -236,7 +237,7 @@ func (a *App) GetGroupMemberUsers(groupID string) ([]*model.User, *model.AppErro } func (a *App) GetGroupMemberUsersPage(groupID string, page int, perPage int) ([]*model.User, int, *model.AppError) { - members, err := a.Srv().Store.Group().GetMemberUsersPage(groupID, page, perPage) + members, err := a.Srv().Store().Group().GetMemberUsersPage(groupID, page, perPage) if err != nil { return nil, 0, model.NewAppError("GetGroupMemberUsersPage", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -248,7 +249,7 @@ func (a *App) GetGroupMemberUsersPage(groupID string, page int, perPage int) ([] return a.sanitizeProfiles(members, false), int(count), nil } func (a *App) GetUsersNotInGroupPage(groupID string, page int, perPage int) ([]*model.User, *model.AppError) { - members, err := a.Srv().Store.Group().GetNonMemberUsersPage(groupID, page, perPage) + members, err := a.Srv().Store().Group().GetNonMemberUsersPage(groupID, page, perPage) if err != nil { return nil, model.NewAppError("GetUsersNotInGroupPage", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -257,7 +258,7 @@ func (a *App) GetUsersNotInGroupPage(groupID string, page int, perPage int) ([]* } func (a *App) UpsertGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) { - groupMember, err := a.Srv().Store.Group().UpsertMember(groupID, userID) + groupMember, err := a.Srv().Store().Group().UpsertMember(groupID, userID) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -279,7 +280,7 @@ func (a *App) UpsertGroupMember(groupID string, userID string) (*model.GroupMemb } func (a *App) DeleteGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError) { - groupMember, err := a.Srv().Store.Group().DeleteMember(groupID, userID) + groupMember, err := a.Srv().Store().Group().DeleteMember(groupID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -298,7 +299,7 @@ func (a *App) DeleteGroupMember(groupID string, userID string) (*model.GroupMemb } func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) { - gs, err := a.Srv().Store.Group().GetGroupSyncable(groupSyncable.GroupId, groupSyncable.SyncableId, groupSyncable.Type) + gs, err := a.Srv().Store().Group().GetGroupSyncable(groupSyncable.GroupId, groupSyncable.SyncableId, groupSyncable.Type) var notFoundErr *store.ErrNotFound if err != nil && !errors.As(err, ¬FoundErr) { return nil, model.NewAppError("UpsertGroupSyncable", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -306,7 +307,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr // reject the syncable creation if the group isn't already associated to the parent team if groupSyncable.Type == model.GroupSyncableTypeChannel { - channel, nErr := a.Srv().Store.Channel().Get(groupSyncable.SyncableId, true) + channel, nErr := a.Srv().Store().Channel().Get(groupSyncable.SyncableId, true) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -318,7 +319,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } var team *model.Team - team, nErr = a.Srv().Store.Team().Get(channel.TeamId) + team, nErr = a.Srv().Store().Team().Get(channel.TeamId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -330,7 +331,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } if team.IsGroupConstrained() { var teamGroups []*model.GroupWithSchemeAdmin - teamGroups, err = a.Srv().Store.Group().GetGroupsByTeam(channel.TeamId, model.GroupSearchOpts{}) + teamGroups, err = a.Srv().Store().Group().GetGroupsByTeam(channel.TeamId, model.GroupSearchOpts{}) if err != nil { return nil, model.NewAppError("UpsertGroupSyncable", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -353,7 +354,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } if gs == nil { - gs, err = a.Srv().Store.Group().CreateGroupSyncable(groupSyncable) + gs, err = a.Srv().Store().Group().CreateGroupSyncable(groupSyncable) if err != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -367,7 +368,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } } } else { - gs, err = a.Srv().Store.Group().UpdateGroupSyncable(groupSyncable) + gs, err = a.Srv().Store().Group().UpdateGroupSyncable(groupSyncable) if err != nil { var appErr *model.AppError switch { @@ -392,7 +393,7 @@ func (a *App) UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } func (a *App) GetGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) { - group, err := a.Srv().Store.Group().GetGroupSyncable(groupID, syncableID, syncableType) + group, err := a.Srv().Store().Group().GetGroupSyncable(groupID, syncableID, syncableType) if err != nil { var nfErr *store.ErrNotFound switch { @@ -407,7 +408,7 @@ func (a *App) GetGroupSyncable(groupID string, syncableID string, syncableType m } func (a *App) GetGroupSyncables(groupID string, syncableType model.GroupSyncableType) ([]*model.GroupSyncable, *model.AppError) { - groups, err := a.Srv().Store.Group().GetAllGroupSyncablesByGroupId(groupID, syncableType) + groups, err := a.Srv().Store().Group().GetAllGroupSyncablesByGroupId(groupID, syncableType) if err != nil { return nil, model.NewAppError("GetGroupSyncables", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -418,7 +419,7 @@ func (a *App) GetGroupSyncables(groupID string, syncableType model.GroupSyncable func (a *App) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) { if groupSyncable.DeleteAt == 0 { // updating a *deleted* GroupSyncable, so no need to ensure the GroupTeam is present (as done in the upsert) - gs, err := a.Srv().Store.Group().UpdateGroupSyncable(groupSyncable) + gs, err := a.Srv().Store().Group().UpdateGroupSyncable(groupSyncable) if err != nil { var appErr *model.AppError switch { @@ -442,7 +443,7 @@ func (a *App) UpdateGroupSyncable(groupSyncable *model.GroupSyncable) (*model.Gr } func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableType model.GroupSyncableType) (*model.GroupSyncable, *model.AppError) { - gs, err := a.Srv().Store.Group().DeleteGroupSyncable(groupID, syncableID, syncableType) + gs, err := a.Srv().Store().Group().DeleteGroupSyncable(groupID, syncableID, syncableType) if err != nil { var invErr *store.ErrInvalidInput var nfErr *store.ErrNotFound @@ -458,13 +459,13 @@ func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableTyp // if a GroupTeam is being deleted delete all associated GroupChannels if gs.Type == model.GroupSyncableTypeTeam { - allGroupChannels, err := a.Srv().Store.Group().GetAllGroupSyncablesByGroupId(gs.GroupId, model.GroupSyncableTypeChannel) + allGroupChannels, err := a.Srv().Store().Group().GetAllGroupSyncablesByGroupId(gs.GroupId, model.GroupSyncableTypeChannel) if err != nil { return nil, model.NewAppError("DeleteGroupSyncable", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } for _, groupChannel := range allGroupChannels { - _, err = a.Srv().Store.Group().DeleteGroupSyncable(groupChannel.GroupId, groupChannel.SyncableId, groupChannel.Type) + _, err = a.Srv().Store().Group().DeleteGroupSyncable(groupChannel.GroupId, groupChannel.SyncableId, groupChannel.Type) if err != nil { var invErr *store.ErrInvalidInput var nfErr *store.ErrNotFound @@ -500,7 +501,7 @@ func (a *App) DeleteGroupSyncable(groupID string, syncableID string, syncableTyp // If includeRemovedMembers is true, then team members who left or were removed from the team will // be included; otherwise, they will be excluded. func (a *App) TeamMembersToAdd(since int64, teamID *string, includeRemovedMembers bool) ([]*model.UserTeamIDPair, *model.AppError) { - userTeams, err := a.Srv().Store.Group().TeamMembersToAdd(since, teamID, includeRemovedMembers) + userTeams, err := a.Srv().Store().Group().TeamMembersToAdd(since, teamID, includeRemovedMembers) if err != nil { return nil, model.NewAppError("TeamMembersToAdd", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -515,7 +516,7 @@ func (a *App) TeamMembersToAdd(since int64, teamID *string, includeRemovedMember // If includeRemovedMembers is true, then channel members who left or were removed from the channel will // be included; otherwise, they will be excluded. func (a *App) ChannelMembersToAdd(since int64, channelID *string, includeRemovedMembers bool) ([]*model.UserChannelIDPair, *model.AppError) { - userChannels, err := a.Srv().Store.Group().ChannelMembersToAdd(since, channelID, includeRemovedMembers) + userChannels, err := a.Srv().Store().Group().ChannelMembersToAdd(since, channelID, includeRemovedMembers) if err != nil { return nil, model.NewAppError("ChannelMembersToAdd", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -524,7 +525,7 @@ func (a *App) ChannelMembersToAdd(since int64, channelID *string, includeRemoved } func (a *App) TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError) { - teamMembers, err := a.Srv().Store.Group().TeamMembersToRemove(teamID) + teamMembers, err := a.Srv().Store().Group().TeamMembersToRemove(teamID) if err != nil { return nil, model.NewAppError("TeamMembersToRemove", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -533,7 +534,7 @@ func (a *App) TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.A } func (a *App) ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *model.AppError) { - channelMembers, err := a.Srv().Store.Group().ChannelMembersToRemove(teamID) + channelMembers, err := a.Srv().Store().Group().ChannelMembersToRemove(teamID) if err != nil { return nil, model.NewAppError("ChannelMembersToRemove", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -542,12 +543,12 @@ func (a *App) ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *m } func (a *App) GetGroupsByChannel(channelID string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) { - groups, err := a.Srv().Store.Group().GetGroupsByChannel(channelID, opts) + groups, err := a.Srv().Store().Group().GetGroupsByChannel(channelID, opts) if err != nil { return nil, 0, model.NewAppError("GetGroupsByChannel", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } - count, err := a.Srv().Store.Group().CountGroupsByChannel(channelID, opts) + count, err := a.Srv().Store().Group().CountGroupsByChannel(channelID, opts) if err != nil { return nil, 0, model.NewAppError("GetGroupsByChannel", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -557,12 +558,12 @@ func (a *App) GetGroupsByChannel(channelID string, opts model.GroupSearchOpts) ( // GetGroupsByTeam returns the paged list and the total count of group associated to the given team. func (a *App) GetGroupsByTeam(teamID string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) { - groups, err := a.Srv().Store.Group().GetGroupsByTeam(teamID, opts) + groups, err := a.Srv().Store().Group().GetGroupsByTeam(teamID, opts) if err != nil { return nil, 0, model.NewAppError("GetGroupsByTeam", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } - count, err := a.Srv().Store.Group().CountGroupsByTeam(teamID, opts) + count, err := a.Srv().Store().Group().CountGroupsByTeam(teamID, opts) if err != nil { return nil, 0, model.NewAppError("GetGroupsByTeam", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -571,7 +572,7 @@ func (a *App) GetGroupsByTeam(teamID string, opts model.GroupSearchOpts) ([]*mod } func (a *App) GetGroupsAssociatedToChannelsByTeam(teamID string, opts model.GroupSearchOpts) (map[string][]*model.GroupWithSchemeAdmin, *model.AppError) { - groupsAssociatedByChannelId, err := a.Srv().Store.Group().GetGroupsAssociatedToChannelsByTeam(teamID, opts) + groupsAssociatedByChannelId, err := a.Srv().Store().Group().GetGroupsAssociatedToChannelsByTeam(teamID, opts) if err != nil { return nil, model.NewAppError("GetGroupsAssociatedToChannelsByTeam", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -580,7 +581,7 @@ func (a *App) GetGroupsAssociatedToChannelsByTeam(teamID string, opts model.Grou } func (a *App) GetGroups(page, perPage int, opts model.GroupSearchOpts) ([]*model.Group, *model.AppError) { - groups, err := a.Srv().Store.Group().GetGroups(page, perPage, opts) + groups, err := a.Srv().Store().Group().GetGroups(page, perPage, opts) if err != nil { return nil, model.NewAppError("GetGroups", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -594,7 +595,7 @@ func (a *App) GetGroups(page, perPage int, opts model.GroupSearchOpts) ([]*model // The result can be used, for example, to determine the set of users who would be removed from a team if the team // were group-constrained with the given groups. func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) { - users, err := a.Srv().Store.Group().TeamMembersMinusGroupMembers(teamID, groupIDs, page, perPage) + users, err := a.Srv().Store().Group().TeamMembersMinusGroupMembers(teamID, groupIDs, page, perPage) if err != nil { return nil, 0, model.NewAppError("TeamMembersMinusGroupMembers", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -640,7 +641,7 @@ func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, pag } } - totalCount, err := a.Srv().Store.Group().CountTeamMembersMinusGroupMembers(teamID, groupIDs) + totalCount, err := a.Srv().Store().Group().CountTeamMembersMinusGroupMembers(teamID, groupIDs) if err != nil { return nil, 0, model.NewAppError("TeamMembersMinusGroupMembers", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -648,7 +649,7 @@ func (a *App) TeamMembersMinusGroupMembers(teamID string, groupIDs []string, pag } func (a *App) GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) { - groups, err := a.Srv().Store.Group().GetByIDs(groupIDs) + groups, err := a.Srv().Store().Group().GetByIDs(groupIDs) if err != nil { return nil, model.NewAppError("GetGroupsByIDs", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -662,7 +663,7 @@ func (a *App) GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError // The result can be used, for example, to determine the set of users who would be removed from a channel if the // channel were group-constrained with the given groups. func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []string, page, perPage int) ([]*model.UserWithGroups, int64, *model.AppError) { - users, err := a.Srv().Store.Group().ChannelMembersMinusGroupMembers(channelID, groupIDs, page, perPage) + users, err := a.Srv().Store().Group().ChannelMembersMinusGroupMembers(channelID, groupIDs, page, perPage) if err != nil { return nil, 0, model.NewAppError("ChannelMembersMinusGroupMembers", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -708,7 +709,7 @@ func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []strin } } - totalCount, err := a.Srv().Store.Group().CountChannelMembersMinusGroupMembers(channelID, groupIDs) + totalCount, err := a.Srv().Store().Group().CountChannelMembersMinusGroupMembers(channelID, groupIDs) if err != nil { return nil, 0, model.NewAppError("ChannelMembersMinusGroupMembers", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -718,7 +719,7 @@ func (a *App) ChannelMembersMinusGroupMembers(channelID string, groupIDs []strin // UserIsInAdminRoleGroup returns true at least one of the user's groups are configured to set the members as // admins in the given syncable. func (a *App) UserIsInAdminRoleGroup(userID, syncableID string, syncableType model.GroupSyncableType) (bool, *model.AppError) { - groupIDs, err := a.Srv().Store.Group().AdminRoleGroupsForSyncableMember(userID, syncableID, syncableType) + groupIDs, err := a.Srv().Store().Group().AdminRoleGroupsForSyncableMember(userID, syncableID, syncableType) if err != nil { return false, model.NewAppError("UserIsInAdminRoleGroup", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -731,7 +732,7 @@ func (a *App) UserIsInAdminRoleGroup(userID, syncableID string, syncableType mod } func (a *App) UpsertGroupMembers(groupID string, userIDs []string) ([]*model.GroupMember, *model.AppError) { - members, err := a.Srv().Store.Group().UpsertMembers(groupID, userIDs) + members, err := a.Srv().Store().Group().UpsertMembers(groupID, userIDs) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -755,7 +756,7 @@ func (a *App) UpsertGroupMembers(groupID string, userIDs []string) ([]*model.Gro } func (a *App) DeleteGroupMembers(groupID string, userIDs []string) ([]*model.GroupMember, *model.AppError) { - members, err := a.Srv().Store.Group().DeleteMembers(groupID, userIDs) + members, err := a.Srv().Store().Group().DeleteMembers(groupID, userIDs) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError diff --git a/app/helper_test.go b/app/helper_test.go index 7de517ea58..fdf590cc2f 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -22,7 +22,6 @@ import ( "github.com/mattermost/mattermost-server/v6/plugin" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" - "github.com/mattermost/mattermost-server/v6/store/localcachelayer" "github.com/mattermost/mattermost-server/v6/store/sqlstore" "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" "github.com/mattermost/mattermost-server/v6/testlib" @@ -68,13 +67,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo options = append(options, ConfigStore(configStore)) if includeCacheLayer { // Adds the cache layer to the test store - options = append(options, StoreOverride(func(s *Server) store.Store { - lcl, err2 := localcachelayer.NewLocalCacheLayer(dbStore, s.GetMetrics(), s.Cluster, s.CacheProvider) - if err2 != nil { - panic(err2) - } - return lcl - })) + options = append(options, StoreOverrideWithCache(dbStore)) } else { options = append(options, StoreOverride(dbStore)) } @@ -117,9 +110,9 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) - th.App.Srv().SearchEngine = mainHelper.SearchEngine + th.App.Srv().Platform().SearchEngine = mainHelper.SearchEngine - th.App.Srv().Store.MarkSystemRanUnitTests() + th.App.Srv().Store().MarkSystemRanUnitTests() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -179,7 +172,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) emptyMockStore.On("Status").Return(&statusMock) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -194,7 +187,7 @@ func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper { emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) emptyMockStore.On("Status").Return(&statusMock) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -207,7 +200,7 @@ func SetupWithClusterMock(tb testing.TB, cluster einterfaces.ClusterInterface) * dbStore.MarkSystemRanUnitTests() mainHelper.PreloadMigrations() - return setupTestHelper(dbStore, true, true, []Option{setCluster(cluster)}, tb) + return setupTestHelper(dbStore, true, true, []Option{SetCluster(cluster)}, tb) } var initBasicOnce sync.Once @@ -506,7 +499,7 @@ func (th *TestHelper) CreateGroup() *model.Group { } func (th *TestHelper) CreateEmoji() *model.Emoji { - emoji, err := th.App.Srv().Store.Emoji().Save(&model.Emoji{ + emoji, err := th.App.Srv().Store().Emoji().Save(&model.Emoji{ CreatorId: th.BasicUser.Id, Name: model.NewRandomString(10), }) @@ -609,13 +602,13 @@ func (*TestHelper) ResetEmojisMigration() { } func (th *TestHelper) CheckTeamCount(t *testing.T, expected int64) { - teamCount, err := th.App.Srv().Store.Team().AnalyticsTeamCount(nil) + teamCount, err := th.App.Srv().Store().Team().AnalyticsTeamCount(nil) require.NoError(t, err, "Failed to get team count.") require.Equalf(t, teamCount, expected, "Unexpected number of teams. Expected: %v, found: %v", expected, teamCount) } func (th *TestHelper) CheckChannelsCount(t *testing.T, expected int64) { - count, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) + count, err := th.App.Srv().Store().Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) require.NoError(t, err, "Failed to get channel count.") require.Equalf(t, count, expected, "Unexpected number of channels. Expected: %v, found: %v", expected, count) } diff --git a/app/import.go b/app/import.go index 7f613ee5aa..832524aa99 100644 --- a/app/import.go +++ b/app/import.go @@ -177,8 +177,8 @@ func (a *App) bulkImport(c request.CTX, jsonlReader io.Reader, attachmentsReader lineNumber := 0 - a.Srv().Store.LockToMaster() - defer a.Srv().Store.UnlockFromMaster() + a.Srv().Store().LockToMaster() + defer a.Srv().Store().UnlockFromMaster() errorsChan := make(chan imports.LineImportWorkerError, (2*workers)+1) // size chosen to ensure it never gets filled up completely. var wg sync.WaitGroup diff --git a/app/import_functions.go b/app/import_functions.go index 240c01ba34..976acea62c 100644 --- a/app/import_functions.go +++ b/app/import_functions.go @@ -170,7 +170,7 @@ func (a *App) importTeam(c request.CTX, data *imports.TeamImportData, dryRun boo } var team *model.Team - team, err := a.Srv().Store.Team().GetByName(*data.Name) + team, err := a.Srv().Store().Team().GetByName(*data.Name) if err != nil { team = &model.Team{} @@ -237,13 +237,13 @@ func (a *App) importChannel(c request.CTX, data *imports.ChannelImportData, dryR return nil } - team, err := a.Srv().Store.Team().GetByName(*data.Team) + team, err := a.Srv().Store().Team().GetByName(*data.Team) if err != nil { return model.NewAppError("BulkImport", "app.import.import_channel.team_not_found.error", map[string]any{"TeamName": *data.Team}, "", http.StatusBadRequest).Wrap(err) } var channel *model.Channel - if result, err := a.Srv().Store.Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); err == nil { + if result, err := a.Srv().Store().Channel().GetByNameIncludeDeleted(team.Id, *data.Name, true); err == nil { channel = result } else { channel = &model.Channel{} @@ -311,7 +311,7 @@ func (a *App) importUser(c request.CTX, data *imports.UserImportData, dryRun boo var user *model.User var nErr error - user, nErr = a.Srv().Store.User().GetByUsername(*data.Username) + user, nErr = a.Srv().Store().User().GetByUsername(*data.Username) if nErr != nil { user = &model.User{} user.MakeNonNil() @@ -520,7 +520,7 @@ func (a *App) importUser(c request.CTX, data *imports.UserImportData, dryRun boo } pref := model.Preference{UserId: savedUser.Id, Category: model.PreferenceCategoryTutorialSteps, Name: savedUser.Id, Value: "0"} - if err := a.Srv().Store.Preference().Save(model.Preferences{pref}); err != nil { + if err := a.Srv().Store().Preference().Save(model.Preferences{pref}); err != nil { c.Logger().Warn("Encountered error saving tutorial preference", mlog.Err(err)) } @@ -550,7 +550,7 @@ func (a *App) importUser(c request.CTX, data *imports.UserImportData, dryRun boo } } else { if hasUserAuthDataChanged { - if _, nErr := a.Srv().Store.User().UpdateAuthData(user.Id, authService, authData, user.Email, false); nErr != nil { + if _, nErr := a.Srv().Store().User().UpdateAuthData(user.Id, authService, authData, user.Email, false); nErr != nil { var invErr *store.ErrInvalidInput switch { case errors.As(nErr, &invErr): @@ -723,7 +723,7 @@ func (a *App) importUser(c request.CTX, data *imports.UserImportData, dryRun boo } if len(preferences) > 0 { - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { return model.NewAppError("BulkImport", "app.import.import_user.save_preferences.error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -755,7 +755,7 @@ func (a *App) importUserTeams(c request.CTX, user *model.User, data *[]imports.U isGuestByTeamId := map[string]bool{} isUserByTeamId := map[string]bool{} isAdminByTeamId := map[string]bool{} - existingMemberships, nErr := a.Srv().Store.Team().GetTeamsForUser(context.Background(), user.Id, "", true) + existingMemberships, nErr := a.Srv().Store().Team().GetTeamsForUser(context.Background(), user.Id, "", true) if nErr != nil { return model.NewAppError("importUserTeams", "app.team.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -833,7 +833,7 @@ func (a *App) importUserTeams(c request.CTX, user *model.User, data *[]imports.U } } - oldMembers, nErr := a.Srv().Store.Team().UpdateMultipleMembers(oldTeamMembers) + oldMembers, nErr := a.Srv().Store().Team().UpdateMultipleMembers(oldTeamMembers) if nErr != nil { var appErr *model.AppError switch { @@ -847,7 +847,7 @@ func (a *App) importUserTeams(c request.CTX, user *model.User, data *[]imports.U newMembers := []*model.TeamMember{} if len(newTeamMembers) > 0 { var nErr error - newMembers, nErr = a.Srv().Store.Team().SaveMultipleMembers(newTeamMembers, *a.Config().TeamSettings.MaxUsersPerTeam) + newMembers, nErr = a.Srv().Store().Team().SaveMultipleMembers(newTeamMembers, *a.Config().TeamSettings.MaxUsersPerTeam) if nErr != nil { var appErr *model.AppError var conflictErr *store.ErrConflict @@ -878,7 +878,7 @@ func (a *App) importUserTeams(c request.CTX, user *model.User, data *[]imports.U for _, team := range allTeams { if len(teamThemePreferencesByID[team.Id]) > 0 { pref := teamThemePreferencesByID[team.Id] - if err := a.Srv().Store.Preference().Save(pref); err != nil { + if err := a.Srv().Store().Preference().Save(pref); err != nil { return model.NewAppError("BulkImport", "app.import.import_user_teams.save_preferences.error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -914,7 +914,7 @@ func (a *App) importUserChannels(c request.CTX, user *model.User, team *model.Te isGuestByChannelId := map[string]bool{} isUserByChannelId := map[string]bool{} isAdminByChannelId := map[string]bool{} - existingMemberships, nErr := a.Srv().Store.Channel().GetMembersForUser(team.Id, user.Id) + existingMemberships, nErr := a.Srv().Store().Channel().GetMembersForUser(team.Id, user.Id) if nErr != nil { return model.NewAppError("importUserChannels", "app.channel.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1005,7 +1005,7 @@ func (a *App) importUserChannels(c request.CTX, user *model.User, team *model.Te } } - oldMembers, nErr := a.Srv().Store.Channel().UpdateMultipleMembers(oldChannelMembers) + oldMembers, nErr := a.Srv().Store().Channel().UpdateMultipleMembers(oldChannelMembers) if nErr != nil { var nfErr *store.ErrNotFound var appErr *model.AppError @@ -1021,7 +1021,7 @@ func (a *App) importUserChannels(c request.CTX, user *model.User, team *model.Te newMembers := []*model.ChannelMember{} if len(newChannelMembers) > 0 { - newMembers, nErr = a.Srv().Store.Channel().SaveMultipleMembers(newChannelMembers) + newMembers, nErr = a.Srv().Store().Channel().SaveMultipleMembers(newChannelMembers) if nErr != nil { var cErr *store.ErrConflict var appErr *model.AppError @@ -1052,7 +1052,7 @@ func (a *App) importUserChannels(c request.CTX, user *model.User, team *model.Te for _, channel := range allChannels { if len(channelPreferencesByID[channel.Id]) > 0 { pref := channelPreferencesByID[channel.Id] - if err := a.Srv().Store.Preference().Save(pref); err != nil { + if err := a.Srv().Store().Preference().Save(pref); err != nil { return model.NewAppError("BulkImport", "app.import.import_user_channels.save_preferences.error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -1068,7 +1068,7 @@ func (a *App) importReaction(data *imports.ReactionImportData, post *model.Post) var user *model.User var nErr error - if user, nErr = a.Srv().Store.User().GetByUsername(*data.User); nErr != nil { + if user, nErr = a.Srv().Store().User().GetByUsername(*data.User); nErr != nil { return model.NewAppError("BulkImport", "app.import.import_post.user_not_found.error", map[string]any{"Username": data.User}, "", http.StatusBadRequest).Wrap(nErr) } @@ -1078,7 +1078,7 @@ func (a *App) importReaction(data *imports.ReactionImportData, post *model.Post) EmojiName: *data.EmojiName, CreateAt: *data.CreateAt, } - if _, nErr = a.Srv().Store.Reaction().Save(reaction); nErr != nil { + if _, nErr = a.Srv().Store().Reaction().Save(reaction); nErr != nil { var appErr *model.AppError switch { case errors.As(nErr, &appErr): @@ -1116,7 +1116,7 @@ func (a *App) importReplies(c request.CTX, data []imports.ReplyImportData, post user := users[*replyData.User] // Check if this post already exists. - replies, nErr := a.Srv().Store.Post().GetPostsCreatedAt(post.ChannelId, *replyData.CreateAt) + replies, nErr := a.Srv().Store().Post().GetPostsCreatedAt(post.ChannelId, *replyData.CreateAt) if nErr != nil { return model.NewAppError("importReplies", "app.post.get_posts_created_at.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1151,7 +1151,7 @@ func (a *App) importReplies(c request.CTX, data []imports.ReplyImportData, post fileIDs := a.uploadAttachments(c, replyData.Attachments, reply, teamID) for _, fileID := range reply.FileIds { if _, ok := fileIDs[fileID]; !ok { - a.Srv().Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store().FileInfo().PermanentDelete(fileID) } } reply.FileIds = make([]string, 0) @@ -1168,7 +1168,7 @@ func (a *App) importReplies(c request.CTX, data []imports.ReplyImportData, post } if len(postsForCreateList) > 0 { - if _, _, err := a.Srv().Store.Post().SaveMultiple(postsForCreateList); err != nil { + if _, _, err := a.Srv().Store().Post().SaveMultiple(postsForCreateList); err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput switch { @@ -1182,7 +1182,7 @@ func (a *App) importReplies(c request.CTX, data []imports.ReplyImportData, post } } - if _, _, nErr := a.Srv().Store.Post().OverwriteMultiple(postsForOverwriteList); nErr != nil { + if _, _, nErr := a.Srv().Store().Post().OverwriteMultiple(postsForOverwriteList); nErr != nil { return model.NewAppError("importReplies", "app.post.overwrite.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1274,7 +1274,7 @@ type postAndData struct { func (a *App) getUsersByUsernames(usernames []string) (map[string]*model.User, *model.AppError) { uniqueUsernames := utils.RemoveDuplicatesFromStringArray(usernames) - allUsers, err := a.Srv().Store.User().GetProfilesByUsernames(uniqueUsernames, nil) + allUsers, err := a.Srv().Store().User().GetProfilesByUsernames(uniqueUsernames, nil) if err != nil { return nil, model.NewAppError("BulkImport", "app.import.get_users_by_username.some_users_not_found.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1291,7 +1291,7 @@ func (a *App) getUsersByUsernames(usernames []string) (map[string]*model.User, * } func (a *App) getTeamsByNames(names []string) (map[string]*model.Team, *model.AppError) { - allTeams, err := a.Srv().Store.Team().GetByNames(names) + allTeams, err := a.Srv().Store().Team().GetByNames(names) if err != nil { return nil, model.NewAppError("BulkImport", "app.import.get_teams_by_names.some_teams_not_found.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1304,7 +1304,7 @@ func (a *App) getTeamsByNames(names []string) (map[string]*model.Team, *model.Ap } func (a *App) getChannelsByNames(names []string, teamID string) (map[string]*model.Channel, *model.AppError) { - allChannels, err := a.Srv().Store.Channel().GetByNames(teamID, names, true) + allChannels, err := a.Srv().Store().Channel().GetByNames(teamID, names, true) if err != nil { return nil, model.NewAppError("BulkImport", "app.import.get_teams_by_names.some_teams_not_found.error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1326,7 +1326,7 @@ func (a *App) getChannelsForPosts(teams map[string]*model.Team, data []*imports. } if channel, ok := teamChannels[teamName][*postData.Channel]; !ok || channel == nil { var err error - channel, err = a.Srv().Store.Channel().GetByName(teams[teamName].Id, *postData.Channel, true) + channel, err = a.Srv().Store().Channel().GetByName(teams[teamName].Id, *postData.Channel, true) if err != nil { return nil, model.NewAppError("BulkImport", "app.import.import_post.channel_not_found.error", map[string]any{"ChannelName": *postData.Channel}, "", http.StatusBadRequest).Wrap(err) } @@ -1398,7 +1398,7 @@ func (a *App) importMultiplePostLines(c request.CTX, lines []imports.LineImportW user := users[*line.Post.User] // Check if this post already exists. - posts, nErr := a.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *line.Post.CreateAt) + posts, nErr := a.Srv().Store().Post().GetPostsCreatedAt(channel.Id, *line.Post.CreateAt) if nErr != nil { return line.LineNumber, model.NewAppError("importMultiplePostLines", "app.post.get_posts_created_at.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1437,7 +1437,7 @@ func (a *App) importMultiplePostLines(c request.CTX, lines []imports.LineImportW fileIDs := a.uploadAttachments(c, line.Post.Attachments, post, team.Id) for _, fileID := range post.FileIds { if _, ok := fileIDs[fileID]; !ok { - a.Srv().Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store().FileInfo().PermanentDelete(fileID) } } post.FileIds = make([]string, 0) @@ -1456,7 +1456,7 @@ func (a *App) importMultiplePostLines(c request.CTX, lines []imports.LineImportW } if len(postsForCreateList) > 0 { - if _, idx, nErr := a.Srv().Store.Post().SaveMultiple(postsForCreateList); nErr != nil { + if _, idx, nErr := a.Srv().Store().Post().SaveMultiple(postsForCreateList); nErr != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput var retErr *model.AppError @@ -1479,7 +1479,7 @@ func (a *App) importMultiplePostLines(c request.CTX, lines []imports.LineImportW } } - if _, idx, err := a.Srv().Store.Post().OverwriteMultiple(postsForOverwriteList); err != nil { + if _, idx, err := a.Srv().Store().Post().OverwriteMultiple(postsForOverwriteList); err != nil { if idx != -1 && idx < len(postsForOverwriteList) { post := postsForOverwriteList[idx] if lineNumber, ok := postsForOverwriteMap[getPostStrID(post)]; ok { @@ -1506,7 +1506,7 @@ func (a *App) importMultiplePostLines(c request.CTX, lines []imports.LineImportW } if len(preferences) > 0 { - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { return postWithData.lineNumber, model.NewAppError("BulkImport", "app.import.import_post.save_preferences.error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -1560,7 +1560,7 @@ func (a *App) uploadAttachments(c request.CTX, attachments *[]imports.Attachment func (a *App) updateFileInfoWithPostId(post *model.Post) { for _, fileID := range post.FileIds { - if err := a.Srv().Store.FileInfo().AttachToPost(fileID, post.Id, post.UserId); err != nil { + if err := a.Srv().Store().FileInfo().AttachToPost(fileID, post.Id, post.UserId); err != nil { mlog.Error("Error attaching files to post.", mlog.String("post_id", post.Id), mlog.Any("post_file_ids", post.FileIds), mlog.Err(err)) } } @@ -1623,7 +1623,7 @@ func (a *App) importDirectChannel(c request.CTX, data *imports.DirectChannelImpo } } - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -1636,7 +1636,7 @@ func (a *App) importDirectChannel(c request.CTX, data *imports.DirectChannelImpo if data.Header != nil { channel.Header = *data.Header - if _, appErr := a.Srv().Store.Channel().Update(channel); appErr != nil { + if _, appErr := a.Srv().Store().Channel().Update(channel); appErr != nil { return model.NewAppError("BulkImport", "app.import.import_direct_channel.update_header_failed.error", nil, "", http.StatusBadRequest).Wrap(appErr) } } @@ -1709,7 +1709,7 @@ func (a *App) importMultipleDirectPostLines(c request.CTX, lines []imports.LineI user := users[*line.DirectPost.User] // Check if this post already exists. - posts, nErr := a.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *line.DirectPost.CreateAt) + posts, nErr := a.Srv().Store().Post().GetPostsCreatedAt(channel.Id, *line.DirectPost.CreateAt) if nErr != nil { return line.LineNumber, model.NewAppError("BulkImport", "app.post.get_posts_created_at.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1748,7 +1748,7 @@ func (a *App) importMultipleDirectPostLines(c request.CTX, lines []imports.LineI fileIDs := a.uploadAttachments(c, line.DirectPost.Attachments, post, "noteam") for _, fileID := range post.FileIds { if _, ok := fileIDs[fileID]; !ok { - a.Srv().Store.FileInfo().PermanentDelete(fileID) + a.Srv().Store().FileInfo().PermanentDelete(fileID) } } post.FileIds = make([]string, 0) @@ -1767,7 +1767,7 @@ func (a *App) importMultipleDirectPostLines(c request.CTX, lines []imports.LineI } if len(postsForCreateList) > 0 { - if _, idx, err := a.Srv().Store.Post().SaveMultiple(postsForCreateList); err != nil { + if _, idx, err := a.Srv().Store().Post().SaveMultiple(postsForCreateList); err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput var retErr *model.AppError @@ -1789,7 +1789,7 @@ func (a *App) importMultipleDirectPostLines(c request.CTX, lines []imports.LineI return 0, retErr } } - if _, idx, err := a.Srv().Store.Post().OverwriteMultiple(postsForOverwriteList); err != nil { + if _, idx, err := a.Srv().Store().Post().OverwriteMultiple(postsForOverwriteList); err != nil { if idx != -1 && idx < len(postsForOverwriteList) { post := postsForOverwriteList[idx] if lineNumber, ok := postsForOverwriteMap[getPostStrID(post)]; ok { @@ -1815,7 +1815,7 @@ func (a *App) importMultipleDirectPostLines(c request.CTX, lines []imports.LineI } if len(preferences) > 0 { - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { return postWithData.lineNumber, model.NewAppError("BulkImport", "app.import.import_post.save_preferences.error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -1858,7 +1858,7 @@ func (a *App) importEmoji(data *imports.EmojiImportData, dryRun bool) *model.App var emoji *model.Emoji - emoji, err := a.Srv().Store.Emoji().GetByName(context.Background(), *data.Name, true) + emoji, err := a.Srv().Store().Emoji().GetByName(context.Background(), *data.Name, true) if err != nil { var nfErr *store.ErrNotFound if !errors.As(err, &nfErr) { @@ -1892,7 +1892,7 @@ func (a *App) importEmoji(data *imports.EmojiImportData, dryRun bool) *model.App } if !alreadyExists { - if _, err := a.Srv().Store.Emoji().Save(emoji); err != nil { + if _, err := a.Srv().Store().Emoji().Save(emoji); err != nil { return model.NewAppError("importEmoji", "api.emoji.create.internal_error", nil, "", http.StatusBadRequest).Wrap(err) } } diff --git a/app/import_functions_test.go b/app/import_functions_test.go index 23dc11d8fb..bb2271eeb6 100644 --- a/app/import_functions_test.go +++ b/app/import_functions_test.go @@ -28,10 +28,10 @@ func TestImportImportScheme(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() // Try importing an invalid scheme in dryRun mode. @@ -68,7 +68,7 @@ func TestImportImportScheme(t *testing.T) { err := th.App.importScheme(&data, true) require.NotNil(t, err, "Should have failed to import.") - _, nErr := th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr := th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing a valid scheme in dryRun mode. @@ -77,7 +77,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, true) require.Nil(t, err, "Should have succeeded.") - _, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing an invalid scheme. @@ -86,7 +86,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - _, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing a valid scheme with all params set. @@ -95,7 +95,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded.") - scheme, nErr := th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr := th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -103,42 +103,42 @@ func TestImportImportScheme(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, nErr := th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) + role, nErr := th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -152,7 +152,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded: %v", err) - scheme, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -160,42 +160,42 @@ func TestImportImportScheme(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -208,7 +208,7 @@ func TestImportImportScheme(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - scheme, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -223,10 +223,10 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() // Try importing an invalid scheme in dryRun mode. @@ -255,7 +255,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err := th.App.importScheme(&data, true) require.NotNil(t, err, "Should have failed to import.") - _, nErr := th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr := th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing a valid scheme in dryRun mode. @@ -264,7 +264,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, true) require.Nil(t, err, "Should have succeeded.") - _, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing an invalid scheme. @@ -273,7 +273,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - _, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + _, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.Error(t, nErr, "Scheme should not have imported.") // Try importing a valid scheme with all params set. @@ -282,7 +282,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded.") - scheme, nErr := th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr := th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -290,42 +290,42 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, nErr := th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) + role, nErr := th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -339,7 +339,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.Nil(t, err, "Should have succeeded: %v", err) - scheme, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -347,42 +347,42 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { assert.Equal(t, *data.Description, scheme.Description) assert.Equal(t, *data.Scope, scheme.Scope) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultTeamGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultTeamGuestRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelAdminRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelUserRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName) assert.False(t, role.BuiltIn) assert.True(t, role.SchemeManaged) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), scheme.DefaultChannelGuestRole) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.DefaultChannelGuestRole.DisplayName, role.DisplayName) @@ -395,7 +395,7 @@ func TestImportImportSchemeWithoutGuestRoles(t *testing.T) { err = th.App.importScheme(&data, false) require.NotNil(t, err, "Should have failed to import.") - scheme, nErr = th.App.Srv().Store.Scheme().GetByName(*data.Name) + scheme, nErr = th.App.Srv().Store().Scheme().GetByName(*data.Name) require.NoError(t, nErr, "Failed to import scheme: %v", err) assert.Equal(t, *data.Name, scheme.Name) @@ -417,7 +417,7 @@ func TestImportImportRole(t *testing.T) { err := th.App.importRole(&data, true, false) require.NotNil(t, err, "Should have failed to import.") - _, nErr := th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + _, nErr := th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.Error(t, nErr, "Should have failed to import.") // Try importing the valid role in dryRun mode. @@ -426,7 +426,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, true, false) require.Nil(t, err, "Should have succeeded.") - _, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + _, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.Error(t, nErr, "Role should not have imported as we are in dry run mode.") // Try importing an invalid role. @@ -435,7 +435,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, false) require.NotNil(t, err, "Should have failed to import.") - _, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + _, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.Error(t, nErr, "Role should not have imported.") // Try importing a valid role with all params set. @@ -446,7 +446,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, false) require.Nil(t, err, "Should have succeeded.") - role, nErr := th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + role, nErr := th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.Name, role.Name) @@ -464,7 +464,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data, false, true) require.Nil(t, err, "Should have succeeded. %v", err) - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data.Name, role.Name) @@ -483,7 +483,7 @@ func TestImportImportRole(t *testing.T) { err = th.App.importRole(&data2, false, false) require.Nil(t, err, "Should have succeeded.") - role, nErr = th.App.Srv().Store.Role().GetByName(context.Background(), rid1) + role, nErr = th.App.Srv().Store().Role().GetByName(context.Background(), rid1) require.NoError(t, nErr, "Should have found the imported role.") assert.Equal(t, *data2.Name, role.Name) @@ -499,17 +499,17 @@ func TestImportImportTeam(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() scheme1 := th.SetupTeamScheme() scheme2 := th.SetupTeamScheme() // Check how many teams are in the database. - teamsCount, err := th.App.Srv().Store.Team().AnalyticsTeamCount(nil) + teamsCount, err := th.App.Srv().Store().Team().AnalyticsTeamCount(nil) require.NoError(t, err, "Failed to get team count.") data := imports.TeamImportData{ @@ -589,10 +589,10 @@ func TestImportImportChannel(t *testing.T) { defer th.TearDown() // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() scheme1 := th.SetupChannelScheme() @@ -609,7 +609,7 @@ func TestImportImportChannel(t *testing.T) { require.Nil(t, err, "Failed to get team from database.") // Check how many channels are in the database. - channelCount, nErr := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) + channelCount, nErr := th.App.Srv().Store().Channel().AnalyticsTypeCount("", model.ChannelTypeOpen) require.NoError(t, nErr, "Failed to get team count.") // Do an invalid channel in dry-run mode. @@ -712,7 +712,7 @@ func TestImportImportUser(t *testing.T) { defer th.TearDown() // Check how many users are in the database. - userCount, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -726,7 +726,7 @@ func TestImportImportUser(t *testing.T) { require.Error(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. - userCount2, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount2, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -742,7 +742,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Should have succeeded to import valid user.") // Check that no more users are in the DB. - userCount3, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount3, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -757,7 +757,7 @@ func TestImportImportUser(t *testing.T) { require.Error(t, err, "Should have failed to import invalid user.") // Check that no more users are in the DB. - userCount4, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount4, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -780,7 +780,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Should have succeeded to import valid user.") // Check that one more user is in the DB. - userCount5, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount5, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -823,7 +823,7 @@ func TestImportImportUser(t *testing.T) { require.Nil(t, appErr, "Should have succeeded to update valid user %v", err) // Check user count the same. - userCount6, err := th.App.Srv().Store.User().Count(model.UserCountOptions{ + userCount6, err := th.App.Srv().Store().User().Count(model.UserCountOptions{ IncludeDeleted: true, IncludeBotAccounts: false, }) @@ -1347,10 +1347,10 @@ func TestImportImportUser(t *testing.T) { // to the appropriate scheme-managed-role booleans. // Mark the phase 2 permissions migration as completed. - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() teamSchemeData := &imports.SchemeImportData{ @@ -1387,7 +1387,7 @@ func TestImportImportUser(t *testing.T) { appErr = th.App.importScheme(teamSchemeData, false) assert.Nil(t, appErr) - teamScheme, nErr := th.App.Srv().Store.Scheme().GetByName(*teamSchemeData.Name) + teamScheme, nErr := th.App.Srv().Store().Scheme().GetByName(*teamSchemeData.Name) require.NoError(t, nErr, "Failed to import scheme") teamData := &imports.TeamImportData{ @@ -1724,14 +1724,14 @@ func TestImportUserTeams(t *testing.T) { } else { require.Nil(t, err) } - teamMembers, nErr := th.App.Srv().Store.Team().GetTeamsForUser(context.Background(), user.Id, "", true) + teamMembers, nErr := th.App.Srv().Store().Team().GetTeamsForUser(context.Background(), user.Id, "", true) require.NoError(t, nErr) require.Len(t, teamMembers, tc.expectedUserTeams) if tc.expectedUserTeams == 1 { require.Equal(t, tc.expectedExplicitRoles, teamMembers[0].ExplicitRoles, "Not matching expected explicit roles") require.Equal(t, tc.expectedRoles, teamMembers[0].Roles, "not matching expected roles") if tc.expectedTheme != "" { - pref, prefErr := th.App.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryTheme, teamMembers[0].TeamId) + pref, prefErr := th.App.Srv().Store().Preference().Get(user.Id, model.PreferenceCategoryTheme, teamMembers[0].TeamId) require.NoError(t, prefErr) require.Equal(t, tc.expectedTheme, pref.Value) } @@ -1739,7 +1739,7 @@ func TestImportUserTeams(t *testing.T) { totalMembers := 0 for _, teamMember := range teamMembers { - channelMembers, err := th.App.Srv().Store.Channel().GetMembersForUser(teamMember.TeamId, user.Id) + channelMembers, err := th.App.Srv().Store().Channel().GetMembersForUser(teamMember.TeamId, user.Id) require.NoError(t, err) totalMembers += len(channelMembers) } @@ -1878,7 +1878,7 @@ func TestImportUserChannels(t *testing.T) { } else { require.Nil(t, appErr) } - channelMembers, err := th.App.Srv().Store.Channel().GetMembersForUser(th.BasicTeam.Id, user.Id) + channelMembers, err := th.App.Srv().Store().Channel().GetMembersForUser(th.BasicTeam.Id, user.Id) require.NoError(t, err) require.Len(t, channelMembers, tc.expectedUserChannels) if tc.expectedUserChannels == 1 { @@ -1971,7 +1971,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { require.Nil(t, err, "Failed to get user from database.") // Count the number of posts in the testing team. - initialPostCount, nErr := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team.Id}) + initialPostCount, nErr := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team.Id}) require.NoError(t, nErr) // Try adding an invalid post in dry run mode. @@ -2105,7 +2105,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, time) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2133,7 +2133,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, time) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2198,7 +2198,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) - posts, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime) + posts, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, hashtagTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2243,7 +2243,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 5, team.Id) // Check the post values. - posts, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, flagsTime) + posts, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, flagsTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2282,7 +2282,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 6, team.Id) // Check the post values. - posts, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, reactionPostTime) + posts, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, reactionPostTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2291,7 +2291,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { postBool = post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id || !post.HasReactions require.False(t, postBool, "Post properties not as expected") - reactions, nErr := th.App.Srv().Store.Reaction().GetForPost(post.Id, false) + reactions, nErr := th.App.Srv().Store().Reaction().GetForPost(post.Id, false) require.NoError(t, nErr, "Can't get reaction") require.Len(t, reactions, 1, "Invalid number of reactions") @@ -2323,7 +2323,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 8, team.Id) // Check the post values. - posts, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyPostTime) + posts, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, replyPostTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2333,7 +2333,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { require.False(t, postBool, "Post properties not as expected") // Check the reply values. - replies, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyTime) + replies, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, replyTime) require.NoError(t, nErr) require.Len(t, replies, 1, "Unexpected number of posts found.") @@ -2449,7 +2449,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 13, team.Id) // Check the reply values. - replies, nErr = th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, editedReplyTime) + replies, nErr = th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, editedReplyTime) assert.NoError(t, nErr, "Expected success.") reply = replies[0] importReply := (*data.Post.Replies)[0] @@ -2477,7 +2477,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { require.Nil(t, err, "Failed to get channel from database.") // Count the number of posts in the team2. - initialPostCountForTeam2, nErr := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team2.Id}) + initialPostCountForTeam2, nErr := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team2.Id}) require.NoError(t, nErr) // Try adding two valid posts in apply mode. @@ -2527,7 +2527,7 @@ func TestImportimportMultiplePostLines(t *testing.T) { require.Nil(t, err) require.Equal(t, 0, errLine) - resultPosts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *data.Post.CreateAt) + resultPosts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, *data.Post.CreateAt) require.NoError(t, nErr, "Expected success.") // Should be one post only created at this time. require.Equal(t, 1, len(resultPosts)) @@ -2583,7 +2583,7 @@ func TestImportImportPost(t *testing.T) { require.Nil(t, appErr, "Failed to get user from database.") // Count the number of posts in the testing team. - initialPostCount, nErr := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team.Id}) + initialPostCount, nErr := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: team.Id}) require.NoError(t, nErr) time := model.GetMillis() @@ -2724,7 +2724,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, time) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2753,7 +2753,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, time) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, time) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2820,7 +2820,7 @@ func TestImportImportPost(t *testing.T) { assert.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, hashtagTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2858,7 +2858,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 5, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, flagsTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, flagsTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2898,7 +2898,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 6, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, reactionPostTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, reactionPostTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2907,7 +2907,7 @@ func TestImportImportPost(t *testing.T) { postBool := post.Message != *data.Post.Message || post.CreateAt != *data.Post.CreateAt || post.UserId != user.Id || !post.HasReactions require.False(t, postBool, "Post properties not as expected") - reactions, nErr := th.App.Srv().Store.Reaction().GetForPost(post.Id, false) + reactions, nErr := th.App.Srv().Store().Reaction().GetForPost(post.Id, false) require.NoError(t, nErr, "Can't get reaction") require.Len(t, reactions, 1, "Invalid number of reactions") @@ -2938,7 +2938,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 8, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyPostTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, replyPostTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -2948,7 +2948,7 @@ func TestImportImportPost(t *testing.T) { require.False(t, postBool, "Post properties not as expected") // Check the reply values. - replies, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, replyTime) + replies, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, replyTime) require.NoError(t, nErr) require.Len(t, replies, 1, "Unexpected number of posts found.") @@ -3057,7 +3057,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 12, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, posttypeTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, posttypeTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -3089,7 +3089,7 @@ func TestImportImportPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 13, team.Id) // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, editatCreateTime) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, editatCreateTime) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -3124,7 +3124,7 @@ func TestImportImportPost(t *testing.T) { require.Nil(t, err, "Expected success.") require.Equal(t, 0, errLine) - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, now) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, now) require.NoError(t, nErr) require.Len(t, posts, 2, "Unexpected number of posts found.") require.NoError(t, th.TestLogger.Flush()) @@ -3146,10 +3146,10 @@ func TestImportImportDirectChannel(t *testing.T) { defer th.TearDown() // Check how many channels are in the database. - directChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeDirect) + directChannelCount, err := th.App.Srv().Store().Channel().AnalyticsTypeCount("", model.ChannelTypeDirect) require.NoError(t, err, "Failed to get direct channel count.") - groupChannelCount, err := th.App.Srv().Store.Channel().AnalyticsTypeCount("", model.ChannelTypeGroup) + groupChannelCount, err := th.App.Srv().Store().Channel().AnalyticsTypeCount("", model.ChannelTypeGroup) require.NoError(t, err, "Failed to get group channel count.") // Do an invalid channel in dry-run mode. @@ -3331,7 +3331,7 @@ func TestImportImportDirectPost(t *testing.T) { directChannel = channel // Get the number of posts in the system. - result, err := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + result, err := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) require.NoError(t, err) initialPostCount := result initialDate := model.GetMillis() @@ -3422,7 +3422,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3453,7 +3453,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3525,7 +3525,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3562,7 +3562,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 5, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3592,7 +3592,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 6, "") - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3624,7 +3624,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 7, "") - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3658,7 +3658,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 8, "") - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(directChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3692,7 +3692,7 @@ func TestImportImportDirectPost(t *testing.T) { groupChannel = channel // Get the number of posts in the system. - result, nErr := th.App.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + result, nErr := th.App.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) require.NoError(t, nErr) initialPostCount = result @@ -3784,7 +3784,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3816,7 +3816,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3891,7 +3891,7 @@ func TestImportImportDirectPost(t *testing.T) { require.Equal(t, 0, errLine) AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3930,7 +3930,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 5, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1) @@ -3969,7 +3969,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 6, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -3978,7 +3978,7 @@ func TestImportImportDirectPost(t *testing.T) { postBool := post.Message != *data.DirectPost.Message || post.CreateAt != *data.DirectPost.CreateAt || post.UserId != th.BasicUser.Id || !post.HasReactions require.False(t, postBool, "Post properties not as expected") - reactions, nErr := th.App.Srv().Store.Reaction().GetForPost(post.Id, false) + reactions, nErr := th.App.Srv().Store().Reaction().GetForPost(post.Id, false) require.NoError(t, nErr, "Can't get reaction") require.Len(t, reactions, 1, "Invalid number of reactions") @@ -4014,7 +4014,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 8, "") // Check the post values. - posts, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) + posts, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(groupChannel.Id, *data.DirectPost.CreateAt) require.NoError(t, nErr) require.Len(t, posts, 1, "Unexpected number of posts found.") @@ -4024,7 +4024,7 @@ func TestImportImportDirectPost(t *testing.T) { require.False(t, postBool, "Post properties not as expected") // Check the reply values. - replies, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *replyTime) + replies, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, *replyTime) require.NoError(t, nErr) require.Len(t, replies, 1, "Unexpected number of posts found.") @@ -4129,7 +4129,7 @@ func TestImportImportDirectPost(t *testing.T) { AssertAllPostsCount(t, th.App, initialPostCount, 12, "") // Check the reply values. - replies, nErr := th.App.Srv().Store.Post().GetPostsCreatedAt(channel.Id, *replyTime) + replies, nErr := th.App.Srv().Store().Post().GetPostsCreatedAt(channel.Id, *replyTime) require.NoError(t, nErr) require.Len(t, replies, 1, "Unexpected number of posts found.") @@ -4154,7 +4154,7 @@ func TestImportImportEmoji(t *testing.T) { appErr := th.App.importEmoji(&data, true) assert.NotNil(t, appErr, "Invalid emoji should have failed dry run") - emoji, nErr := th.App.Srv().Store.Emoji().GetByName(context.Background(), *data.Name, true) + emoji, nErr := th.App.Srv().Store().Emoji().GetByName(context.Background(), *data.Name, true) assert.Nil(t, emoji, "Emoji should not have been imported") assert.Error(t, nErr) @@ -4174,7 +4174,7 @@ func TestImportImportEmoji(t *testing.T) { appErr = th.App.importEmoji(&data, false) assert.Nil(t, appErr, "Valid emoji should have succeeded apply mode") - emoji, nErr = th.App.Srv().Store.Emoji().GetByName(context.Background(), *data.Name, true) + emoji, nErr = th.App.Srv().Store().Emoji().GetByName(context.Background(), *data.Name, true) assert.NotNil(t, emoji, "Emoji should have been imported") assert.NoError(t, nErr, "Emoji should have been imported without any error") diff --git a/app/import_test.go b/app/import_test.go index 6babb409f3..0ddb6834ec 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -39,7 +39,7 @@ func ptrBool(b bool) *bool { } func checkPreference(t *testing.T, a *App, userID string, category string, name string, value string) { - preferences, err := a.Srv().Store.Preference().GetCategory(userID, category) + preferences, err := a.Srv().Store().Preference().GetCategory(userID, category) require.NoErrorf(t, err, "Failed to get preferences for user %v with category %v", userID, category) found := false for _, preference := range preferences { @@ -68,13 +68,13 @@ func checkNoError(t *testing.T, err *model.AppError) { } func AssertAllPostsCount(t *testing.T, a *App, initialCount int64, change int64, teamName string) { - result, err := a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamName}) + result, err := a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{TeamId: teamName}) require.NoError(t, err) require.Equal(t, initialCount+change, result, "Did not find the expected number of posts.") } func AssertChannelCount(t *testing.T, a *App, channelType model.ChannelType, expectedCount int64) { - count, err := a.Srv().Store.Channel().AnalyticsTypeCount("", channelType) + count, err := a.Srv().Store().Channel().AnalyticsTypeCount("", channelType) require.Equalf(t, expectedCount, count, "Channel count of type: %v. Expected: %v, Got: %v", channelType, expectedCount, count) require.NoError(t, err, "Failed to get channel count.") } @@ -266,7 +266,7 @@ func TestImportProcessImportDataFileVersionLine(t *testing.T) { } func GetAttachments(userID string, th *TestHelper, t *testing.T) []*model.FileInfo { - fileInfos, err := th.App.Srv().Store.FileInfo().GetForUser(userID) + fileInfos, err := th.App.Srv().Store().FileInfo().GetForUser(userID) require.NoError(t, err) return fileInfos } @@ -275,7 +275,7 @@ func AssertFileIdsInPost(files []*model.FileInfo, th *TestHelper, t *testing.T) postID := files[0].PostId require.NotNil(t, postID) - posts, err := th.App.Srv().Store.Post().GetPostsByIds([]string{postID}) + posts, err := th.App.Srv().Store().Post().GetPostsByIds([]string{postID}) require.NoError(t, err) require.Len(t, posts, 1) diff --git a/app/integration_action.go b/app/integration_action.go index e85ad88f5e..4ae7e97e07 100644 --- a/app/integration_action.go +++ b/app/integration_action.go @@ -73,21 +73,21 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI // Start all queries here for parallel execution pchan := make(chan store.StoreResult, 1) go func() { - post, err := a.Srv().Store.Post().GetSingle(postID, false) + post, err := a.Srv().Store().Post().GetSingle(postID, false) pchan <- store.StoreResult{Data: post, NErr: err} close(pchan) }() cchan := make(chan store.StoreResult, 1) go func() { - channel, err := a.Srv().Store.Channel().GetForPost(postID) + channel, err := a.Srv().Store().Channel().GetForPost(postID) cchan <- store.StoreResult{Data: channel, NErr: err} close(cchan) }() userChan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), upstreamRequest.UserId) + user, err := a.Srv().Store().User().Get(context.Background(), upstreamRequest.UserId) userChan <- store.StoreResult{Data: user, NErr: err} close(userChan) }() @@ -111,7 +111,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI return "", model.NewAppError("DoPostActionWithCookie", "api.post.do_action.action_integration.app_error", nil, "postId doesn't match", http.StatusBadRequest) } - channel, err := a.Srv().Store.Channel().Get(cookie.ChannelId, true) + channel, err := a.Srv().Store().Channel().Get(cookie.ChannelId, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -186,7 +186,7 @@ func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userI return } - team, err := a.Srv().Store.Team().Get(upstreamRequest.TeamId) + team, err := a.Srv().Store().Team().Get(upstreamRequest.TeamId) teamChan <- store.StoreResult{Data: team, NErr: err} }() @@ -553,7 +553,7 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s mailBody += T("api.server.warn_metric.bot_response.mailto_email_header", map[string]any{"Email": user.Email}) mailBody += "\r\n" - registeredUsersCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) + registeredUsersCount, err := a.Srv().Store().User().Count(model.UserCountOptions{}) if err != nil { mlog.Warn("Error retrieving the number of registered users", mlog.Err(err)) } else { diff --git a/app/integration_action_test.go b/app/integration_action_test.go index 8fa6debe5d..0651f52ad4 100644 --- a/app/integration_action_test.go +++ b/app/integration_action_test.go @@ -475,7 +475,7 @@ func TestPostActionProps(t *testing.T) { require.Nil(t, err) assert.True(t, len(clientTriggerId) == 26) - newPost, nErr := th.App.Srv().Store.Post().GetSingle(post.Id, false) + newPost, nErr := th.App.Srv().Store().Post().GetSingle(post.Id, false) require.NoError(t, nErr) assert.True(t, newPost.IsPinned) diff --git a/app/job.go b/app/job.go index 0eaeb82d7a..f227178b67 100644 --- a/app/job.go +++ b/app/job.go @@ -12,7 +12,7 @@ import ( ) func (a *App) GetJob(id string) (*model.Job, *model.AppError) { - job, err := a.Srv().Store.Job().Get(id) + job, err := a.Srv().Store().Job().Get(id) if err != nil { var nfErr *store.ErrNotFound switch { @@ -31,7 +31,7 @@ func (a *App) GetJobsPage(page int, perPage int) ([]*model.Job, *model.AppError) } func (a *App) GetJobs(offset int, limit int) ([]*model.Job, *model.AppError) { - jobs, err := a.Srv().Store.Job().GetAllPage(offset, limit) + jobs, err := a.Srv().Store().Job().GetAllPage(offset, limit) if err != nil { return nil, model.NewAppError("GetJobs", "app.job.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -44,7 +44,7 @@ func (a *App) GetJobsByTypePage(jobType string, page int, perPage int) ([]*model } func (a *App) GetJobsByType(jobType string, offset int, limit int) ([]*model.Job, *model.AppError) { - jobs, err := a.Srv().Store.Job().GetAllByTypePage(jobType, offset, limit) + jobs, err := a.Srv().Store().Job().GetAllByTypePage(jobType, offset, limit) if err != nil { return nil, model.NewAppError("GetJobsByType", "app.job.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -57,7 +57,7 @@ func (a *App) GetJobsByTypesPage(jobType []string, page int, perPage int) ([]*mo } func (a *App) GetJobsByTypes(jobTypes []string, offset int, limit int) ([]*model.Job, *model.AppError) { - jobs, err := a.Srv().Store.Job().GetAllByTypesPage(jobTypes, offset, limit) + jobs, err := a.Srv().Store().Job().GetAllByTypesPage(jobTypes, offset, limit) if err != nil { return nil, model.NewAppError("GetJobsByType", "app.job.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/job_test.go b/app/job_test.go index 55ddb6b975..12438e37ca 100644 --- a/app/job_test.go +++ b/app/job_test.go @@ -22,10 +22,10 @@ func TestGetJob(t *testing.T) { Id: model.NewId(), Status: model.NewId(), } - _, err := th.App.Srv().Store.Job().Save(status) + _, err := th.App.Srv().Store().Job().Save(status) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(status.Id) + defer th.App.Srv().Store().Job().Delete(status.Id) received, appErr := th.App.GetJob(status.Id) require.Nil(t, appErr) @@ -238,9 +238,9 @@ func TestGetJobByType(t *testing.T) { } for _, status := range statuses { - _, err := th.App.Srv().Store.Job().Save(status) + _, err := th.App.Srv().Store().Job().Save(status) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(status.Id) + defer th.App.Srv().Store().Job().Delete(status.Id) } received, err := th.App.GetJobsByType(jobType, 0, 2) @@ -282,9 +282,9 @@ func TestGetJobsByTypes(t *testing.T) { } for _, status := range statuses { - _, err := th.App.Srv().Store.Job().Save(status) + _, err := th.App.Srv().Store().Job().Save(status) require.NoError(t, err) - defer th.App.Srv().Store.Job().Delete(status.Id) + defer th.App.Srv().Store().Job().Delete(status.Id) } jobTypes := []string{jobType, jobType1, jobType2} diff --git a/app/layer_generators/opentracing_layer.go.tmpl b/app/layer_generators/opentracing_layer.go.tmpl index 3b690bd96f..7b71bfee5f 100644 --- a/app/layer_generators/opentracing_layer.go.tmpl +++ b/app/layer_generators/opentracing_layer.go.tmpl @@ -43,9 +43,9 @@ func (a *{{$.Name}}) {{$index}}({{$element.Params | joinParamsWithType}}) {{$ele span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.{{$index}}") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() {{range $paramIdx, $param := $element.Params}} diff --git a/app/license.go b/app/license.go index f812ae9527..9afff64349 100644 --- a/app/license.go +++ b/app/license.go @@ -4,22 +4,15 @@ package app import ( - "bytes" - "encoding/json" - "fmt" "net/http" - "os" "time" "github.com/dgrijalva/jwt-go" "github.com/pkg/errors" - "github.com/mattermost/mattermost-server/v6/jobs" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/product" - "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" - "github.com/mattermost/mattermost-server/v6/utils" ) const ( @@ -82,7 +75,7 @@ func (w *licenseWrapper) RequestTrialLicense(requesterID string, users int, term ReceiveEmailsAccepted: receiveEmailsAccepted, } - return w.srv.RequestTrialLicense(trialLicenseRequest) + return w.srv.platform.RequestTrialLicense(trialLicenseRequest) } // JWTClaims custom JWT claims with the needed information for the @@ -94,336 +87,55 @@ type JWTClaims struct { } func (s *Server) License() *model.License { - license, _ := s.licenseValue.Load().(*model.License) - return license + return s.platform.License() } func (s *Server) LoadLicense() { - // ENV var overrides all other sources of license. - licenseStr := os.Getenv(LicenseEnv) - if licenseStr != "" { - license, err := utils.LicenseValidator.LicenseFromBytes([]byte(licenseStr)) - if err != nil { - mlog.Error("Failed to read license set in environment.", mlog.Err(err)) - return - } - - // skip the restrictions if license is a sanctioned trial - if !license.IsSanctionedTrial() && license.IsTrialLicense() { - canStartTrialLicense, err := s.LicenseManager.CanStartTrial() - if err != nil { - mlog.Error("Failed to validate trial eligibility.", mlog.Err(err)) - return - } - - if !canStartTrialLicense { - mlog.Info("Cannot start trial multiple times.") - return - } - } - - if s.ValidateAndSetLicenseBytes([]byte(licenseStr)) { - mlog.Info("License key from ENV is valid, unlocking enterprise features.") - } - return - } - - licenseId := "" - props, nErr := s.Store.System().Get() - if nErr == nil { - licenseId = props[model.SystemActiveLicenseId] - } - - if !model.IsValidId(licenseId) { - // Lets attempt to load the file from disk since it was missing from the DB - license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*s.platform.Config().ServiceSettings.LicenseFileLocation) - - if license != nil { - if _, err := s.SaveLicense(licenseBytes); err != nil { - mlog.Error("Failed to save license key loaded from disk.", mlog.Err(err)) - } else { - licenseId = license.Id - } - } - } - - record, nErr := s.Store.License().Get(licenseId) - if nErr != nil { - mlog.Error("License key from https://mattermost.com required to unlock enterprise features.", mlog.Err(nErr)) - s.SetLicense(nil) - return - } - - s.ValidateAndSetLicenseBytes([]byte(record.Bytes)) - mlog.Info("License key valid unlocking enterprise features.") + s.platform.LoadLicense() } func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { - success, licenseStr := utils.LicenseValidator.ValidateLicense(licenseBytes) - if !success { - return nil, model.NewAppError("addLicense", model.InvalidLicenseError, nil, "", http.StatusBadRequest) - } - - var license model.License - if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil { - return nil, model.NewAppError("addLicense", "api.unmarshal_error", nil, "", http.StatusInternalServerError).Wrap(jsonErr) - } - - uniqueUserCount, err := s.Store.User().Count(model.UserCountOptions{}) - if err != nil { - return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, "", http.StatusBadRequest).Wrap(err) - } - - if uniqueUserCount > int64(*license.Features.Users) { - return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]any{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest) - } - - if license.IsExpired() { - return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) - } - - if *s.platform.Config().JobSettings.RunJobs && s.Jobs != nil { - if err := s.Jobs.StopWorkers(); err != nil && !errors.Is(err, jobs.ErrWorkersNotRunning) { - mlog.Warn("Stopping job server workers failed", mlog.Err(err)) - } - } - - if *s.platform.Config().JobSettings.RunScheduler && s.Jobs != nil { - if err := s.Jobs.StopSchedulers(); err != nil && !errors.Is(err, jobs.ErrSchedulersNotRunning) { - mlog.Error("Stopping job server schedulers failed", mlog.Err(err)) - } - } - - defer func() { - // restart job server workers - this handles the edge case where a license file is uploaded, but the job server - // doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from - // functioning as expected - if *s.platform.Config().JobSettings.RunJobs && s.Jobs != nil { - if err := s.Jobs.StartWorkers(); err != nil { - mlog.Error("Starting job server workers failed", mlog.Err(err)) - } - } - if *s.platform.Config().JobSettings.RunScheduler && s.Jobs != nil { - if err := s.Jobs.StartSchedulers(); err != nil && !errors.Is(err, jobs.ErrSchedulersRunning) { - mlog.Error("Starting job server schedulers failed", mlog.Err(err)) - } - } - }() - - if ok := s.SetLicense(&license); !ok { - return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) - } - - record := &model.LicenseRecord{} - record.Id = license.Id - record.Bytes = string(licenseBytes) - - _, nErr := s.Store.License().Save(record) - if nErr != nil { - s.RemoveLicense() - var appErr *model.AppError - switch { - case errors.As(nErr, &appErr): - return nil, appErr - default: - return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) - } - } - - sysVar := &model.System{} - sysVar.Name = model.SystemActiveLicenseId - sysVar.Value = license.Id - if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { - s.RemoveLicense() - return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) - } - - s.platform.ReloadConfig() - s.InvalidateAllCaches() - - return &license, nil + return s.platform.SaveLicense(licenseBytes) } func (s *Server) SetLicense(license *model.License) bool { - oldLicense := s.licenseValue.Load() - - defer func() { - for _, listener := range s.licenseListeners { - if oldLicense == nil { - listener(nil, license) - } else { - listener(oldLicense.(*model.License), license) - } - } - }() - - if license != nil { - license.Features.SetDefaults() - - s.licenseValue.Store(license) - if s.platform != nil { - s.platform.SetLicense(license) - } - - s.clientLicenseValue.Store(utils.GetClientLicense(license)) - return true - } - - s.licenseValue.Store((*model.License)(nil)) - s.clientLicenseValue.Store(map[string]string(nil)) - if s.platform != nil { - s.platform.SetLicense((*model.License)(nil)) - } - - return false + return s.platform.SetLicense(license) } func (s *Server) ValidateAndSetLicenseBytes(b []byte) bool { - if success, licenseStr := utils.LicenseValidator.ValidateLicense(b); success { - var license model.License - if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil { - mlog.Warn("Failed to decode license from JSON", mlog.Err(jsonErr)) - return false - } - s.SetLicense(&license) - return true - } - - mlog.Warn("No valid enterprise license found") - return false + return s.platform.ValidateAndSetLicenseBytes(b) } func (s *Server) SetClientLicense(m map[string]string) { - s.clientLicenseValue.Store(m) + s.platform.SetClientLicense(m) } func (s *Server) ClientLicense() map[string]string { - if clientLicense, _ := s.clientLicenseValue.Load().(map[string]string); clientLicense != nil { - return clientLicense - } - return map[string]string{"IsLicensed": "false"} + return s.platform.ClientLicense() } func (s *Server) RemoveLicense() *model.AppError { - if license, _ := s.licenseValue.Load().(*model.License); license == nil { - return nil - } - - mlog.Info("Remove license.", mlog.String("id", model.SystemActiveLicenseId)) - - sysVar := &model.System{} - sysVar.Name = model.SystemActiveLicenseId - sysVar.Value = "" - - if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { - return model.NewAppError("RemoveLicense", "app.system.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - s.SetLicense(nil) - s.platform.ReloadConfig() - s.InvalidateAllCaches() - - return nil + return s.platform.RemoveLicense() } func (s *Server) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string { - id := model.NewId() - s.licenseListeners[id] = listener - return id + return s.platform.AddLicenseListener(listener) } func (s *Server) RemoveLicenseListener(id string) { - delete(s.licenseListeners, id) + s.platform.RemoveLicenseListener(id) } func (s *Server) GetSanitizedClientLicense() map[string]string { - return utils.GetSanitizedClientLicense(s.ClientLicense()) -} - -// RequestTrialLicense request a trial license from the mattermost official license server -func (s *Server) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { - trialRequestJSON, err := json.Marshal(trialRequest) - if err != nil { - return model.NewAppError("RequestTrialLicense", "api.unmarshal_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - resp, err := http.Post(RequestTrialURL, "application/json", bytes.NewBuffer(trialRequestJSON)) - if err != nil { - return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, "", http.StatusBadRequest).Wrap(err) - } - defer resp.Body.Close() - - // CloudFlare sitting in front of the Customer Portal will block this request with a 451 response code in the event that the request originates from a country sanctioned by the U.S. Government. - if resp.StatusCode == http.StatusUnavailableForLegalReasons { - return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.embargoed", nil, "Request for trial license came from an embargoed country", http.StatusUnavailableForLegalReasons) - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, - fmt.Sprintf("Unexpected HTTP status code %q returned by server", resp.Status), http.StatusInternalServerError) - } - - var licenseResponse map[string]string - err = json.NewDecoder(resp.Body).Decode(&licenseResponse) - if err != nil { - s.Log().Warn("Error decoding license response", mlog.Err(err)) - } - - if _, ok := licenseResponse["license"]; !ok { - return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, licenseResponse["message"], http.StatusBadRequest) - } - - if _, err := s.SaveLicense([]byte(licenseResponse["license"])); err != nil { - return err - } - - s.platform.ReloadConfig() - s.InvalidateAllCaches() - - return nil + return s.platform.GetSanitizedClientLicense() } // GenerateRenewalToken returns a renewal token that expires after duration expiration func (s *Server) GenerateRenewalToken(expiration time.Duration) (string, *model.AppError) { - license := s.License() - if license == nil { - return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.no_license", nil, "", http.StatusBadRequest) - } - - if *license.Features.Cloud { - return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.bad_license", nil, "", http.StatusBadRequest) - } - - activeUsers, err := s.Store.User().Count(model.UserCountOptions{}) - if err != nil { - return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", - nil, "", http.StatusInternalServerError).Wrap(err) - } - - expirationTime := time.Now().UTC().Add(expiration) - claims := &JWTClaims{ - LicenseID: license.Id, - ActiveUsers: activeUsers, - StandardClaims: jwt.StandardClaims{ - ExpiresAt: expirationTime.Unix(), - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - tokenString, err := token.SignedString([]byte(license.Customer.Email)) - if err != nil { - return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - return tokenString, nil + return s.platform.GenerateRenewalToken(expiration) } // GenerateLicenseRenewalLink returns a link that points to the CWS where clients can renew license func (s *Server) GenerateLicenseRenewalLink() (string, string, *model.AppError) { - renewalToken, err := s.GenerateRenewalToken(JWTDefaultTokenExpiration) - if err != nil { - return "", "", err - } - renewalLink := LicenseRenewalURL + "?token=" + renewalToken - return renewalLink, renewalToken, nil + return s.platform.GenerateLicenseRenewalLink() } diff --git a/app/login.go b/app/login.go index 620c843f9c..77abb8d0e3 100644 --- a/app/login.go +++ b/app/login.go @@ -70,7 +70,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password if err = checkUserNotBot(user); err != nil { return nil, err } - token, err := a.Srv().Store.Token().GetByToken(cwsToken) + token, err := a.Srv().Store().Token().GetByToken(cwsToken) if nfErr := new(store.ErrNotFound); err != nil && !errors.As(err, &nfErr) { mlog.Debug("Error retrieving the cws token from the store", mlog.Err(err)) return nil, model.NewAppError("AuthenticateUserForLogin", @@ -88,7 +88,7 @@ func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password CreateAt: model.GetMillis(), Type: TokenTypeCWSAccess, } - err := a.Srv().Store.Token().Save(token) + err := a.Srv().Store().Token().Save(token) if err != nil { mlog.Debug("Error storing the cws token in the store", mlog.Err(err)) return nil, model.NewAppError("AuthenticateUserForLogin", @@ -139,7 +139,7 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError) } // Try to get the user by username/email - if user, err := a.Srv().Store.User().GetForLogin(loginId, enableUsername, enableEmail); err == nil { + if user, err := a.Srv().Store().User().GetForLogin(loginId, enableUsername, enableEmail); err == nil { return user, nil } @@ -178,7 +178,7 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request session.GenerateCSRF() if deviceID != "" { - a.ch.srv.userService.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthMobileInHours) + a.ch.srv.platform.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthMobileInHours) // A special case where we logout of all other sessions with the same Id if err := a.RevokeSessionsForDeviceId(user.Id, deviceID, ""); err != nil { @@ -186,11 +186,11 @@ func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request return err } } else if isMobile { - a.ch.srv.userService.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthMobileInHours) + a.ch.srv.platform.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthMobileInHours) } else if isOAuthUser || isSaml { - a.ch.srv.userService.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthSSOInHours) + a.ch.srv.platform.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthSSOInHours) } else { - a.ch.srv.userService.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthWebInHours) + a.ch.srv.platform.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthWebInHours) } ua := uasurfer.Parse(r.UserAgent()) diff --git a/app/login_test.go b/app/login_test.go index 784ad43b5d..280b0df937 100644 --- a/app/login_test.go +++ b/app/login_test.go @@ -55,7 +55,7 @@ func TestCWSLogin(t *testing.T) { require.Nil(t, err) require.NotNil(t, user) require.Equal(t, th.BasicUser.Username, user.Username) - _, apperr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, apperr := th.App.Srv().Store().Token().GetByToken(token.Token) require.NoError(t, apperr) th.App.DeleteToken(token) }) @@ -63,7 +63,7 @@ func TestCWSLogin(t *testing.T) { t.Run("Should not authenticate the user when CWS token was used", func(t *testing.T) { token := model.NewToken(TokenTypeCWSAccess, "") os.Setenv("CWS_CLOUD_TOKEN", token.Token) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) user, err := th.App.AuthenticateUserForLogin(th.Context, "", th.BasicUser.Username, "", "", token.Token, false) require.NotNil(t, err) diff --git a/app/migrations.go b/app/migrations.go index 36d12302c1..21295aa840 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -28,7 +28,7 @@ func (a *App) DoAdvancedPermissionsMigration() { func (s *Server) doAdvancedPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(model.AdvancedPermissionsMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(model.AdvancedPermissionsMigrationKey); err == nil { return } @@ -38,13 +38,13 @@ func (s *Server) doAdvancedPermissionsMigration() { allSucceeded := true for _, role := range roles { - _, err := s.Store.Role().Save(role) + _, err := s.Store().Role().Save(role) if err == nil { continue } // If this failed for reasons other than the role already existing, don't mark the migration as done. - fetchedRole, err := s.Store.Role().GetByName(context.Background(), role.Name) + fetchedRole, err := s.Store().Role().GetByName(context.Background(), role.Name) if err != nil { mlog.Critical("Failed to migrate role to database.", mlog.Err(err)) allSucceeded = false @@ -57,7 +57,7 @@ func (s *Server) doAdvancedPermissionsMigration() { fetchedRole.Description != role.Description || fetchedRole.SchemeManaged != role.SchemeManaged { role.Id = fetchedRole.Id - if _, err = s.Store.Role().Save(role); err != nil { + if _, err = s.Store().Role().Save(role); err != nil { // Role is not the same, but failed to update. mlog.Critical("Failed to migrate role to database.", mlog.Err(err)) allSucceeded = false @@ -80,14 +80,14 @@ func (s *Server) doAdvancedPermissionsMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark advanced permissions migration as completed.", mlog.Err(err)) } } func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error { if !isComplete { - if _, err := a.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { + if _, err := a.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { return err } } @@ -101,7 +101,7 @@ func (a *App) DoEmojisPermissionsMigration() { func (s *Server) doEmojisPermissionsMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(EmojisPermissionsMigrationKey); err == nil { return } @@ -120,7 +120,7 @@ func (s *Server) doEmojisPermissionsMigration() { if role != nil { role.Permissions = append(role.Permissions, model.PermissionCreateEmojis.Id, model.PermissionDeleteEmojis.Id) - if _, nErr := s.Store.Role().Save(role); nErr != nil { + if _, nErr := s.Store().Role().Save(role); nErr != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(nErr)) return } @@ -137,7 +137,7 @@ func (s *Server) doEmojisPermissionsMigration() { model.PermissionDeleteEmojis.Id, model.PermissionDeleteOthersEmojis.Id, ) - if _, err := s.Store.Role().Save(systemAdminRole); err != nil { + if _, err := s.Store().Role().Save(systemAdminRole); err != nil { mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err)) return } @@ -147,7 +147,7 @@ func (s *Server) doEmojisPermissionsMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark emojis permissions migration as completed.", mlog.Err(err)) } } @@ -158,33 +158,33 @@ func (a *App) DoGuestRolesCreationMigration() { func (s *Server) doGuestRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(GuestRolesCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.ChannelGuestRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.ChannelGuestRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.ChannelGuestRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.ChannelGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.TeamGuestRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.TeamGuestRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.TeamGuestRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.TeamGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SystemGuestRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.SystemGuestRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.SystemGuestRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.SystemGuestRoleId]); err != nil { mlog.Critical("Failed to create new guest role to database.", mlog.Err(err)) allSucceeded = false } } - schemes, err := s.Store.Scheme().GetAllPage("", 0, 1000000) + schemes, err := s.Store().Scheme().GetAllPage("", 0, 1000000) if err != nil { mlog.Critical("Failed to get all schemes.", mlog.Err(err)) allSucceeded = false @@ -200,7 +200,7 @@ func (s *Server) doGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(teamGuestRole); err != nil { + if savedRole, err := s.Store().Role().Save(teamGuestRole); err != nil { mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -216,14 +216,14 @@ func (s *Server) doGuestRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(channelGuestRole); err != nil { + if savedRole, err := s.Store().Role().Save(channelGuestRole); err != nil { mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err)) allSucceeded = false } else { scheme.DefaultChannelGuestRole = savedRole.Name } - _, err := s.Store.Scheme().Save(scheme) + _, err := s.Store().Scheme().Save(scheme) if err != nil { mlog.Critical("Failed to update custom scheme.", mlog.Err(err)) allSucceeded = false @@ -240,7 +240,7 @@ func (s *Server) doGuestRolesCreationMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark guest roles creation migration as completed.", mlog.Err(err)) } } @@ -251,27 +251,27 @@ func (a *App) DoSystemConsoleRolesCreationMigration() { func (s *Server) doSystemConsoleRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.SystemManagerRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.SystemManagerRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.SystemManagerRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.SystemManagerRoleId]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemManagerRoleId)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SystemReadOnlyAdminRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.SystemReadOnlyAdminRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.SystemReadOnlyAdminRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.SystemReadOnlyAdminRoleId]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemReadOnlyAdminRoleId)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.SystemUserManagerRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.SystemUserManagerRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.SystemUserManagerRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.SystemUserManagerRoleId]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemUserManagerRoleId)) allSucceeded = false } @@ -286,22 +286,22 @@ func (s *Server) doSystemConsoleRolesCreationMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark system console roles creation migration as completed.", mlog.Err(err)) } } func (s *Server) doCustomGroupAdminRoleCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(CustomGroupAdminRoleCreationMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(CustomGroupAdminRoleCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.SystemCustomGroupAdminRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.SystemCustomGroupAdminRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.SystemCustomGroupAdminRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.SystemCustomGroupAdminRoleId]); err != nil { mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SystemCustomGroupAdminRoleId)) allSucceeded = false } @@ -316,14 +316,14 @@ func (s *Server) doCustomGroupAdminRoleCreationMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark custom group admin role creation migration as completed.", mlog.Err(err)) } } func (s *Server) doContentExtractionConfigDefaultTrueMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil { return } @@ -336,45 +336,45 @@ func (s *Server) doContentExtractionConfigDefaultTrueMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark content extraction config migration as completed.", mlog.Err(err)) } } func (s *Server) doPlaybooksRolesCreationMigration() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(PlaybookRolesCreationMigrationKey); err == nil { + if _, err := s.Store().System().GetByName(PlaybookRolesCreationMigrationKey); err == nil { return } roles := model.MakeDefaultRoles() allSucceeded := true - if _, err := s.Store.Role().GetByName(context.Background(), model.PlaybookAdminRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.PlaybookAdminRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.PlaybookAdminRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.PlaybookAdminRoleId]); err != nil { mlog.Critical("Failed to create new playbook admin role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.PlaybookMemberRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.PlaybookMemberRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.PlaybookMemberRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.PlaybookMemberRoleId]); err != nil { mlog.Critical("Failed to create new playbook member role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.RunAdminRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.RunAdminRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.RunAdminRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.RunAdminRoleId]); err != nil { mlog.Critical("Failed to create new run admin role to database.", mlog.Err(err)) allSucceeded = false } } - if _, err := s.Store.Role().GetByName(context.Background(), model.RunMemberRoleId); err != nil { - if _, err := s.Store.Role().Save(roles[model.RunMemberRoleId]); err != nil { + if _, err := s.Store().Role().GetByName(context.Background(), model.RunMemberRoleId); err != nil { + if _, err := s.Store().Role().Save(roles[model.RunMemberRoleId]); err != nil { mlog.Critical("Failed to create new run member role to database.", mlog.Err(err)) allSucceeded = false } } - schemes, err := s.Store.Scheme().GetAllPage(model.SchemeScopeTeam, 0, 1000000) + schemes, err := s.Store().Scheme().GetAllPage(model.SchemeScopeTeam, 0, 1000000) if err != nil { mlog.Critical("Failed to get all schemes.", mlog.Err(err)) allSucceeded = false @@ -390,7 +390,7 @@ func (s *Server) doPlaybooksRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(playbookAdminRole); err != nil { + if savedRole, err := s.Store().Role().Save(playbookAdminRole); err != nil { mlog.Critical("Failed to create new playbook admin role for existing custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -405,7 +405,7 @@ func (s *Server) doPlaybooksRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(playbookMember); err != nil { + if savedRole, err := s.Store().Role().Save(playbookMember); err != nil { mlog.Critical("Failed to create new playbook member role for existing custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -421,7 +421,7 @@ func (s *Server) doPlaybooksRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(runAdminRole); err != nil { + if savedRole, err := s.Store().Role().Save(runAdminRole); err != nil { mlog.Critical("Failed to create new run admin role for existing custom scheme.", mlog.Err(err)) allSucceeded = false } else { @@ -437,14 +437,14 @@ func (s *Server) doPlaybooksRolesCreationMigration() { SchemeManaged: true, } - if savedRole, err := s.Store.Role().Save(runMemberRole); err != nil { + if savedRole, err := s.Store().Role().Save(runMemberRole); err != nil { mlog.Critical("Failed to create new run member role for existing custom scheme.", mlog.Err(err)) allSucceeded = false } else { scheme.DefaultRunMemberRole = savedRole.Name } } - _, err := s.Store.Scheme().Save(scheme) + _, err := s.Store().Scheme().Save(scheme) if err != nil { mlog.Critical("Failed to update custom scheme.", mlog.Err(err)) allSucceeded = false @@ -461,7 +461,7 @@ func (s *Server) doPlaybooksRolesCreationMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark playbook roles creation migration as completed.", mlog.Err(err)) } @@ -479,11 +479,11 @@ func (s *Server) doFirstAdminSetupCompleteMigration() { } // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(FirstAdminSetupCompleteKey); err == nil { + if _, err := s.Store().System().GetByName(FirstAdminSetupCompleteKey); err == nil { return } - teams, err := s.Store.Team().GetAll() + teams, err := s.Store().Team().GetAll() if err != nil { // can not confirm that admin has started in this case. return @@ -496,7 +496,7 @@ func (s *Server) doFirstAdminSetupCompleteMigration() { } // if there are teams, then if this isn't a new installation, there should be posts - postCount, err := s.Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + postCount, err := s.Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) if err != nil || postCount < existingInstallationPostsThreshold { return } @@ -506,23 +506,23 @@ func (s *Server) doFirstAdminSetupCompleteMigration() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark first admin setup migration as completed.", mlog.Err(err)) } } func (s *Server) doRemainingSchemaMigrations() { // If the migration is already marked as completed, don't do it again. - if _, err := s.Store.System().GetByName(remainingSchemaMigrationsKey); err == nil { + if _, err := s.Store().System().GetByName(remainingSchemaMigrationsKey); err == nil { return } - if teams, err := s.Store.Team().GetByEmptyInviteID(); err != nil { + if teams, err := s.Store().Team().GetByEmptyInviteID(); err != nil { mlog.Error("Error fetching Teams without InviteID", mlog.Err(err)) } else { for _, team := range teams { team.InviteId = model.NewId() - if _, err := s.Store.Team().Update(team); err != nil { + if _, err := s.Store().Team().Update(team); err != nil { mlog.Error("Error updating Team InviteIDs", mlog.String("team_id", team.Id), mlog.Err(err)) } } @@ -533,7 +533,7 @@ func (s *Server) doRemainingSchemaMigrations() { Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Critical("Failed to mark the remaining schema migrations as completed.", mlog.Err(err)) } } diff --git a/app/notification.go b/app/notification.go index b0870c612f..f143789f4b 100644 --- a/app/notification.go +++ b/app/notification.go @@ -47,14 +47,14 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea pchan := make(chan store.StoreResult, 1) go func() { - props, err := a.Srv().Store.User().GetAllProfilesInChannel(context.Background(), channel.Id, true) + props, err := a.Srv().Store().User().GetAllProfilesInChannel(context.Background(), channel.Id, true) pchan <- store.StoreResult{Data: props, NErr: err} close(pchan) }() cmnchan := make(chan store.StoreResult, 1) go func() { - props, err := a.Srv().Store.Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) + props, err := a.Srv().Store().Channel().GetAllChannelMembersNotifyPropsForChannel(channel.Id, true) cmnchan <- store.StoreResult{Data: props, NErr: err} close(cmnchan) }() @@ -73,7 +73,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea if len(post.FileIds) != 0 { fchan = make(chan store.StoreResult, 1) go func() { - fileInfos, err := a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, true) + fileInfos, err := a.Srv().Store().FileInfo().GetForPost(post.Id, true, false, true) fchan <- store.StoreResult{Data: fileInfos, NErr: err} close(fchan) }() @@ -83,7 +83,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea if isCRTAllowed && post.RootId != "" { tchan = make(chan store.StoreResult, 1) go func() { - followers, err := a.Srv().Store.Thread().GetThreadFollowers(post.RootId, true) + followers, err := a.Srv().Store().Thread().GetThreadFollowers(post.RootId, true) tchan <- store.StoreResult{Data: followers, NErr: err} close(tchan) }() @@ -253,7 +253,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea mentionType, incrementMentions := mentions.Mentions[userID] // if the user was not explicitly mentioned, check if they explicitly unfollowed the thread if !incrementMentions { - membership, err := a.Srv().Store.Thread().GetMembershipForUser(userID, post.RootId) + membership, err := a.Srv().Store().Thread().GetMembershipForUser(userID, post.RootId) var nfErr *store.ErrNotFound if err != nil && !errors.As(err, &nfErr) { @@ -278,7 +278,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea UpdateViewedTimestamp: false, UpdateParticipants: userID == post.UserId, } - threadMembership, err := a.Srv().Store.Thread().MaintainMembership(userID, post.RootId, opts) + threadMembership, err := a.Srv().Store().Thread().MaintainMembership(userID, post.RootId, opts) if err != nil { mac <- model.NewAppError("SendNotifications", "app.channel.autofollow.app_error", nil, "", http.StatusInternalServerError).Wrap(err) return @@ -305,7 +305,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea mentionedUsersList = append(mentionedUsersList, id) } - nErr := a.Srv().Store.Channel().IncrementMentionCount(post.ChannelId, mentionedUsersList, post.RootId == "") + nErr := a.Srv().Store().Channel().IncrementMentionCount(post.ChannelId, mentionedUsersList, post.RootId == "") if nErr != nil { mlog.Warn( "Failed to update mention count", @@ -587,7 +587,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, team.Id, "", uid, nil, "") threadMembership := participantMemberships[uid] if threadMembership == nil { - tm, err := a.Srv().Store.Thread().GetMembershipForUser(uid, post.RootId) + tm, err := a.Srv().Store().Thread().GetMembershipForUser(uid, post.RootId) if err != nil { return nil, errors.Wrapf(err, "Missing thread membership for participant in notifications. user_id=%q thread_id=%q", uid, post.RootId) } @@ -596,7 +596,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea } threadMembership = tm } - userThread, err := a.Srv().Store.Thread().GetThreadForUser(channel.TeamId, threadMembership, true) + userThread, err := a.Srv().Store().Thread().GetThreadForUser(channel.TeamId, threadMembership, true) if err != nil { return nil, errors.Wrapf(err, "cannot get thread %q for user %q", post.RootId, uid) } @@ -620,7 +620,7 @@ func (a *App) SendNotifications(c request.CTX, post *model.Post, team *model.Tea UpdateViewedTimestamp: true, } // should set unread mentions, and unread replies to 0 - _, err = a.Srv().Store.Thread().MaintainMembership(uid, post.RootId, opts) + _, err = a.Srv().Store().Thread().MaintainMembership(uid, post.RootId, opts) if err != nil { return nil, errors.Wrapf(err, "cannot maintain thread membership %q for user %q", post.RootId, uid) } @@ -755,7 +755,7 @@ func (a *App) filterOutOfChannelMentions(sender *model.User, post *model.Post, c return nil, nil, nil } - users, err := a.Srv().Store.User().GetProfilesByUsernames(potentialMentions, &model.ViewUsersRestrictions{Teams: []string{channel.TeamId}}) + users, err := a.Srv().Store().User().GetProfilesByUsernames(potentialMentions, &model.ViewUsersRestrictions{Teams: []string{channel.TeamId}}) if err != nil { return nil, nil, err } @@ -1067,9 +1067,9 @@ func (a *App) getGroupsAllowedForReferenceInChannel(channel *model.Channel, team if channel.IsGroupConstrained() || (team != nil && team.IsGroupConstrained()) { var groups []*model.GroupWithSchemeAdmin if channel.IsGroupConstrained() { - groups, err = a.Srv().Store.Group().GetGroupsByChannel(channel.Id, opts) + groups, err = a.Srv().Store().Group().GetGroupsByChannel(channel.Id, opts) } else { - groups, err = a.Srv().Store.Group().GetGroupsByTeam(team.Id, opts) + groups, err = a.Srv().Store().Group().GetGroupsByTeam(team.Id, opts) } if err != nil { return nil, errors.Wrap(err, "unable to get groups") @@ -1082,7 +1082,7 @@ func (a *App) getGroupsAllowedForReferenceInChannel(channel *model.Channel, team return groupsMap, nil } - groups, err := a.Srv().Store.Group().GetGroups(0, 0, opts) + groups, err := a.Srv().Store().Group().GetGroups(0, 0, opts) if err != nil { return nil, errors.Wrap(err, "unable to get groups") } @@ -1122,9 +1122,9 @@ func (a *App) insertGroupMentions(group *model.Group, channel *model.Channel, pr isGroupOrDirect := channel.IsGroupOrDirect() if isGroupOrDirect { - groupMembers, err = a.Srv().Store.Group().GetMemberUsers(group.Id) + groupMembers, err = a.Srv().Store().Group().GetMemberUsers(group.Id) } else { - groupMembers, err = a.Srv().Store.Group().GetMemberUsersInTeam(group.Id, channel.TeamId) + groupMembers, err = a.Srv().Store().Group().GetMemberUsersInTeam(group.Id, channel.TeamId) } if err != nil { @@ -1369,7 +1369,7 @@ func (a *App) GetNotificationNameFormat(user *model.User) string { return model.ShowUsername } - data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameNameFormat) + data, err := a.Srv().Store().Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameNameFormat) if err != nil { return *a.Config().TeamSettings.TeammateNameDisplay } diff --git a/app/notification_email.go b/app/notification_email.go index 9690152a57..914b729a01 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -25,7 +25,7 @@ func (a *App) sendNotificationEmail(c request.CTX, notification *PostNotificatio post := notification.Post if channel.IsGroupOrDirect() { - teams, err := a.Srv().Store.Team().GetTeamsByUserId(user.Id) + teams, err := a.Srv().Store().Team().GetTeamsByUserId(user.Id) if err != nil { return errors.Wrap(err, "unable to get user teams") } @@ -50,7 +50,7 @@ func (a *App) sendNotificationEmail(c request.CTX, notification *PostNotificatio if *a.Config().EmailSettings.EnableEmailBatching { var sendBatched bool - if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval); err != nil { + if data, err := a.Srv().Store().Preference().Get(user.Id, model.PreferenceCategoryNotifications, model.PreferenceNameEmailInterval); err != nil { // if the call fails, assume that the interval has not been explicitly set and batch the notifications sendBatched = true } else { @@ -70,7 +70,7 @@ func (a *App) sendNotificationEmail(c request.CTX, notification *PostNotificatio translateFunc := i18n.GetUserTranslations(user.Locale) var useMilitaryTime bool - if data, err := a.Srv().Store.Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime); err != nil { + if data, err := a.Srv().Store().Preference().Get(user.Id, model.PreferenceCategoryDisplaySettings, model.PreferenceNameUseMilitaryTime); err != nil { useMilitaryTime = true } else { useMilitaryTime = data.Value == "true" diff --git a/app/notification_email_test.go b/app/notification_email_test.go index 312cd03872..8b48b50035 100644 --- a/app/notification_email_test.go +++ b/app/notification_email_test.go @@ -85,7 +85,7 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -116,7 +116,7 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -147,7 +147,7 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -178,7 +178,7 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -213,7 +213,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeWithTimezone(t *testi emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -247,7 +247,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTimeNoTimezone(t *testing emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -296,7 +296,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime12Hour(t *testing.T) emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -329,7 +329,7 @@ func TestGetNotificationEmailBodyFullNotificationLocaleTime24Hour(t *testing.T) emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -359,7 +359,7 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -389,7 +389,7 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -419,7 +419,7 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -449,7 +449,7 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) emailNotificationContentsType := model.EmailNotificationContentsGeneric translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -481,7 +481,7 @@ func TestGetNotificationEmailEscapingChars(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -521,7 +521,7 @@ func TestGetNotificationEmailBodyPublicChannelMention(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -587,7 +587,7 @@ func TestGetNotificationEmailBodyMultiPublicChannelMention(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -636,7 +636,7 @@ func TestGetNotificationEmailBodyPrivateChannelMention(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -669,7 +669,7 @@ func TestGenerateHyperlinkForChannelsPublic(t *testing.T) { teamName := "testteam" teamURL := "http://localhost:8065/testteam" - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -719,7 +719,7 @@ func TestGenerateHyperlinkForChannelsMultiPublic(t *testing.T) { teamName := "testteam" teamURL := "http://localhost:8065/testteam" - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -753,7 +753,7 @@ func TestGenerateHyperlinkForChannelsPrivate(t *testing.T) { teamName := "testteam" teamURL := "http://localhost:8065/testteam" - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Id: "test", Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -786,7 +786,7 @@ func TestLandingLink(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -816,7 +816,7 @@ func TestLandingLinkPermalink(t *testing.T) { emailNotificationContentsType := model.EmailNotificationContentsFull translateFunc := i18n.GetUserTranslations("en") - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) @@ -913,7 +913,7 @@ func TestMarkdownConversion(t *testing.T) { defer th.TearDown() recipient := &model.User{} - storeMock := th.App.Srv().Store.(*mocks.Store) + storeMock := th.App.Srv().Store().(*mocks.Store) teamStoreMock := mocks.TeamStore{} teamStoreMock.On("GetByName", "testteam").Return(&model.Team{Name: "testteam"}, nil) storeMock.On("Team").Return(&teamStoreMock) diff --git a/app/notification_push.go b/app/notification_push.go index a50b16ceab..3861d15f13 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -220,14 +220,14 @@ func (a *App) getPushNotificationMessage(contentsConfig, postMessage string, exp } func (a *App) getUserBadgeCount(userID string, isCRTEnabled bool) (int, *model.AppError) { - unreadCount, err := a.Srv().Store.User().GetUnreadCount(userID, isCRTEnabled) + unreadCount, err := a.Srv().Store().User().GetUnreadCount(userID, isCRTEnabled) if err != nil { return 0, model.NewAppError("getUserBadgeCount", "app.user.get_unread_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } badgeCount := int(unreadCount) if isCRTEnabled { - threadUnreadMentions, err := a.Srv().Store.Thread().GetTotalUnreadMentions(userID, "", model.GetUserThreadsOpts{}) + threadUnreadMentions, err := a.Srv().Store().Thread().GetTotalUnreadMentions(userID, "", model.GetUserThreadsOpts{}) if err != nil { return 0, model.NewAppError("getUserBadgeCount", "app.user.get_thread_count_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -483,7 +483,7 @@ func (a *App) SendAckToPushProxy(ack *model.PushNotificationAck) error { } func (a *App) getMobileAppSessions(userID string) ([]*model.Session, *model.AppError) { - sessions, err := a.Srv().Store.Session().GetSessionsWithActiveDeviceIds(userID) + sessions, err := a.Srv().Store().Session().GetSessionsWithActiveDeviceIds(userID) if err != nil { return nil, model.NewAppError("getMobileAppSessions", "app.session.get_sessions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/notification_push_test.go b/app/notification_push_test.go index dfb226573e..6dd1b5a2ff 100644 --- a/app/notification_push_test.go +++ b/app/notification_push_test.go @@ -555,7 +555,7 @@ func TestGetPushNotificationMessage(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -1133,7 +1133,7 @@ func TestClearPushNotificationSync(t *testing.T) { ExpiresAt: model.GetMillis() + 100000, } - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockUserStore.On("GetUnreadCount", mock.AnythingOfType("string"), mock.AnythingOfType("bool")).Return(int64(1), nil) @@ -1209,7 +1209,7 @@ func TestUpdateMobileAppBadgeSync(t *testing.T) { ExpiresAt: model.GetMillis() + 100000, } - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockUserStore.On("GetUnreadCount", mock.AnythingOfType("string"), mock.AnythingOfType("bool")).Return(int64(1), nil) @@ -1282,7 +1282,7 @@ func TestSendAckToPushProxy(t *testing.T) { ) defer pushServer.Close() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -1440,7 +1440,6 @@ func TestPushNotificationRace(t *testing.T) { Return(&model.Preference{Value: "test"}, nil) mockStore.On("Preference").Return(&mockPreferenceStore) s := &Server{ - Store: mockStore, products: make(map[string]Product), Router: mux.NewRouter(), filestore: &fmocks.FileBackend{}, @@ -1449,6 +1448,7 @@ func TestPushNotificationRace(t *testing.T) { s.platform, err = platform.New(platform.ServiceConfig{ ConfigStore: memoryStore, }) + s.SetStore(mockStore) require.NoError(t, err) serviceMap := map[ServiceKey]any{ ConfigKey: s.platform, @@ -1527,7 +1527,7 @@ func BenchmarkPushNotificationThroughput(b *testing.B) { ) defer pushServer.Close() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockUserStore.On("GetUnreadCount", mock.AnythingOfType("string"), mock.AnythingOfType("bool")).Return(int64(1), nil) diff --git a/app/notification_test.go b/app/notification_test.go index 4929244bb7..26903e3e48 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -189,7 +189,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { t.Run("1-mention", func(t *testing.T) { for i, user := range users { t.Run(fmt.Sprintf("user-%d", i+1), func(t *testing.T) { - channelUnread, appErr2 := th.Server.Store.Channel().GetChannelUnread(th.BasicChannel.Id, user.Id) + channelUnread, appErr2 := th.Server.Store().Channel().GetChannelUnread(th.BasicChannel.Id, user.Id) require.NoError(t, appErr2) assert.Equal(t, int64(1), channelUnread.MentionCount) }) @@ -209,7 +209,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) { t.Run("2-mentions", func(t *testing.T) { for i, user := range users { t.Run(fmt.Sprintf("user-%d", i+1), func(t *testing.T) { - channelUnread, appErr2 := th.Server.Store.Channel().GetChannelUnread(th.BasicChannel.Id, user.Id) + channelUnread, appErr2 := th.Server.Store().Channel().GetChannelUnread(th.BasicChannel.Id, user.Id) require.NoError(t, appErr2) assert.Equal(t, int64(2), channelUnread.MentionCount) }) diff --git a/app/notify_admin.go b/app/notify_admin.go index da1cecfd9c..b006bc5106 100644 --- a/app/notify_admin.go +++ b/app/notify_admin.go @@ -57,7 +57,7 @@ func (a *App) DoCheckForAdminNotifications(trial bool) *model.AppError { } func (a *App) SaveAdminNotifyData(data *model.NotifyAdminData) (*model.NotifyAdminData, *model.AppError) { - d, err := a.Srv().Store.NotifyAdmin().Save(data) + d, err := a.Srv().Store().NotifyAdmin().Save(data) if err != nil { var nfErr *store.ErrNotFound switch { @@ -102,7 +102,7 @@ func (a *App) SendNotifyAdminPosts(c *request.Context, workspaceName string, cur now := model.GetMillis() - data, err := a.Srv().Store.NotifyAdmin().Get(trial) + data, err := a.Srv().Store().NotifyAdmin().Get(trial) if err != nil { return model.NewAppError("SendNotifyAdminPosts", "app.notify_admin.send_notification_post.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -162,7 +162,7 @@ func (a *App) SendNotifyAdminPosts(c *request.Context, workspaceName string, cur } func (a *App) UserAlreadyNotifiedOnRequiredFeature(user string, feature model.MattermostPaidFeature) bool { - data, err := a.Srv().Store.NotifyAdmin().GetDataByUserIdAndFeature(user, feature) + data, err := a.Srv().Store().NotifyAdmin().GetDataByUserIdAndFeature(user, feature) if err != nil { return false } @@ -179,7 +179,7 @@ func (a *App) CanNotifyAdmin(trial bool) bool { systemVarName = lastTrialNotificationTimeStamp } - sysVal, sysValErr := a.Srv().Store.System().GetByName(systemVarName) + sysVal, sysValErr := a.Srv().Store().System().GetByName(systemVarName) if sysValErr != nil { var nfErr *store.ErrNotFound if errors.As(sysValErr, &nfErr) { // if no timestamps have been recorded before, system is free to notify @@ -213,12 +213,12 @@ func (a *App) FinishSendAdminNotifyPost(trial bool, now int64) { val := strconv.FormatInt(model.GetMillis(), 10) sysVar := &model.System{Name: systemVarName, Value: val} - if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { + if err := a.Srv().Store().System().SaveOrUpdate(sysVar); err != nil { mlog.Error("Unable to finish send admin notify post job", mlog.Err(err)) } // all the notifications are now sent in a post and can safely be removed - if err := a.Srv().Store.NotifyAdmin().DeleteBefore(trial, now); err != nil { + if err := a.Srv().Store().NotifyAdmin().DeleteBefore(trial, now); err != nil { mlog.Error("Unable to finish send admin notify post job", mlog.Err(err)) } diff --git a/app/notify_admin_test.go b/app/notify_admin_test.go index 39c7745b6e..c784622f38 100644 --- a/app/notify_admin_test.go +++ b/app/notify_admin_test.go @@ -76,7 +76,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { if time.Since(begin) > timeout { break } - channel, err = th.App.Srv().Store.Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) + channel, err = th.App.Srv().Store().Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) if err == nil && channel != nil { break } @@ -84,7 +84,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { } require.NoError(t, err, "Expected message to have been sent within %d seconds", timeout) - postList, err := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) + postList, err := th.App.Srv().Store().Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) require.NoError(t, err) post := postList.Posts[postList.Order[0]] @@ -124,7 +124,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { if time.Since(begin) > timeout { break } - channel, err = th.App.Srv().Store.Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) + channel, err = th.App.Srv().Store().Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) if err == nil && channel != nil { break } @@ -132,7 +132,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { } require.NoError(t, err, "Expected message to have been sent within %d seconds", timeout) - postList, err := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) + postList, err := th.App.Srv().Store().Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) require.NoError(t, err) post := postList.Posts[postList.Order[0]] @@ -248,7 +248,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { if time.Since(begin) > timeout { break } - channel, err = th.App.Srv().Store.Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) + channel, err = th.App.Srv().Store().Channel().GetByName("", model.GetDMNameFromIds(bot.UserId, th.SystemAdminUser.Id), false) if err == nil && channel != nil { break } @@ -256,7 +256,7 @@ func Test_SendNotifyAdminPosts(t *testing.T) { } require.NoError(t, err, "Expected message to have been sent within %d seconds", timeout) - postList, err := th.App.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) + postList, err := th.App.Srv().Store().Post().GetPosts(model.GetPostsOptions{ChannelId: channel.Id, Page: 0, PerPage: 1}, false, map[string]bool{}) require.NoError(t, err) post := postList.Posts[postList.Order[0]] diff --git a/app/oauth.go b/app/oauth.go index e78596ea41..c0ca0484b4 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -16,8 +16,8 @@ import ( "strings" "time" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/app/request" - "github.com/mattermost/mattermost-server/v6/app/users" "github.com/mattermost/mattermost-server/v6/einterfaces" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" @@ -40,7 +40,7 @@ func (a *App) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppEr app.ClientSecret = model.NewId() - oauthApp, err := a.Srv().Store.OAuth().SaveApp(app) + oauthApp, err := a.Srv().Store().OAuth().SaveApp(app) if err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -62,7 +62,7 @@ func (a *App) GetOAuthApp(appID string) (*model.OAuthApp, *model.AppError) { return nil, model.NewAppError("GetOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - oauthApp, err := a.Srv().Store.OAuth().GetApp(appID) + oauthApp, err := a.Srv().Store().OAuth().GetApp(appID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -86,7 +86,7 @@ func (a *App) UpdateOAuthApp(oldApp, updatedApp *model.OAuthApp) (*model.OAuthAp updatedApp.CreateAt = oldApp.CreateAt updatedApp.ClientSecret = oldApp.ClientSecret - oauthApp, err := a.Srv().Store.OAuth().UpdateApp(updatedApp) + oauthApp, err := a.Srv().Store().OAuth().UpdateApp(updatedApp) if err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -108,7 +108,7 @@ func (a *App) DeleteOAuthApp(appID string) *model.AppError { return model.NewAppError("DeleteOAuthApp", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - if err := a.Srv().Store.OAuth().DeleteApp(appID); err != nil { + if err := a.Srv().Store().OAuth().DeleteApp(appID); err != nil { return model.NewAppError("DeleteOAuthApp", "app.oauth.delete_app.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -124,7 +124,7 @@ func (a *App) GetOAuthApps(page, perPage int) ([]*model.OAuthApp, *model.AppErro return nil, model.NewAppError("GetOAuthApps", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - oauthApps, err := a.Srv().Store.OAuth().GetApps(page*perPage, perPage) + oauthApps, err := a.Srv().Store().OAuth().GetApps(page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetOAuthApps", "app.oauth.get_apps.find.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -137,7 +137,7 @@ func (a *App) GetOAuthAppsByCreator(userID string, page, perPage int) ([]*model. return nil, model.NewAppError("GetOAuthAppsByUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - oauthApps, err := a.Srv().Store.OAuth().GetAppByUser(userID, page*perPage, perPage) + oauthApps, err := a.Srv().Store().OAuth().GetAppByUser(userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetOAuthAppsByCreator", "app.oauth.get_app_by_user.find.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -165,7 +165,7 @@ func (a *App) GetOAuthCodeRedirect(userID string, authRequest *model.AuthorizeRe authData := &model.AuthData{UserId: userID, ClientId: authRequest.ClientId, CreateAt: model.GetMillis(), RedirectUri: authRequest.RedirectURI, State: authRequest.State, Scope: authRequest.Scope} authData.Code = model.NewId() + model.NewId() - if _, err := a.Srv().Store.OAuth().SaveAuthData(authData); err != nil { + if _, err := a.Srv().Store().OAuth().SaveAuthData(authData); err != nil { return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil } @@ -181,7 +181,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author authRequest.Scope = model.DefaultScope } - oauthApp, nErr := a.Srv().Store.OAuth().GetApp(authRequest.ClientId) + oauthApp, nErr := a.Srv().Store().OAuth().GetApp(authRequest.ClientId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -220,7 +220,7 @@ func (a *App) AllowOAuthAppAccessToUser(userID string, authRequest *model.Author Value: authRequest.Scope, } - if nErr := a.Srv().Store.Preference().Save(model.Preferences{authorizedApp}); nErr != nil { + if nErr := a.Srv().Store().Preference().Save(model.Preferences{authorizedApp}); nErr != nil { mlog.Warn("error saving store preference", mlog.Err(nErr)) return authRequest.RedirectURI + "?error=server_error&state=" + authRequest.State, nil } @@ -250,7 +250,7 @@ func (a *App) GetOAuthAccessTokenForImplicitFlow(userID string, authRequest *mod accessData := &model.AccessData{ClientId: authRequest.ClientId, UserId: user.Id, Token: session.Token, RefreshToken: "", RedirectUri: authRequest.RedirectURI, ExpiresAt: session.ExpiresAt, Scope: authRequest.Scope} - if _, err := a.Srv().Store.OAuth().SaveAccessData(accessData); err != nil { + if _, err := a.Srv().Store().OAuth().SaveAccessData(accessData); err != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -262,7 +262,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, c return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.disabled.app_error", nil, "", http.StatusNotImplemented) } - oauthApp, nErr := a.Srv().Store.OAuth().GetApp(clientId) + oauthApp, nErr := a.Srv().Store().OAuth().GetApp(clientId) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.credentials.app_error", nil, "", http.StatusNotFound) } @@ -276,13 +276,13 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, c var user *model.User if grantType == model.AccessTokenGrantType { var authData *model.AuthData - authData, nErr = a.Srv().Store.OAuth().GetAuthData(code) + authData, nErr = a.Srv().Store().OAuth().GetAuthData(code) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusBadRequest) } if authData.IsExpired() { - if nErr = a.Srv().Store.OAuth().RemoveAuthData(authData.Code); nErr != nil { + if nErr = a.Srv().Store().OAuth().RemoveAuthData(authData.Code); nErr != nil { mlog.Warn("unable to remove auth data", mlog.Err(nErr)) } return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.expired_code.app_error", nil, "", http.StatusForbidden) @@ -292,12 +292,12 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, c return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.redirect_uri.app_error", nil, "", http.StatusBadRequest) } - user, nErr = a.Srv().Store.User().Get(context.Background(), authData.UserId) + user, nErr = a.Srv().Store().User().Get(context.Background(), authData.UserId) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } - accessData, nErr = a.Srv().Store.OAuth().GetPreviousAccessData(user.Id, clientId) + accessData, nErr = a.Srv().Store().OAuth().GetPreviousAccessData(user.Id, clientId) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal.app_error", nil, "", http.StatusBadRequest) } @@ -329,7 +329,7 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, c accessData = &model.AccessData{ClientId: clientId, UserId: user.Id, Token: session.Token, RefreshToken: model.NewId(), RedirectUri: redirectURI, ExpiresAt: session.ExpiresAt, Scope: authData.Scope} - if _, nErr = a.Srv().Store.OAuth().SaveAccessData(accessData); nErr != nil { + if _, nErr = a.Srv().Store().OAuth().SaveAccessData(accessData); nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } @@ -341,17 +341,17 @@ func (a *App) GetOAuthAccessTokenForCodeFlow(clientId, grantType, redirectURI, c } } - if nErr = a.Srv().Store.OAuth().RemoveAuthData(authData.Code); nErr != nil { + if nErr = a.Srv().Store().OAuth().RemoveAuthData(authData.Code); nErr != nil { mlog.Warn("unable to remove auth data", mlog.Err(nErr)) } } else { // When grantType is refresh_token - accessData, nErr = a.Srv().Store.OAuth().GetAccessDataByRefreshToken(refreshToken) + accessData, nErr = a.Srv().Store().OAuth().GetAccessDataByRefreshToken(refreshToken) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.refresh_token.app_error", nil, "", http.StatusNotFound) } - user, nErr := a.Srv().Store.User().Get(context.Background(), accessData.UserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), accessData.UserId) if nErr != nil { return nil, model.NewAppError("GetOAuthAccessToken", "api.oauth.get_access_token.internal_user.app_error", nil, "", http.StatusNotFound) } @@ -370,26 +370,26 @@ func (a *App) newSession(app *model.OAuthApp, user *model.User) (*model.Session, // Set new token an session session := &model.Session{UserId: user.Id, Roles: user.Roles, IsOAuth: true} session.GenerateCSRF() - a.ch.srv.userService.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthSSOInHours) + a.ch.srv.platform.SetSessionExpireInHours(session, *a.Config().ServiceSettings.SessionLengthSSOInHours) session.AddProp(model.SessionPropPlatform, app.Name) session.AddProp(model.SessionPropOAuthAppID, app.Id) session.AddProp(model.SessionPropMattermostAppID, app.MattermostAppID) session.AddProp(model.SessionPropOs, "OAuth2") session.AddProp(model.SessionPropBrowser, "OAuth2") - session, err := a.Srv().Store.Session().Save(session) + session, err := a.Srv().Store().Session().Save(session) if err != nil { return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError) } - a.ch.srv.userService.AddSessionToCache(session) + a.ch.srv.platform.AddSessionToCache(session) return session, nil } func (a *App) newSessionUpdateToken(app *model.OAuthApp, accessData *model.AccessData, user *model.User) (*model.AccessResponse, *model.AppError) { // Remove the previous session - if err := a.Srv().Store.Session().Remove(accessData.Token); err != nil { + if err := a.Srv().Store().Session().Remove(accessData.Token); err != nil { mlog.Warn("error removing access data token from session", mlog.Err(err)) } @@ -402,7 +402,7 @@ func (a *App) newSessionUpdateToken(app *model.OAuthApp, accessData *model.Acces accessData.RefreshToken = model.NewId() accessData.ExpiresAt = session.ExpiresAt - if _, err := a.Srv().Store.OAuth().UpdateAccessData(accessData); err != nil { + if _, err := a.Srv().Store().OAuth().UpdateAccessData(accessData); err != nil { return nil, model.NewAppError("newSessionUpdateToken", "web.get_access_token.internal_saving.app_error", nil, "", http.StatusInternalServerError) } accessRsp := &model.AccessResponse{ @@ -456,7 +456,7 @@ func (a *App) GetAuthorizedAppsForUser(userID string, page, perPage int) ([]*mod return nil, model.NewAppError("GetAuthorizedAppsForUser", "api.oauth.allow_oauth.turn_off.app_error", nil, "", http.StatusNotImplemented) } - apps, err := a.Srv().Store.OAuth().GetAuthorizedApps(userID, page*perPage, perPage) + apps, err := a.Srv().Store().OAuth().GetAuthorizedApps(userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetAuthorizedAppsForUser", "app.oauth.get_apps.find.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -475,7 +475,7 @@ func (a *App) DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError { } // Revoke app sessions - accessData, err := a.Srv().Store.OAuth().GetAccessDataByUserForApp(userID, appID) + accessData, err := a.Srv().Store().OAuth().GetAccessDataByUserForApp(userID, appID) if err != nil { return model.NewAppError("DeauthorizeOAuthAppForUser", "app.oauth.get_access_data_by_user_for_app.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -485,13 +485,13 @@ func (a *App) DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError { return err } - if err := a.Srv().Store.OAuth().RemoveAccessData(ad.Token); err != nil { + if err := a.Srv().Store().OAuth().RemoveAccessData(ad.Token); err != nil { return model.NewAppError("DeauthorizeOAuthAppForUser", "app.oauth.remove_access_data.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } } // Deauthorize the app - if err := a.Srv().Store.Preference().Delete(userID, model.PreferenceCategoryAuthorizedOAuthApp, appID); err != nil { + if err := a.Srv().Store().Preference().Delete(userID, model.PreferenceCategoryAuthorizedOAuthApp, appID); err != nil { return model.NewAppError("DeauthorizeOAuthAppForUser", "app.preference.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -504,7 +504,7 @@ func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *m } app.ClientSecret = model.NewId() - if _, err := a.Srv().Store.OAuth().UpdateApp(app); err != nil { + if _, err := a.Srv().Store().OAuth().UpdateApp(app); err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput switch { @@ -521,13 +521,13 @@ func (a *App) RegenerateOAuthAppSecret(app *model.OAuthApp) (*model.OAuthApp, *m } func (a *App) RevokeAccessToken(token string) *model.AppError { - if err := a.ch.srv.userService.RevokeAccessToken(token); err != nil { + if err := a.ch.srv.platform.RevokeAccessToken(token); err != nil { switch { - case errors.Is(err, users.GetTokenError): + case errors.Is(err, platform.GetTokenError): return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.get.app_error", nil, "", http.StatusBadRequest).Wrap(err) - case errors.Is(err, users.DeleteTokenError): + case errors.Is(err, platform.DeleteTokenError): return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.del_token.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - case errors.Is(err, users.DeleteSessionError): + case errors.Is(err, platform.DeleteSessionError): return model.NewAppError("RevokeAccessToken", "api.oauth.revoke_access_token.del_session.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -645,7 +645,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email map[string]any{"Service": service}, "", http.StatusBadRequest) } - user, nErr := a.Srv().Store.User().GetByEmail(email) + user, nErr := a.Srv().Store().User().GetByEmail(email) if nErr != nil { return nil, model.NewAppError("CompleteSwitchWithOAuth", MissingAccountError, nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -654,7 +654,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email return nil, err } - if _, nErr := a.Srv().Store.User().UpdateAuthData(user.Id, service, ssoUser.AuthData, ssoUser.Email, true); nErr != nil { + if _, nErr := a.Srv().Store().User().UpdateAuthData(user.Id, service, ssoUser.AuthData, ssoUser.Email, true); nErr != nil { var invErr *store.ErrInvalidInput switch { case errors.As(nErr, &invErr): @@ -676,7 +676,7 @@ func (a *App) CompleteSwitchWithOAuth(service string, userData io.Reader, email func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError) { token := model.NewToken(model.TokenTypeOAuth, extra) - if err := a.Srv().Store.Token().Save(token); err != nil { + if err := a.Srv().Store().Token().Save(token); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -690,7 +690,7 @@ func (a *App) CreateOAuthStateToken(extra string) (*model.Token, *model.AppError } func (a *App) GetOAuthStateToken(token string) (*model.Token, *model.AppError) { - mToken, err := a.Srv().Store.Token().GetByToken(token) + mToken, err := a.Srv().Store().Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetOAuthStateToken", "api.oauth.invalid_state_token.app_error", nil, "", http.StatusBadRequest).Wrap(err) } diff --git a/app/oauth_test.go b/app/oauth_test.go index 0beff5b312..48930d2dbc 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -111,7 +111,7 @@ func TestOAuthDeleteApp(t *testing.T) { session.Token = model.NewId() session.Roles = model.SystemUserRoleId session.IsOAuth = true - th.App.ch.srv.userService.SetSessionExpireInHours(session, 24) + th.App.ch.srv.platform.SetSessionExpireInHours(session, 24) session, _ = th.App.CreateSession(session) @@ -122,7 +122,7 @@ func TestOAuthDeleteApp(t *testing.T) { accessData.ClientId = a1.Id accessData.ExpiresAt = session.ExpiresAt - _, nErr := th.App.Srv().Store.OAuth().SaveAccessData(accessData) + _, nErr := th.App.Srv().Store().OAuth().SaveAccessData(accessData) require.NoError(t, nErr) err = th.App.DeleteOAuthApp(a1.Id) @@ -218,7 +218,7 @@ func TestAuthorizeOAuthUser(t *testing.T) { defer th.TearDown() token := model.NewToken("invalid", "") - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) state := makeState(token) diff --git a/app/onboarding.go b/app/onboarding.go index f73cd68d84..9a9e25739c 100644 --- a/app/onboarding.go +++ b/app/onboarding.go @@ -20,7 +20,7 @@ func (a *App) markAdminOnboardingComplete(c *request.Context) *model.AppError { Value: "true", } - if err := a.Srv().Store.System().SaveOrUpdate(&firstAdminCompleteSetupObj); err != nil { + if err := a.Srv().Store().System().SaveOrUpdate(&firstAdminCompleteSetupObj); err != nil { return model.NewAppError("setFirstAdminCompleteSetup", "api.error_set_first_admin_complete_setup", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -72,7 +72,7 @@ func (a *App) CompleteOnboarding(c *request.Context, request *model.CompleteOnbo } func (a *App) GetOnboarding() (*model.System, *model.AppError) { - firstAdminCompleteSetupObj, err := a.Srv().Store.System().GetByName(model.SystemFirstAdminSetupComplete) + firstAdminCompleteSetupObj, err := a.Srv().Store().System().GetByName(model.SystemFirstAdminSetupComplete) if err != nil { var nfErr *store.ErrNotFound switch { diff --git a/app/opentracing/opentracing_layer.go b/app/opentracing/opentracing_layer.go index 30379abfe2..6dd849aefb 100644 --- a/app/opentracing/opentracing_layer.go +++ b/app/opentracing/opentracing_layer.go @@ -19,6 +19,7 @@ import ( "time" "github.com/mattermost/mattermost-server/v6/app" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/audit" "github.com/mattermost/mattermost-server/v6/einterfaces" @@ -69,9 +70,9 @@ func (a *OpenTracingAppLayer) ActivateMfa(userID string, token string) *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ActivateMfa") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -91,9 +92,9 @@ func (a *OpenTracingAppLayer) AddChannelMember(c request.CTX, userID string, cha span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddChannelMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -113,9 +114,9 @@ func (a *OpenTracingAppLayer) AddChannelsToRetentionPolicy(policyID string, chan span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddChannelsToRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -135,9 +136,9 @@ func (a *OpenTracingAppLayer) AddConfigListener(listener func(*model.Config, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddConfigListener") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -152,9 +153,9 @@ func (a *OpenTracingAppLayer) AddCursorIdsForPostList(originalList *model.PostLi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddCursorIdsForPostList") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -167,9 +168,9 @@ func (a *OpenTracingAppLayer) AddDirectChannels(c request.CTX, teamID string, us span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddDirectChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -189,9 +190,9 @@ func (a *OpenTracingAppLayer) AddLdapPrivateCertificate(fileData *multipart.File span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddLdapPrivateCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -211,9 +212,9 @@ func (a *OpenTracingAppLayer) AddLdapPublicCertificate(fileData *multipart.FileH span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddLdapPublicCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -233,9 +234,9 @@ func (a *OpenTracingAppLayer) AddPublicKey(name string, key io.Reader) *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddPublicKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -255,9 +256,9 @@ func (a *OpenTracingAppLayer) AddRemoteCluster(rc *model.RemoteCluster) (*model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddRemoteCluster") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -277,9 +278,9 @@ func (a *OpenTracingAppLayer) AddSamlIdpCertificate(fileData *multipart.FileHead span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddSamlIdpCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -299,9 +300,9 @@ func (a *OpenTracingAppLayer) AddSamlPrivateCertificate(fileData *multipart.File span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddSamlPrivateCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -321,9 +322,9 @@ func (a *OpenTracingAppLayer) AddSamlPublicCertificate(fileData *multipart.FileH span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddSamlPublicCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -343,9 +344,9 @@ func (a *OpenTracingAppLayer) AddSessionToCache(session *model.Session) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddSessionToCache") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -353,44 +354,14 @@ func (a *OpenTracingAppLayer) AddSessionToCache(session *model.Session) { a.app.AddSessionToCache(session) } -func (a *OpenTracingAppLayer) AddStatusCache(status *model.Status) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddStatusCache") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.AddStatusCache(status) -} - -func (a *OpenTracingAppLayer) AddStatusCacheSkipClusterSend(status *model.Status) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddStatusCacheSkipClusterSend") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.AddStatusCacheSkipClusterSend(status) -} - func (a *OpenTracingAppLayer) AddTeamMember(c request.CTX, teamID string, userID string) (*model.TeamMember, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -410,9 +381,9 @@ func (a *OpenTracingAppLayer) AddTeamMemberByInviteId(c *request.Context, invite span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMemberByInviteId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -432,9 +403,9 @@ func (a *OpenTracingAppLayer) AddTeamMemberByToken(c *request.Context, userID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMemberByToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -454,9 +425,9 @@ func (a *OpenTracingAppLayer) AddTeamMembers(c *request.Context, teamID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -476,9 +447,9 @@ func (a *OpenTracingAppLayer) AddTeamsToRetentionPolicy(policyID string, teamIDs span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddTeamsToRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -498,9 +469,9 @@ func (a *OpenTracingAppLayer) AddUserToChannel(c request.CTX, user *model.User, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -520,9 +491,9 @@ func (a *OpenTracingAppLayer) AddUserToTeam(c request.CTX, teamID string, userID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -542,9 +513,9 @@ func (a *OpenTracingAppLayer) AddUserToTeamByInviteId(c *request.Context, invite span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByInviteId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -564,9 +535,9 @@ func (a *OpenTracingAppLayer) AddUserToTeamByTeamId(c *request.Context, teamID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByTeamId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -586,9 +557,9 @@ func (a *OpenTracingAppLayer) AddUserToTeamByToken(c *request.Context, userID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddUserToTeamByToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -608,9 +579,9 @@ func (a *OpenTracingAppLayer) AdjustImage(file io.Reader) (*bytes.Buffer, *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AdjustImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -630,9 +601,9 @@ func (a *OpenTracingAppLayer) AdjustInProductLimits(limits *model.ProductLimits, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AdjustInProductLimits") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -652,9 +623,9 @@ func (a *OpenTracingAppLayer) AdjustTeamsFromProductLimits(teamLimits *model.Tea span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AdjustTeamsFromProductLimits") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -674,9 +645,9 @@ func (a *OpenTracingAppLayer) AllowOAuthAppAccessToUser(userID string, authReque span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AllowOAuthAppAccessToUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -696,9 +667,9 @@ func (a *OpenTracingAppLayer) AppendFile(fr io.Reader, path string) (int64, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AppendFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -718,9 +689,9 @@ func (a *OpenTracingAppLayer) AsymmetricSigningKey() *ecdsa.PrivateKey { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AsymmetricSigningKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -735,9 +706,9 @@ func (a *OpenTracingAppLayer) AttachCloudSessionCookie(c *request.Context, w htt span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AttachCloudSessionCookie") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -750,9 +721,9 @@ func (a *OpenTracingAppLayer) AttachDeviceId(sessionID string, deviceID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AttachDeviceId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -772,9 +743,9 @@ func (a *OpenTracingAppLayer) AttachSessionCookies(c *request.Context, w http.Re span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AttachSessionCookies") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -787,9 +758,9 @@ func (a *OpenTracingAppLayer) AuthenticateUserForLogin(c *request.Context, id st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AuthenticateUserForLogin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -809,9 +780,9 @@ func (a *OpenTracingAppLayer) AuthorizeOAuthUser(w http.ResponseWriter, r *http. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AuthorizeOAuthUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -831,9 +802,9 @@ func (a *OpenTracingAppLayer) AutocompleteChannels(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -853,9 +824,9 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForSearch(c request.CTX, teamI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannelsForSearch") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -875,9 +846,9 @@ func (a *OpenTracingAppLayer) AutocompleteChannelsForTeam(c request.CTX, teamID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteChannelsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -897,9 +868,9 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInChannel(teamID string, channelI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteUsersInChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -919,9 +890,9 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInTeam(teamID string, term string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AutocompleteUsersInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -936,29 +907,14 @@ func (a *OpenTracingAppLayer) AutocompleteUsersInTeam(teamID string, term string return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) BroadcastStatus(status *model.Status) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BroadcastStatus") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.BroadcastStatus(status) -} - func (a *OpenTracingAppLayer) BuildPostReactions(ctx request.CTX, postID string) (*[]app.ReactionImportData, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BuildPostReactions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -978,9 +934,9 @@ func (a *OpenTracingAppLayer) BuildPushNotificationMessage(c request.CTX, conten span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BuildPushNotificationMessage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1000,9 +956,9 @@ func (a *OpenTracingAppLayer) BuildSamlMetadataObject(idpMetadata []byte) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BuildSamlMetadataObject") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1022,9 +978,9 @@ func (a *OpenTracingAppLayer) BulkExport(ctx request.CTX, writer io.Writer, outP span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BulkExport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1044,9 +1000,9 @@ func (a *OpenTracingAppLayer) BulkImport(c *request.Context, jsonlReader io.Read span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BulkImport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1066,9 +1022,9 @@ func (a *OpenTracingAppLayer) BulkImportWithPath(c *request.Context, jsonlReader span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.BulkImportWithPath") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1088,9 +1044,9 @@ func (a *OpenTracingAppLayer) CanNotifyAdmin(trial bool) bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CanNotifyAdmin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1105,9 +1061,9 @@ func (a *OpenTracingAppLayer) CancelJob(jobId string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CancelJob") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1127,9 +1083,9 @@ func (a *OpenTracingAppLayer) ChannelMembersMinusGroupMembers(channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ChannelMembersMinusGroupMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1149,9 +1105,9 @@ func (a *OpenTracingAppLayer) ChannelMembersToAdd(since int64, channelID *string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ChannelMembersToAdd") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1171,9 +1127,9 @@ func (a *OpenTracingAppLayer) ChannelMembersToRemove(teamID *string) ([]*model.C span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ChannelMembersToRemove") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1193,9 +1149,9 @@ func (a *OpenTracingAppLayer) Channels() *app.Channels { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Channels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1210,9 +1166,9 @@ func (a *OpenTracingAppLayer) CheckCanInviteToSharedChannel(channelId string) er span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckCanInviteToSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1232,9 +1188,9 @@ func (a *OpenTracingAppLayer) CheckForClientSideCert(r *http.Request) (string, s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckForClientSideCert") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1249,9 +1205,9 @@ func (a *OpenTracingAppLayer) CheckFreemiumLimitsForConfigSave(oldConfig *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckFreemiumLimitsForConfigSave") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1271,9 +1227,9 @@ func (a *OpenTracingAppLayer) CheckIntegrity() <-chan model.IntegrityCheckResult span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckIntegrity") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1288,9 +1244,9 @@ func (a *OpenTracingAppLayer) CheckMandatoryS3Fields(settings *model.FileSetting span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckMandatoryS3Fields") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1310,9 +1266,9 @@ func (a *OpenTracingAppLayer) CheckPasswordAndAllCriteria(user *model.User, pass span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckPasswordAndAllCriteria") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1332,9 +1288,9 @@ func (a *OpenTracingAppLayer) CheckPostReminders() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckPostReminders") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1347,9 +1303,9 @@ func (a *OpenTracingAppLayer) CheckProviderAttributes(user *model.User, patch *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckProviderAttributes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1364,9 +1320,9 @@ func (a *OpenTracingAppLayer) CheckRolesExist(roleNames []string) *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckRolesExist") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1386,9 +1342,9 @@ func (a *OpenTracingAppLayer) CheckUserAllAuthenticationCriteria(user *model.Use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckUserAllAuthenticationCriteria") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1408,9 +1364,9 @@ func (a *OpenTracingAppLayer) CheckUserMfa(user *model.User, token string) *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckUserMfa") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1430,9 +1386,9 @@ func (a *OpenTracingAppLayer) CheckUserPostflightAuthenticationCriteria(user *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckUserPostflightAuthenticationCriteria") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1452,9 +1408,9 @@ func (a *OpenTracingAppLayer) CheckUserPreflightAuthenticationCriteria(user *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckUserPreflightAuthenticationCriteria") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1469,14 +1425,14 @@ func (a *OpenTracingAppLayer) CheckUserPreflightAuthenticationCriteria(user *mod return resultVar0 } -func (a *OpenTracingAppLayer) CheckWebConn(userID string, connectionID string) *app.CheckConnResult { +func (a *OpenTracingAppLayer) CheckWebConn(userID string, connectionID string) *platform.CheckConnResult { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CheckWebConn") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1491,9 +1447,9 @@ func (a *OpenTracingAppLayer) ClearChannelMembersCache(c request.CTX, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearChannelMembersCache") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1513,9 +1469,9 @@ func (a *OpenTracingAppLayer) ClearLatestVersionCache() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearLatestVersionCache") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1528,9 +1484,9 @@ func (a *OpenTracingAppLayer) ClearSessionCacheForAllUsers() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearSessionCacheForAllUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1543,9 +1499,9 @@ func (a *OpenTracingAppLayer) ClearSessionCacheForAllUsersSkipClusterSend() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearSessionCacheForAllUsersSkipClusterSend") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1558,9 +1514,9 @@ func (a *OpenTracingAppLayer) ClearSessionCacheForUser(userID string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearSessionCacheForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1573,9 +1529,9 @@ func (a *OpenTracingAppLayer) ClearSessionCacheForUserSkipClusterSend(userID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearSessionCacheForUserSkipClusterSend") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1588,9 +1544,9 @@ func (a *OpenTracingAppLayer) ClearTeamMembersCache(teamID string) error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClearTeamMembersCache") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1610,9 +1566,9 @@ func (a *OpenTracingAppLayer) ClientConfig() map[string]string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClientConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1627,9 +1583,9 @@ func (a *OpenTracingAppLayer) ClientConfigHash() string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClientConfigHash") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1639,31 +1595,14 @@ func (a *OpenTracingAppLayer) ClientConfigHash() string { return resultVar0 } -func (a *OpenTracingAppLayer) ClientConfigWithComputed() map[string]string { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClientConfigWithComputed") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.ClientConfigWithComputed() - - return resultVar0 -} - func (a *OpenTracingAppLayer) Cloud() einterfaces.CloudInterface { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Cloud") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1678,9 +1617,9 @@ func (a *OpenTracingAppLayer) CompareAndDeletePluginKey(pluginID string, key str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompareAndDeletePluginKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1700,9 +1639,9 @@ func (a *OpenTracingAppLayer) CompareAndSetPluginKey(pluginID string, key string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompareAndSetPluginKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1722,9 +1661,9 @@ func (a *OpenTracingAppLayer) CompleteOAuth(c *request.Context, service string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompleteOAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1744,9 +1683,9 @@ func (a *OpenTracingAppLayer) CompleteOnboarding(c *request.Context, request *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompleteOnboarding") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1766,9 +1705,9 @@ func (a *OpenTracingAppLayer) CompleteSwitchWithOAuth(service string, userData i span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompleteSwitchWithOAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1788,9 +1727,9 @@ func (a *OpenTracingAppLayer) ComputeLastAccessibleFileTime() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ComputeLastAccessibleFileTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1810,9 +1749,9 @@ func (a *OpenTracingAppLayer) ComputeLastAccessiblePostTime() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ComputeLastAccessiblePostTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1832,9 +1771,9 @@ func (a *OpenTracingAppLayer) Config() *model.Config { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Config") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1849,9 +1788,9 @@ func (a *OpenTracingAppLayer) ConvertBotToUser(c request.CTX, bot *model.Bot, us span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ConvertBotToUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1871,9 +1810,9 @@ func (a *OpenTracingAppLayer) ConvertUserToBot(user *model.User) (*model.Bot, *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ConvertUserToBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1893,9 +1832,9 @@ func (a *OpenTracingAppLayer) CopyFileInfos(userID string, fileIDs []string) ([] span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CopyFileInfos") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1915,9 +1854,9 @@ func (a *OpenTracingAppLayer) CreateBot(c request.CTX, bot *model.Bot) (*model.B span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1937,9 +1876,9 @@ func (a *OpenTracingAppLayer) CreateChannel(c request.CTX, channel *model.Channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1959,9 +1898,9 @@ func (a *OpenTracingAppLayer) CreateChannelScheme(c request.CTX, channel *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannelScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -1981,9 +1920,9 @@ func (a *OpenTracingAppLayer) CreateChannelWithUser(c request.CTX, channel *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateChannelWithUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2003,9 +1942,9 @@ func (a *OpenTracingAppLayer) CreateCommand(cmd *model.Command) (*model.Command, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2025,9 +1964,9 @@ func (a *OpenTracingAppLayer) CreateCommandPost(c request.CTX, post *model.Post, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateCommandPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2051,9 +1990,9 @@ func (a *OpenTracingAppLayer) CreateCommandWebhook(commandID string, args *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateCommandWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2073,9 +2012,9 @@ func (a *OpenTracingAppLayer) CreateDefaultMemberships(c *request.Context, since span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateDefaultMemberships") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2095,9 +2034,9 @@ func (a *OpenTracingAppLayer) CreateEmoji(sessionUserId string, emoji *model.Emo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateEmoji") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2117,9 +2056,9 @@ func (a *OpenTracingAppLayer) CreateGroup(group *model.Group) (*model.Group, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2139,9 +2078,9 @@ func (a *OpenTracingAppLayer) CreateGroupChannel(c request.CTX, userIDs []string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGroupChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2161,9 +2100,9 @@ func (a *OpenTracingAppLayer) CreateGroupWithUserIds(group *model.GroupWithUserI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGroupWithUserIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2183,9 +2122,9 @@ func (a *OpenTracingAppLayer) CreateGuest(c request.CTX, user *model.User) (*mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateGuest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2205,9 +2144,9 @@ func (a *OpenTracingAppLayer) CreateIncomingWebhookForChannel(creatorId string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateIncomingWebhookForChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2227,9 +2166,9 @@ func (a *OpenTracingAppLayer) CreateJob(job *model.Job) (*model.Job, *model.AppE span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateJob") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2249,9 +2188,9 @@ func (a *OpenTracingAppLayer) CreateOAuthApp(app *model.OAuthApp) (*model.OAuthA span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateOAuthApp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2271,9 +2210,9 @@ func (a *OpenTracingAppLayer) CreateOAuthStateToken(extra string) (*model.Token, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateOAuthStateToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2293,9 +2232,9 @@ func (a *OpenTracingAppLayer) CreateOAuthUser(c *request.Context, service string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateOAuthUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2315,9 +2254,9 @@ func (a *OpenTracingAppLayer) CreateOutgoingWebhook(hook *model.OutgoingWebhook) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateOutgoingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2337,9 +2276,9 @@ func (a *OpenTracingAppLayer) CreatePasswordRecoveryToken(userID string, email s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePasswordRecoveryToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2359,9 +2298,9 @@ func (a *OpenTracingAppLayer) CreatePost(c request.CTX, post *model.Post, channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2381,9 +2320,9 @@ func (a *OpenTracingAppLayer) CreatePostAsUser(c request.CTX, post *model.Post, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePostAsUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2403,9 +2342,9 @@ func (a *OpenTracingAppLayer) CreatePostMissingChannel(c request.CTX, post *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreatePostMissingChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2425,9 +2364,9 @@ func (a *OpenTracingAppLayer) CreateRetentionPolicy(policy *model.RetentionPolic span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2447,9 +2386,9 @@ func (a *OpenTracingAppLayer) CreateRole(role *model.Role) (*model.Role, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateRole") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2469,9 +2408,9 @@ func (a *OpenTracingAppLayer) CreateScheme(scheme *model.Scheme) (*model.Scheme, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2491,9 +2430,9 @@ func (a *OpenTracingAppLayer) CreateSession(session *model.Session) (*model.Sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2513,9 +2452,9 @@ func (a *OpenTracingAppLayer) CreateSidebarCategory(c request.CTX, userID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateSidebarCategory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2535,9 +2474,9 @@ func (a *OpenTracingAppLayer) CreateTeam(c request.CTX, team *model.Team) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2557,9 +2496,9 @@ func (a *OpenTracingAppLayer) CreateTeamWithUser(c *request.Context, team *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateTeamWithUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2579,9 +2518,9 @@ func (a *OpenTracingAppLayer) CreateTermsOfService(text string, userID string) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateTermsOfService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2601,9 +2540,9 @@ func (a *OpenTracingAppLayer) CreateUploadSession(c request.CTX, us *model.Uploa span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUploadSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2623,9 +2562,9 @@ func (a *OpenTracingAppLayer) CreateUser(c request.CTX, user *model.User) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2645,9 +2584,9 @@ func (a *OpenTracingAppLayer) CreateUserAccessToken(token *model.UserAccessToken span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2667,9 +2606,9 @@ func (a *OpenTracingAppLayer) CreateUserAsAdmin(c request.CTX, user *model.User, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserAsAdmin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2689,9 +2628,9 @@ func (a *OpenTracingAppLayer) CreateUserFromSignup(c request.CTX, user *model.Us span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserFromSignup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2711,9 +2650,9 @@ func (a *OpenTracingAppLayer) CreateUserWithInviteId(c request.CTX, user *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserWithInviteId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2733,9 +2672,9 @@ func (a *OpenTracingAppLayer) CreateUserWithToken(c request.CTX, user *model.Use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateUserWithToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2755,9 +2694,9 @@ func (a *OpenTracingAppLayer) CreateWebhookPost(c request.CTX, userID string, ch span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateWebhookPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2777,9 +2716,9 @@ func (a *OpenTracingAppLayer) CreateZipFileAndAddFiles(fileBackend filestore.Fil span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CreateZipFileAndAddFiles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2799,9 +2738,9 @@ func (a *OpenTracingAppLayer) DBHealthCheckDelete() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DBHealthCheckDelete") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2821,9 +2760,9 @@ func (a *OpenTracingAppLayer) DBHealthCheckWrite() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DBHealthCheckWrite") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2843,9 +2782,9 @@ func (a *OpenTracingAppLayer) DeactivateGuests(c *request.Context) *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeactivateGuests") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2865,9 +2804,9 @@ func (a *OpenTracingAppLayer) DeactivateMfa(userID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeactivateMfa") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2887,9 +2826,9 @@ func (a *OpenTracingAppLayer) DeauthorizeOAuthAppForUser(userID string, appID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeauthorizeOAuthAppForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2909,9 +2848,9 @@ func (a *OpenTracingAppLayer) DefaultChannelNames(c request.CTX) []string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DefaultChannelNames") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2926,9 +2865,9 @@ func (a *OpenTracingAppLayer) DeleteAllExpiredPluginKeys() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteAllExpiredPluginKeys") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2948,9 +2887,9 @@ func (a *OpenTracingAppLayer) DeleteAllKeysForPlugin(pluginID string) *model.App span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteAllKeysForPlugin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2970,9 +2909,9 @@ func (a *OpenTracingAppLayer) DeleteBrandImage() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteBrandImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -2992,9 +2931,9 @@ func (a *OpenTracingAppLayer) DeleteChannel(c request.CTX, channel *model.Channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3014,9 +2953,9 @@ func (a *OpenTracingAppLayer) DeleteChannelScheme(c request.CTX, channel *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteChannelScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3036,9 +2975,9 @@ func (a *OpenTracingAppLayer) DeleteCommand(commandID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3058,9 +2997,9 @@ func (a *OpenTracingAppLayer) DeleteEmoji(emoji *model.Emoji) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteEmoji") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3080,9 +3019,9 @@ func (a *OpenTracingAppLayer) DeleteEphemeralPost(userID string, postID string) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteEphemeralPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3095,9 +3034,9 @@ func (a *OpenTracingAppLayer) DeleteExport(name string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteExport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3117,9 +3056,9 @@ func (a *OpenTracingAppLayer) DeleteGroup(groupID string) (*model.Group, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3139,9 +3078,9 @@ func (a *OpenTracingAppLayer) DeleteGroupConstrainedMemberships(c *request.Conte span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroupConstrainedMemberships") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3161,9 +3100,9 @@ func (a *OpenTracingAppLayer) DeleteGroupMember(groupID string, userID string) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroupMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3183,9 +3122,9 @@ func (a *OpenTracingAppLayer) DeleteGroupMembers(groupID string, userIDs []strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroupMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3205,9 +3144,9 @@ func (a *OpenTracingAppLayer) DeleteGroupSyncable(groupID string, syncableID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteGroupSyncable") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3227,9 +3166,9 @@ func (a *OpenTracingAppLayer) DeleteIncomingWebhook(hookID string) *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteIncomingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3249,9 +3188,9 @@ func (a *OpenTracingAppLayer) DeleteOAuthApp(appID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteOAuthApp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3271,9 +3210,9 @@ func (a *OpenTracingAppLayer) DeleteOutgoingWebhook(hookID string) *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteOutgoingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3293,9 +3232,9 @@ func (a *OpenTracingAppLayer) DeletePluginKey(pluginID string, key string) *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeletePluginKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3315,9 +3254,9 @@ func (a *OpenTracingAppLayer) DeletePost(c request.CTX, postID string, deleteByI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeletePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3337,9 +3276,9 @@ func (a *OpenTracingAppLayer) DeletePreferences(userID string, preferences model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeletePreferences") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3359,9 +3298,9 @@ func (a *OpenTracingAppLayer) DeletePublicKey(name string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeletePublicKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3381,9 +3320,9 @@ func (a *OpenTracingAppLayer) DeleteReactionForPost(c *request.Context, reaction span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteReactionForPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3403,9 +3342,9 @@ func (a *OpenTracingAppLayer) DeleteRemoteCluster(remoteClusterId string) (bool, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteRemoteCluster") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3425,9 +3364,9 @@ func (a *OpenTracingAppLayer) DeleteRetentionPolicy(policyID string) *model.AppE span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3447,9 +3386,9 @@ func (a *OpenTracingAppLayer) DeleteScheme(schemeId string) (*model.Scheme, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3469,9 +3408,9 @@ func (a *OpenTracingAppLayer) DeleteSharedChannel(channelID string) (bool, error span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3491,9 +3430,9 @@ func (a *OpenTracingAppLayer) DeleteSharedChannelRemote(id string) (bool, error) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteSharedChannelRemote") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3513,9 +3452,9 @@ func (a *OpenTracingAppLayer) DeleteSidebarCategory(c request.CTX, userID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteSidebarCategory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3535,9 +3474,9 @@ func (a *OpenTracingAppLayer) DeleteToken(token *model.Token) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3557,9 +3496,9 @@ func (a *OpenTracingAppLayer) DemoteUserToGuest(c request.CTX, user *model.User) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DemoteUserToGuest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3579,9 +3518,9 @@ func (a *OpenTracingAppLayer) DisableAutoResponder(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DisableAutoResponder") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3601,9 +3540,9 @@ func (a *OpenTracingAppLayer) DisablePlugin(id string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DisablePlugin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3623,9 +3562,9 @@ func (a *OpenTracingAppLayer) DisableUserAccessToken(token *model.UserAccessToke span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DisableUserAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3645,9 +3584,9 @@ func (a *OpenTracingAppLayer) DoActionRequest(c *request.Context, rawURL string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoActionRequest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3667,9 +3606,9 @@ func (a *OpenTracingAppLayer) DoAdvancedPermissionsMigration() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoAdvancedPermissionsMigration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3682,9 +3621,9 @@ func (a *OpenTracingAppLayer) DoAppMigrations() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoAppMigrations") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3697,9 +3636,9 @@ func (a *OpenTracingAppLayer) DoCheckForAdminNotifications(trial bool) *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoCheckForAdminNotifications") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3719,9 +3658,9 @@ func (a *OpenTracingAppLayer) DoCommandRequest(cmd *model.Command, p url.Values) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoCommandRequest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3741,9 +3680,9 @@ func (a *OpenTracingAppLayer) DoEmojisPermissionsMigration() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoEmojisPermissionsMigration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3756,9 +3695,9 @@ func (a *OpenTracingAppLayer) DoGuestRolesCreationMigration() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoGuestRolesCreationMigration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3771,9 +3710,9 @@ func (a *OpenTracingAppLayer) DoLocalRequest(c *request.Context, rawURL string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoLocalRequest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3793,9 +3732,9 @@ func (a *OpenTracingAppLayer) DoLogin(c *request.Context, w http.ResponseWriter, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoLogin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3815,9 +3754,9 @@ func (a *OpenTracingAppLayer) DoPermissionsMigrations() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoPermissionsMigrations") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3837,9 +3776,9 @@ func (a *OpenTracingAppLayer) DoPostAction(c *request.Context, postID string, ac span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoPostAction") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3859,9 +3798,9 @@ func (a *OpenTracingAppLayer) DoPostActionWithCookie(c *request.Context, postID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoPostActionWithCookie") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3881,9 +3820,9 @@ func (a *OpenTracingAppLayer) DoSystemConsoleRolesCreationMigration() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoSystemConsoleRolesCreationMigration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3896,9 +3835,9 @@ func (a *OpenTracingAppLayer) DoUploadFile(c request.CTX, now time.Time, rawTeam span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoUploadFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3918,9 +3857,9 @@ func (a *OpenTracingAppLayer) DoUploadFileExpectModification(c request.CTX, now span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoUploadFileExpectModification") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3940,9 +3879,9 @@ func (a *OpenTracingAppLayer) DoubleCheckPassword(user *model.User, password str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DoubleCheckPassword") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3962,9 +3901,9 @@ func (a *OpenTracingAppLayer) DownloadFromURL(downloadURL string) ([]byte, error span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DownloadFromURL") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -3984,9 +3923,9 @@ func (a *OpenTracingAppLayer) EnablePlugin(id string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnablePlugin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4006,9 +3945,9 @@ func (a *OpenTracingAppLayer) EnableUserAccessToken(token *model.UserAccessToken span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnableUserAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4028,9 +3967,9 @@ func (a *OpenTracingAppLayer) EnsureBot(c request.CTX, productID string, bot *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnsureBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4050,9 +3989,9 @@ func (a *OpenTracingAppLayer) EnvironmentConfig(filter func(reflect.StructField) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.EnvironmentConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4067,9 +4006,9 @@ func (a *OpenTracingAppLayer) ExecuteCommand(c request.CTX, args *model.CommandA span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExecuteCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4091,9 +4030,9 @@ func (a *OpenTracingAppLayer) ExportPermissions(w io.Writer) error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExportPermissions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4113,9 +4052,9 @@ func (a *OpenTracingAppLayer) ExtendSessionExpiryIfNeeded(session *model.Session span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExtendSessionExpiryIfNeeded") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4130,9 +4069,9 @@ func (a *OpenTracingAppLayer) ExtractContentFromFileInfo(fileInfo *model.FileInf span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ExtractContentFromFileInfo") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4152,9 +4091,9 @@ func (a *OpenTracingAppLayer) FetchSamlMetadataFromIdp(url string) ([]byte, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FetchSamlMetadataFromIdp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4174,9 +4113,9 @@ func (a *OpenTracingAppLayer) FileBackend() filestore.FileBackend { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FileBackend") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4191,9 +4130,9 @@ func (a *OpenTracingAppLayer) FileExists(path string) (bool, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FileExists") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4213,9 +4152,9 @@ func (a *OpenTracingAppLayer) FileModTime(path string) (time.Time, *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FileModTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4235,9 +4174,9 @@ func (a *OpenTracingAppLayer) FileReader(path string) (filestore.ReadCloseSeeker span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FileReader") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4257,9 +4196,9 @@ func (a *OpenTracingAppLayer) FileSize(path string) (int64, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FileSize") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4279,9 +4218,9 @@ func (a *OpenTracingAppLayer) FillInChannelProps(c request.CTX, channel *model.C span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInChannelProps") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4301,9 +4240,9 @@ func (a *OpenTracingAppLayer) FillInChannelsProps(c request.CTX, channelList mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInChannelsProps") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4323,9 +4262,9 @@ func (a *OpenTracingAppLayer) FillInPostProps(c request.CTX, post *model.Post, c span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FillInPostProps") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4345,9 +4284,9 @@ func (a *OpenTracingAppLayer) FilterNonGroupChannelMembers(userIDs []string, cha span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FilterNonGroupChannelMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4367,9 +4306,9 @@ func (a *OpenTracingAppLayer) FilterNonGroupTeamMembers(userIDs []string, team * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FilterNonGroupTeamMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4389,9 +4328,9 @@ func (a *OpenTracingAppLayer) FilterUsersByVisible(viewer *model.User, otherUser span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FilterUsersByVisible") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4411,9 +4350,9 @@ func (a *OpenTracingAppLayer) FindTeamByName(name string) bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FindTeamByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4428,9 +4367,9 @@ func (a *OpenTracingAppLayer) FinishSendAdminNotifyPost(trial bool, now int64) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.FinishSendAdminNotifyPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4443,9 +4382,9 @@ func (a *OpenTracingAppLayer) GenerateMfaSecret(userID string) (*model.MfaSecret span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GenerateMfaSecret") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4465,9 +4404,9 @@ func (a *OpenTracingAppLayer) GeneratePublicLink(siteURL string, info *model.Fil span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GeneratePublicLink") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4482,9 +4421,9 @@ func (a *OpenTracingAppLayer) GenerateSupportPacket() []model.FileData { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GenerateSupportPacket") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4499,9 +4438,9 @@ func (a *OpenTracingAppLayer) GetActivePluginManifests() ([]*model.Manifest, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetActivePluginManifests") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4521,9 +4460,9 @@ func (a *OpenTracingAppLayer) GetAllChannels(c request.CTX, page int, perPage in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4543,9 +4482,9 @@ func (a *OpenTracingAppLayer) GetAllChannelsCount(c request.CTX, opts model.Chan span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllChannelsCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4565,9 +4504,9 @@ func (a *OpenTracingAppLayer) GetAllLdapGroupsPage(page int, perPage int, opts m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllLdapGroupsPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4587,9 +4526,9 @@ func (a *OpenTracingAppLayer) GetAllPrivateTeams() ([]*model.Team, *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllPrivateTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4609,9 +4548,9 @@ func (a *OpenTracingAppLayer) GetAllPublicTeams() ([]*model.Team, *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllPublicTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4631,9 +4570,9 @@ func (a *OpenTracingAppLayer) GetAllRemoteClusters(filter model.RemoteClusterQue span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllRemoteClusters") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4653,9 +4592,9 @@ func (a *OpenTracingAppLayer) GetAllRoles() ([]*model.Role, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4670,31 +4609,14 @@ func (a *OpenTracingAppLayer) GetAllRoles() ([]*model.Role, *model.AppError) { return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetAllStatuses() map[string]*model.Status { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllStatuses") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.GetAllStatuses() - - return resultVar0 -} - func (a *OpenTracingAppLayer) GetAllTeams() ([]*model.Team, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4714,9 +4636,9 @@ func (a *OpenTracingAppLayer) GetAllTeamsPage(offset int, limit int, opts *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllTeamsPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4736,9 +4658,9 @@ func (a *OpenTracingAppLayer) GetAllTeamsPageWithCount(offset int, limit int, op span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAllTeamsPageWithCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4758,9 +4680,9 @@ func (a *OpenTracingAppLayer) GetAnalytics(name string, teamID string) (model.An span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAnalytics") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4780,9 +4702,9 @@ func (a *OpenTracingAppLayer) GetAppliedSchemaMigrations() ([]model.AppliedMigra span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAppliedSchemaMigrations") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4802,9 +4724,9 @@ func (a *OpenTracingAppLayer) GetAudits(userID string, limit int) (model.Audits, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAudits") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4824,9 +4746,9 @@ func (a *OpenTracingAppLayer) GetAuditsPage(userID string, page int, perPage int span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAuditsPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4846,9 +4768,9 @@ func (a *OpenTracingAppLayer) GetAuthorizationCode(w http.ResponseWriter, r *htt span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAuthorizationCode") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4868,9 +4790,9 @@ func (a *OpenTracingAppLayer) GetAuthorizedAppsForUser(userID string, page int, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetAuthorizedAppsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4890,9 +4812,9 @@ func (a *OpenTracingAppLayer) GetBot(botUserId string, includeDeleted bool) (*mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4912,9 +4834,9 @@ func (a *OpenTracingAppLayer) GetBots(options *model.BotGetOptions) (model.BotLi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetBots") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4934,9 +4856,9 @@ func (a *OpenTracingAppLayer) GetBrandImage() ([]byte, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetBrandImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4956,9 +4878,9 @@ func (a *OpenTracingAppLayer) GetBulkReactionsForPosts(postIDs []string) (map[st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetBulkReactionsForPosts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -4978,9 +4900,9 @@ func (a *OpenTracingAppLayer) GetChannel(c request.CTX, channelID string) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5000,9 +4922,9 @@ func (a *OpenTracingAppLayer) GetChannelByName(c request.CTX, channelName string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5022,9 +4944,9 @@ func (a *OpenTracingAppLayer) GetChannelByNameForTeamName(c request.CTX, channel span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelByNameForTeamName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5044,9 +4966,9 @@ func (a *OpenTracingAppLayer) GetChannelCounts(c request.CTX, teamID string, use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelCounts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5066,9 +4988,9 @@ func (a *OpenTracingAppLayer) GetChannelFileCount(c request.CTX, channelID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelFileCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5088,9 +5010,9 @@ func (a *OpenTracingAppLayer) GetChannelGroupUsers(channelID string) ([]*model.U span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelGroupUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5110,9 +5032,9 @@ func (a *OpenTracingAppLayer) GetChannelGuestCount(c request.CTX, channelID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelGuestCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5132,9 +5054,9 @@ func (a *OpenTracingAppLayer) GetChannelMember(c request.CTX, channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5154,9 +5076,9 @@ func (a *OpenTracingAppLayer) GetChannelMemberCount(c request.CTX, channelID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMemberCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5176,9 +5098,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersByIds(c request.CTX, channelID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5198,9 +5120,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUser(c request.CTX, teamID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5220,9 +5142,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersForUserWithPagination(c request.C span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersForUserWithPagination") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5242,9 +5164,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersPage(c request.CTX, channelID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5264,9 +5186,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersTimezones(c request.CTX, channelI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersTimezones") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5286,9 +5208,9 @@ func (a *OpenTracingAppLayer) GetChannelMembersWithTeamDataForUserWithPagination span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelMembersWithTeamDataForUserWithPagination") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5308,9 +5230,9 @@ func (a *OpenTracingAppLayer) GetChannelModerationsForChannel(c request.CTX, cha span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelModerationsForChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5330,9 +5252,9 @@ func (a *OpenTracingAppLayer) GetChannelPinnedPostCount(c request.CTX, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelPinnedPostCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5352,9 +5274,9 @@ func (a *OpenTracingAppLayer) GetChannelPoliciesForUser(userID string, offset in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelPoliciesForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5374,9 +5296,9 @@ func (a *OpenTracingAppLayer) GetChannelUnread(c request.CTX, channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelUnread") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5396,9 +5318,9 @@ func (a *OpenTracingAppLayer) GetChannels(c request.CTX, channelIDs []string) ([ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5418,9 +5340,9 @@ func (a *OpenTracingAppLayer) GetChannelsByNames(c request.CTX, channelNames []s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsByNames") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5440,9 +5362,9 @@ func (a *OpenTracingAppLayer) GetChannelsForRetentionPolicy(policyID string, off span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5462,9 +5384,9 @@ func (a *OpenTracingAppLayer) GetChannelsForScheme(scheme *model.Scheme, offset span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5484,9 +5406,9 @@ func (a *OpenTracingAppLayer) GetChannelsForSchemePage(scheme *model.Scheme, pag span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForSchemePage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5506,9 +5428,9 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUser(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForTeamForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5528,9 +5450,9 @@ func (a *OpenTracingAppLayer) GetChannelsForTeamForUserWithCursor(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForTeamForUserWithCursor") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5550,9 +5472,9 @@ func (a *OpenTracingAppLayer) GetChannelsForUser(c request.CTX, userID string, i span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5572,9 +5494,9 @@ func (a *OpenTracingAppLayer) GetChannelsUserNotIn(c request.CTX, teamID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetChannelsUserNotIn") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5594,9 +5516,9 @@ func (a *OpenTracingAppLayer) GetCloudSession(token string) (*model.Session, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetCloudSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5616,9 +5538,9 @@ func (a *OpenTracingAppLayer) GetClusterId() string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetClusterId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5633,9 +5555,9 @@ func (a *OpenTracingAppLayer) GetClusterPluginStatuses() (model.PluginStatuses, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetClusterPluginStatuses") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5655,9 +5577,9 @@ func (a *OpenTracingAppLayer) GetClusterStatus() []*model.ClusterInfo { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetClusterStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5672,9 +5594,9 @@ func (a *OpenTracingAppLayer) GetCommand(commandID string) (*model.Command, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5694,9 +5616,9 @@ func (a *OpenTracingAppLayer) GetCommonTeamIDsForTwoUsers(userID string, otherUs span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetCommonTeamIDsForTwoUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5716,9 +5638,9 @@ func (a *OpenTracingAppLayer) GetComplianceFile(job *model.Compliance) ([]byte, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetComplianceFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5738,9 +5660,9 @@ func (a *OpenTracingAppLayer) GetComplianceReport(reportId string) (*model.Compl span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetComplianceReport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5760,9 +5682,9 @@ func (a *OpenTracingAppLayer) GetComplianceReports(page int, perPage int) (model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetComplianceReports") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5782,9 +5704,9 @@ func (a *OpenTracingAppLayer) GetConfigFile(name string) ([]byte, error) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetConfigFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5804,9 +5726,9 @@ func (a *OpenTracingAppLayer) GetCookieDomain() string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetCookieDomain") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5821,9 +5743,9 @@ func (a *OpenTracingAppLayer) GetCustomStatus(userID string) (*model.CustomStatu span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetCustomStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5843,9 +5765,9 @@ func (a *OpenTracingAppLayer) GetDefaultProfileImage(user *model.User) ([]byte, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetDefaultProfileImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5865,9 +5787,9 @@ func (a *OpenTracingAppLayer) GetDeletedChannels(c request.CTX, teamID string, o span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetDeletedChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5887,9 +5809,9 @@ func (a *OpenTracingAppLayer) GetEmoji(emojiId string) (*model.Emoji, *model.App span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmoji") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5909,9 +5831,9 @@ func (a *OpenTracingAppLayer) GetEmojiByName(emojiName string) (*model.Emoji, *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5931,9 +5853,9 @@ func (a *OpenTracingAppLayer) GetEmojiImage(emojiId string) ([]byte, string, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5953,9 +5875,9 @@ func (a *OpenTracingAppLayer) GetEmojiList(page int, perPage int, sort string) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiList") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5975,9 +5897,9 @@ func (a *OpenTracingAppLayer) GetEmojiStaticURL(emojiName string) (string, *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEmojiStaticURL") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -5997,9 +5919,9 @@ func (a *OpenTracingAppLayer) GetEnvironmentConfig(filter func(reflect.StructFie span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetEnvironmentConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6014,9 +5936,9 @@ func (a *OpenTracingAppLayer) GetFile(fileID string) ([]byte, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6036,9 +5958,9 @@ func (a *OpenTracingAppLayer) GetFileInfo(fileID string) (*model.FileInfo, *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFileInfo") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6058,9 +5980,9 @@ func (a *OpenTracingAppLayer) GetFileInfos(page int, perPage int, opt *model.Get span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFileInfos") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6080,9 +6002,9 @@ func (a *OpenTracingAppLayer) GetFileInfosForPost(postID string, fromMaster bool span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFileInfosForPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6102,9 +6024,9 @@ func (a *OpenTracingAppLayer) GetFileInfosForPostWithMigration(postID string, in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFileInfosForPostWithMigration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6124,9 +6046,9 @@ func (a *OpenTracingAppLayer) GetFilteredUsersStats(options *model.UserCountOpti span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFilteredUsersStats") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6146,9 +6068,9 @@ func (a *OpenTracingAppLayer) GetFlaggedPosts(userID string, offset int, limit i span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFlaggedPosts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6168,9 +6090,9 @@ func (a *OpenTracingAppLayer) GetFlaggedPostsForChannel(userID string, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFlaggedPostsForChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6190,9 +6112,9 @@ func (a *OpenTracingAppLayer) GetFlaggedPostsForTeam(userID string, teamID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetFlaggedPostsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6212,9 +6134,9 @@ func (a *OpenTracingAppLayer) GetGlobalRetentionPolicy() (*model.GlobalRetention span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGlobalRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6234,9 +6156,9 @@ func (a *OpenTracingAppLayer) GetGroup(id string, opts *model.GetGroupOpts) (*mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6256,9 +6178,9 @@ func (a *OpenTracingAppLayer) GetGroupByName(name string, opts model.GroupSearch span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6278,9 +6200,9 @@ func (a *OpenTracingAppLayer) GetGroupByRemoteID(remoteID string, groupSource mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupByRemoteID") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6300,9 +6222,9 @@ func (a *OpenTracingAppLayer) GetGroupChannel(c request.CTX, userIDs []string) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6322,9 +6244,9 @@ func (a *OpenTracingAppLayer) GetGroupMemberCount(groupID string) (int64, *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupMemberCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6344,9 +6266,9 @@ func (a *OpenTracingAppLayer) GetGroupMemberUsers(groupID string) ([]*model.User span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupMemberUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6366,9 +6288,9 @@ func (a *OpenTracingAppLayer) GetGroupMemberUsersPage(groupID string, page int, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupMemberUsersPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6388,9 +6310,9 @@ func (a *OpenTracingAppLayer) GetGroupSyncable(groupID string, syncableID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupSyncable") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6410,9 +6332,9 @@ func (a *OpenTracingAppLayer) GetGroupSyncables(groupID string, syncableType mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupSyncables") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6432,9 +6354,9 @@ func (a *OpenTracingAppLayer) GetGroups(page int, perPage int, opts model.GroupS span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroups") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6454,9 +6376,9 @@ func (a *OpenTracingAppLayer) GetGroupsAssociatedToChannelsByTeam(teamID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsAssociatedToChannelsByTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6476,9 +6398,9 @@ func (a *OpenTracingAppLayer) GetGroupsByChannel(channelID string, opts model.Gr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsByChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6498,9 +6420,9 @@ func (a *OpenTracingAppLayer) GetGroupsByIDs(groupIDs []string) ([]*model.Group, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsByIDs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6520,9 +6442,9 @@ func (a *OpenTracingAppLayer) GetGroupsBySource(groupSource model.GroupSource) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsBySource") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6542,9 +6464,9 @@ func (a *OpenTracingAppLayer) GetGroupsByTeam(teamID string, opts model.GroupSea span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsByTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6564,9 +6486,9 @@ func (a *OpenTracingAppLayer) GetGroupsByUserId(userID string) ([]*model.Group, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetGroupsByUserId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6581,14 +6503,14 @@ func (a *OpenTracingAppLayer) GetGroupsByUserId(userID string) ([]*model.Group, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) GetHubForUserId(userID string) *app.Hub { +func (a *OpenTracingAppLayer) GetHubForUserId(userID string) *platform.Hub { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetHubForUserId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6603,9 +6525,9 @@ func (a *OpenTracingAppLayer) GetIncomingWebhook(hookID string) (*model.Incoming span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIncomingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6625,9 +6547,9 @@ func (a *OpenTracingAppLayer) GetIncomingWebhooksForTeamPage(teamID string, page span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIncomingWebhooksForTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6647,9 +6569,9 @@ func (a *OpenTracingAppLayer) GetIncomingWebhooksForTeamPageByUser(teamID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIncomingWebhooksForTeamPageByUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6669,9 +6591,9 @@ func (a *OpenTracingAppLayer) GetIncomingWebhooksPage(page int, perPage int) ([] span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIncomingWebhooksPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6691,9 +6613,9 @@ func (a *OpenTracingAppLayer) GetIncomingWebhooksPageByUser(userID string, page span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIncomingWebhooksPageByUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6713,9 +6635,9 @@ func (a *OpenTracingAppLayer) GetIntegrationsUsage() (*model.IntegrationsUsage, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetIntegrationsUsage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6735,9 +6657,9 @@ func (a *OpenTracingAppLayer) GetJob(id string) (*model.Job, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJob") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6757,9 +6679,9 @@ func (a *OpenTracingAppLayer) GetJobs(offset int, limit int) ([]*model.Job, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6779,9 +6701,9 @@ func (a *OpenTracingAppLayer) GetJobsByType(jobType string, offset int, limit in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobsByType") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6801,9 +6723,9 @@ func (a *OpenTracingAppLayer) GetJobsByTypePage(jobType string, page int, perPag span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobsByTypePage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6823,9 +6745,9 @@ func (a *OpenTracingAppLayer) GetJobsByTypes(jobTypes []string, offset int, limi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobsByTypes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6845,9 +6767,9 @@ func (a *OpenTracingAppLayer) GetJobsByTypesPage(jobType []string, page int, per span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobsByTypesPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6867,9 +6789,9 @@ func (a *OpenTracingAppLayer) GetJobsPage(page int, perPage int) ([]*model.Job, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetJobsPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6889,9 +6811,9 @@ func (a *OpenTracingAppLayer) GetKnownUsers(userID string) ([]string, *model.App span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetKnownUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6911,9 +6833,9 @@ func (a *OpenTracingAppLayer) GetLastAccessibleFileTime() (int64, *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLastAccessibleFileTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6933,9 +6855,9 @@ func (a *OpenTracingAppLayer) GetLastAccessiblePostTime() (int64, *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLastAccessiblePostTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6955,9 +6877,9 @@ func (a *OpenTracingAppLayer) GetLatestTermsOfService() (*model.TermsOfService, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLatestTermsOfService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6977,9 +6899,9 @@ func (a *OpenTracingAppLayer) GetLatestVersion(latestVersionUrl string) (*model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLatestVersion") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -6999,9 +6921,9 @@ func (a *OpenTracingAppLayer) GetLdapGroup(ldapGroupID string) (*model.Group, *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLdapGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7021,9 +6943,9 @@ func (a *OpenTracingAppLayer) GetLogs(page int, perPage int) ([]string, *model.A span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLogs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7043,9 +6965,9 @@ func (a *OpenTracingAppLayer) GetLogsSkipSend(page int, perPage int) ([]string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetLogsSkipSend") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7065,9 +6987,9 @@ func (a *OpenTracingAppLayer) GetMarketplacePlugins(filter *model.MarketplacePlu span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetMarketplacePlugins") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7087,9 +7009,9 @@ func (a *OpenTracingAppLayer) GetMemberCountsByGroup(ctx context.Context, channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetMemberCountsByGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7109,9 +7031,9 @@ func (a *OpenTracingAppLayer) GetMessageForNotification(post *model.Post, transl span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetMessageForNotification") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7126,9 +7048,9 @@ func (a *OpenTracingAppLayer) GetMultipleEmojiByName(names []string) ([]*model.E span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetMultipleEmojiByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7148,9 +7070,9 @@ func (a *OpenTracingAppLayer) GetNewTeamMembersSince(c request.CTX, teamID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNewTeamMembersSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7170,9 +7092,9 @@ func (a *OpenTracingAppLayer) GetNewUsersForTeamPage(teamID string, page int, pe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNewUsersForTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7192,9 +7114,9 @@ func (a *OpenTracingAppLayer) GetNextPostIdFromPostList(postList *model.PostList span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNextPostIdFromPostList") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7209,9 +7131,9 @@ func (a *OpenTracingAppLayer) GetNotificationNameFormat(user *model.User) string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNotificationNameFormat") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7226,9 +7148,9 @@ func (a *OpenTracingAppLayer) GetNumberOfChannelsOnTeam(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetNumberOfChannelsOnTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7248,9 +7170,9 @@ func (a *OpenTracingAppLayer) GetOAuthAccessTokenForCodeFlow(clientId string, gr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthAccessTokenForCodeFlow") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7270,9 +7192,9 @@ func (a *OpenTracingAppLayer) GetOAuthAccessTokenForImplicitFlow(userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthAccessTokenForImplicitFlow") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7292,9 +7214,9 @@ func (a *OpenTracingAppLayer) GetOAuthApp(appID string) (*model.OAuthApp, *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthApp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7314,9 +7236,9 @@ func (a *OpenTracingAppLayer) GetOAuthApps(page int, perPage int) ([]*model.OAut span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthApps") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7336,9 +7258,9 @@ func (a *OpenTracingAppLayer) GetOAuthAppsByCreator(userID string, page int, per span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthAppsByCreator") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7358,9 +7280,9 @@ func (a *OpenTracingAppLayer) GetOAuthCodeRedirect(userID string, authRequest *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthCodeRedirect") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7380,9 +7302,9 @@ func (a *OpenTracingAppLayer) GetOAuthImplicitRedirect(userID string, authReques span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthImplicitRedirect") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7402,9 +7324,9 @@ func (a *OpenTracingAppLayer) GetOAuthLoginEndpoint(w http.ResponseWriter, r *ht span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthLoginEndpoint") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7424,9 +7346,9 @@ func (a *OpenTracingAppLayer) GetOAuthSignupEndpoint(w http.ResponseWriter, r *h span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthSignupEndpoint") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7446,9 +7368,9 @@ func (a *OpenTracingAppLayer) GetOAuthStateToken(token string) (*model.Token, *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOAuthStateToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7468,9 +7390,9 @@ func (a *OpenTracingAppLayer) GetOnboarding() (*model.System, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOnboarding") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7490,9 +7412,9 @@ func (a *OpenTracingAppLayer) GetOpenGraphMetadata(requestURL string) ([]byte, e span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOpenGraphMetadata") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7512,9 +7434,9 @@ func (a *OpenTracingAppLayer) GetOrCreateDirectChannel(c request.CTX, userID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOrCreateDirectChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7534,9 +7456,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhook(hookID string) (*model.Outgoing span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7556,9 +7478,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhooksForChannelPageByUser(channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhooksForChannelPageByUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7578,9 +7500,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhooksForTeamPage(teamID string, page span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhooksForTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7600,9 +7522,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhooksForTeamPageByUser(teamID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhooksForTeamPageByUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7622,9 +7544,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhooksPage(page int, perPage int) ([] span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhooksPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7644,9 +7566,9 @@ func (a *OpenTracingAppLayer) GetOutgoingWebhooksPageByUser(userID string, page span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetOutgoingWebhooksPageByUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7666,9 +7588,9 @@ func (a *OpenTracingAppLayer) GetPasswordRecoveryToken(token string) (*model.Tok span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPasswordRecoveryToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7688,9 +7610,9 @@ func (a *OpenTracingAppLayer) GetPermalinkPost(c request.CTX, postID string, use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPermalinkPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7710,9 +7632,9 @@ func (a *OpenTracingAppLayer) GetPinnedPosts(c request.CTX, channelID string) (* span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPinnedPosts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7732,9 +7654,9 @@ func (a *OpenTracingAppLayer) GetPluginKey(pluginID string, key string) ([]byte, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPluginKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7754,9 +7676,9 @@ func (a *OpenTracingAppLayer) GetPluginStatus(id string) (*model.PluginStatus, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPluginStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7776,9 +7698,9 @@ func (a *OpenTracingAppLayer) GetPluginStatuses() (model.PluginStatuses, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPluginStatuses") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7798,9 +7720,9 @@ func (a *OpenTracingAppLayer) GetPlugins() (*model.PluginsResponse, *model.AppEr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPlugins") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7820,9 +7742,9 @@ func (a *OpenTracingAppLayer) GetPluginsEnvironment() *plugin.Environment { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPluginsEnvironment") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7837,9 +7759,9 @@ func (a *OpenTracingAppLayer) GetPostAfterTime(channelID string, time int64, col span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostAfterTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7859,9 +7781,9 @@ func (a *OpenTracingAppLayer) GetPostIdAfterTime(channelID string, time int64, c span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostIdAfterTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7881,9 +7803,9 @@ func (a *OpenTracingAppLayer) GetPostIdBeforeTime(channelID string, time int64, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostIdBeforeTime") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7903,9 +7825,9 @@ func (a *OpenTracingAppLayer) GetPostIfAuthorized(c request.CTX, postID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostIfAuthorized") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7925,9 +7847,9 @@ func (a *OpenTracingAppLayer) GetPostThread(postID string, opts model.GetPostsOp span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostThread") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7947,9 +7869,9 @@ func (a *OpenTracingAppLayer) GetPosts(channelID string, offset int, limit int) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPosts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7969,9 +7891,9 @@ func (a *OpenTracingAppLayer) GetPostsAfterPost(options model.GetPostsOptions) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsAfterPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -7991,9 +7913,9 @@ func (a *OpenTracingAppLayer) GetPostsAroundPost(before bool, options model.GetP span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsAroundPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8013,9 +7935,9 @@ func (a *OpenTracingAppLayer) GetPostsBeforePost(options model.GetPostsOptions) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsBeforePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8035,9 +7957,9 @@ func (a *OpenTracingAppLayer) GetPostsByIds(postIDs []string) ([]*model.Post, in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8057,9 +7979,9 @@ func (a *OpenTracingAppLayer) GetPostsEtag(channelID string, collapsedThreads bo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsEtag") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8074,9 +7996,9 @@ func (a *OpenTracingAppLayer) GetPostsForChannelAroundLastUnread(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsForChannelAroundLastUnread") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8096,9 +8018,9 @@ func (a *OpenTracingAppLayer) GetPostsPage(options model.GetPostsOptions) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8118,9 +8040,9 @@ func (a *OpenTracingAppLayer) GetPostsSince(options model.GetPostsSinceOptions) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8140,9 +8062,9 @@ func (a *OpenTracingAppLayer) GetPostsUsage() (int64, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPostsUsage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8162,9 +8084,9 @@ func (a *OpenTracingAppLayer) GetPreferenceByCategoryAndNameForUser(userID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPreferenceByCategoryAndNameForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8184,9 +8106,9 @@ func (a *OpenTracingAppLayer) GetPreferenceByCategoryForUser(userID string, cate span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPreferenceByCategoryForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8206,9 +8128,9 @@ func (a *OpenTracingAppLayer) GetPreferencesForUser(userID string) (model.Prefer span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPreferencesForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8228,9 +8150,9 @@ func (a *OpenTracingAppLayer) GetPrevPostIdFromPostList(postList *model.PostList span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPrevPostIdFromPostList") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8245,9 +8167,9 @@ func (a *OpenTracingAppLayer) GetPrivateChannelsForTeam(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPrivateChannelsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8267,9 +8189,9 @@ func (a *OpenTracingAppLayer) GetProductNotices(c *request.Context, userID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetProductNotices") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8289,9 +8211,9 @@ func (a *OpenTracingAppLayer) GetProfileImage(user *model.User) ([]byte, bool, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetProfileImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8311,9 +8233,9 @@ func (a *OpenTracingAppLayer) GetPublicChannelsByIdsForTeam(c request.CTX, teamI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPublicChannelsByIdsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8333,9 +8255,9 @@ func (a *OpenTracingAppLayer) GetPublicChannelsForTeam(c request.CTX, teamID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPublicChannelsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8355,9 +8277,9 @@ func (a *OpenTracingAppLayer) GetPublicKey(name string) ([]byte, *model.AppError span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetPublicKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8377,9 +8299,9 @@ func (a *OpenTracingAppLayer) GetReactionsForPost(postID string) ([]*model.React span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetReactionsForPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8399,9 +8321,9 @@ func (a *OpenTracingAppLayer) GetRecentSearchesForUser(userID string) ([]*model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRecentSearchesForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8421,9 +8343,9 @@ func (a *OpenTracingAppLayer) GetRecentlyActiveUsersForTeam(teamID string) (map[ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRecentlyActiveUsersForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8443,9 +8365,9 @@ func (a *OpenTracingAppLayer) GetRecentlyActiveUsersForTeamPage(teamID string, p span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRecentlyActiveUsersForTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8465,9 +8387,9 @@ func (a *OpenTracingAppLayer) GetRemoteCluster(remoteClusterId string) (*model.R span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRemoteCluster") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8487,9 +8409,9 @@ func (a *OpenTracingAppLayer) GetRemoteClusterForUser(remoteID string, userID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRemoteClusterForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8509,9 +8431,9 @@ func (a *OpenTracingAppLayer) GetRemoteClusterService() (remotecluster.RemoteClu span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRemoteClusterService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8531,9 +8453,9 @@ func (a *OpenTracingAppLayer) GetRemoteClusterSession(token string, remoteId str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRemoteClusterSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8553,9 +8475,9 @@ func (a *OpenTracingAppLayer) GetRetentionPolicies(offset int, limit int) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRetentionPolicies") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8575,9 +8497,9 @@ func (a *OpenTracingAppLayer) GetRetentionPoliciesCount() (int64, *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRetentionPoliciesCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8597,9 +8519,9 @@ func (a *OpenTracingAppLayer) GetRetentionPolicy(policyID string) (*model.Retent span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8619,9 +8541,9 @@ func (a *OpenTracingAppLayer) GetRole(id string) (*model.Role, *model.AppError) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRole") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8641,9 +8563,9 @@ func (a *OpenTracingAppLayer) GetRoleByName(ctx context.Context, name string) (* span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRoleByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8663,9 +8585,9 @@ func (a *OpenTracingAppLayer) GetRolesByNames(names []string) ([]*model.Role, *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetRolesByNames") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8685,9 +8607,9 @@ func (a *OpenTracingAppLayer) GetSamlCertificateStatus() *model.SamlCertificateS span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSamlCertificateStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8702,9 +8624,9 @@ func (a *OpenTracingAppLayer) GetSamlMetadata() (string, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSamlMetadata") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8724,9 +8646,9 @@ func (a *OpenTracingAppLayer) GetSamlMetadataFromIdp(idpMetadataURL string) (*mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSamlMetadataFromIdp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8746,9 +8668,9 @@ func (a *OpenTracingAppLayer) GetSanitizeOptions(asAdmin bool) map[string]bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizeOptions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8763,9 +8685,9 @@ func (a *OpenTracingAppLayer) GetSanitizedConfig() *model.Config { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8780,9 +8702,9 @@ func (a *OpenTracingAppLayer) GetScheme(id string) (*model.Scheme, *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8802,9 +8724,9 @@ func (a *OpenTracingAppLayer) GetSchemeByName(name string) (*model.Scheme, *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemeByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8824,9 +8746,9 @@ func (a *OpenTracingAppLayer) GetSchemeRolesForChannel(c request.CTX, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemeRolesForChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8846,9 +8768,9 @@ func (a *OpenTracingAppLayer) GetSchemeRolesForTeam(teamID string) (string, stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemeRolesForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8868,9 +8790,9 @@ func (a *OpenTracingAppLayer) GetSchemes(scope string, offset int, limit int) ([ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8890,9 +8812,9 @@ func (a *OpenTracingAppLayer) GetSchemesPage(scope string, page int, perPage int span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSchemesPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8912,9 +8834,9 @@ func (a *OpenTracingAppLayer) GetSession(token string) (*model.Session, *model.A span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8934,9 +8856,9 @@ func (a *OpenTracingAppLayer) GetSessionById(sessionID string) (*model.Session, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSessionById") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8956,9 +8878,9 @@ func (a *OpenTracingAppLayer) GetSessionLengthInMillis(session *model.Session) i span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSessionLengthInMillis") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8973,9 +8895,9 @@ func (a *OpenTracingAppLayer) GetSessions(userID string) ([]*model.Session, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSessions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -8995,9 +8917,9 @@ func (a *OpenTracingAppLayer) GetSharedChannel(channelID string) (*model.SharedC span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9017,9 +8939,9 @@ func (a *OpenTracingAppLayer) GetSharedChannelRemote(id string) (*model.SharedCh span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannelRemote") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9039,9 +8961,9 @@ func (a *OpenTracingAppLayer) GetSharedChannelRemoteByIds(channelID string, remo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannelRemoteByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9061,9 +8983,9 @@ func (a *OpenTracingAppLayer) GetSharedChannelRemotes(opts model.SharedChannelRe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannelRemotes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9083,9 +9005,9 @@ func (a *OpenTracingAppLayer) GetSharedChannelRemotesStatus(channelID string) ([ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannelRemotesStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9105,9 +9027,9 @@ func (a *OpenTracingAppLayer) GetSharedChannels(page int, perPage int, opts mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9127,9 +9049,9 @@ func (a *OpenTracingAppLayer) GetSharedChannelsCount(opts model.SharedChannelFil span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSharedChannelsCount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9149,9 +9071,9 @@ func (a *OpenTracingAppLayer) GetSidebarCategories(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategories") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9171,9 +9093,9 @@ func (a *OpenTracingAppLayer) GetSidebarCategoriesForTeamForUser(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategoriesForTeamForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9193,9 +9115,9 @@ func (a *OpenTracingAppLayer) GetSidebarCategory(c request.CTX, categoryId strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9215,9 +9137,9 @@ func (a *OpenTracingAppLayer) GetSidebarCategoryOrder(c request.CTX, userID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSidebarCategoryOrder") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9237,9 +9159,9 @@ func (a *OpenTracingAppLayer) GetSinglePost(postID string, includeDeleted bool) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSinglePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9259,9 +9181,9 @@ func (a *OpenTracingAppLayer) GetSiteURL() string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSiteURL") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9276,9 +9198,9 @@ func (a *OpenTracingAppLayer) GetStatus(userID string) (*model.Status, *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9298,9 +9220,9 @@ func (a *OpenTracingAppLayer) GetStatusFromCache(userID string) *model.Status { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetStatusFromCache") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9310,36 +9232,14 @@ func (a *OpenTracingAppLayer) GetStatusFromCache(userID string) *model.Status { return resultVar0 } -func (a *OpenTracingAppLayer) GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetStatusesByIds") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0, resultVar1 := a.app.GetStatusesByIds(userIDs) - - if resultVar1 != nil { - span.LogFields(spanlog.Error(resultVar1)) - ext.Error.Set(span, true) - } - - return resultVar0, resultVar1 -} - func (a *OpenTracingAppLayer) GetStorageUsage() (int64, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetStorageUsage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9359,9 +9259,9 @@ func (a *OpenTracingAppLayer) GetSuggestions(c *request.Context, commandArgs *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSuggestions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9376,9 +9276,9 @@ func (a *OpenTracingAppLayer) GetSystemBot() (*model.Bot, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSystemBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9398,9 +9298,9 @@ func (a *OpenTracingAppLayer) GetTeam(teamID string) (*model.Team, *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9420,9 +9320,9 @@ func (a *OpenTracingAppLayer) GetTeamByInviteId(inviteId string) (*model.Team, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamByInviteId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9442,9 +9342,9 @@ func (a *OpenTracingAppLayer) GetTeamByName(name string) (*model.Team, *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamByName") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9464,9 +9364,9 @@ func (a *OpenTracingAppLayer) GetTeamGroupUsers(teamID string) ([]*model.User, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamGroupUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9486,9 +9386,9 @@ func (a *OpenTracingAppLayer) GetTeamIcon(team *model.Team) ([]byte, *model.AppE span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamIcon") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9508,9 +9408,9 @@ func (a *OpenTracingAppLayer) GetTeamIdFromQuery(query url.Values) (string, *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamIdFromQuery") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9530,9 +9430,9 @@ func (a *OpenTracingAppLayer) GetTeamMember(teamID string, userID string) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9552,9 +9452,9 @@ func (a *OpenTracingAppLayer) GetTeamMembers(teamID string, offset int, limit in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9574,9 +9474,9 @@ func (a *OpenTracingAppLayer) GetTeamMembersByIds(teamID string, userIDs []strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamMembersByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9596,9 +9496,9 @@ func (a *OpenTracingAppLayer) GetTeamMembersForUser(userID string, excludeTeamID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamMembersForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9618,9 +9518,9 @@ func (a *OpenTracingAppLayer) GetTeamMembersForUserWithPagination(userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamMembersForUserWithPagination") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9640,9 +9540,9 @@ func (a *OpenTracingAppLayer) GetTeamPoliciesForUser(userID string, offset int, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamPoliciesForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9662,9 +9562,9 @@ func (a *OpenTracingAppLayer) GetTeamSchemeChannelRoles(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamSchemeChannelRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9684,9 +9584,9 @@ func (a *OpenTracingAppLayer) GetTeamStats(teamID string, restrictions *model.Vi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamStats") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9706,9 +9606,9 @@ func (a *OpenTracingAppLayer) GetTeamUnread(teamID string, userID string) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamUnread") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9728,9 +9628,9 @@ func (a *OpenTracingAppLayer) GetTeams(teamIDs []string) ([]*model.Team, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9750,9 +9650,9 @@ func (a *OpenTracingAppLayer) GetTeamsForRetentionPolicy(policyID string, offset span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsForRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9772,9 +9672,9 @@ func (a *OpenTracingAppLayer) GetTeamsForScheme(scheme *model.Scheme, offset int span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsForScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9794,9 +9694,9 @@ func (a *OpenTracingAppLayer) GetTeamsForSchemePage(scheme *model.Scheme, page i span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsForSchemePage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9816,9 +9716,9 @@ func (a *OpenTracingAppLayer) GetTeamsForUser(userID string) ([]*model.Team, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9838,9 +9738,9 @@ func (a *OpenTracingAppLayer) GetTeamsUnreadForUser(excludeTeamId string, userID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsUnreadForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9860,9 +9760,9 @@ func (a *OpenTracingAppLayer) GetTeamsUsage() (*model.TeamsUsage, *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTeamsUsage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9882,9 +9782,9 @@ func (a *OpenTracingAppLayer) GetTermsOfService(id string) (*model.TermsOfServic span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTermsOfService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9904,9 +9804,9 @@ func (a *OpenTracingAppLayer) GetThreadForUser(teamID string, threadMembership * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetThreadForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9926,9 +9826,9 @@ func (a *OpenTracingAppLayer) GetThreadMembershipForUser(userId string, threadId span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetThreadMembershipForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9948,9 +9848,9 @@ func (a *OpenTracingAppLayer) GetThreadMembershipsForUser(userID string, teamID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetThreadMembershipsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9970,9 +9870,9 @@ func (a *OpenTracingAppLayer) GetThreadsForUser(userID string, teamID string, op span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetThreadsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -9992,9 +9892,9 @@ func (a *OpenTracingAppLayer) GetTokenById(token string) (*model.Token, *model.A span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTokenById") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10014,9 +9914,9 @@ func (a *OpenTracingAppLayer) GetTopChannelsForTeamSince(c request.CTX, teamID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopChannelsForTeamSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10036,9 +9936,9 @@ func (a *OpenTracingAppLayer) GetTopChannelsForUserSince(c request.CTX, userID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopChannelsForUserSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10058,9 +9958,9 @@ func (a *OpenTracingAppLayer) GetTopDMsForUserSince(userID string, opts *model.I span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopDMsForUserSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10080,9 +9980,9 @@ func (a *OpenTracingAppLayer) GetTopInactiveChannelsForTeamSince(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopInactiveChannelsForTeamSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10102,9 +10002,9 @@ func (a *OpenTracingAppLayer) GetTopInactiveChannelsForUserSince(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopInactiveChannelsForUserSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10124,9 +10024,9 @@ func (a *OpenTracingAppLayer) GetTopReactionsForTeamSince(teamID string, userID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopReactionsForTeamSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10146,9 +10046,9 @@ func (a *OpenTracingAppLayer) GetTopReactionsForUserSince(userID string, teamID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopReactionsForUserSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10168,9 +10068,9 @@ func (a *OpenTracingAppLayer) GetTopThreadsForTeamSince(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopThreadsForTeamSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10190,9 +10090,9 @@ func (a *OpenTracingAppLayer) GetTopThreadsForUserSince(c request.CTX, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTopThreadsForUserSince") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10212,9 +10112,9 @@ func (a *OpenTracingAppLayer) GetTotalUsersStats(viewRestrictions *model.ViewUse span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetTotalUsersStats") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10234,9 +10134,9 @@ func (a *OpenTracingAppLayer) GetUploadSession(uploadId string) (*model.UploadSe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUploadSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10256,9 +10156,9 @@ func (a *OpenTracingAppLayer) GetUploadSessionsForUser(userID string) ([]*model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUploadSessionsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10278,9 +10178,9 @@ func (a *OpenTracingAppLayer) GetUser(userID string) (*model.User, *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10300,9 +10200,9 @@ func (a *OpenTracingAppLayer) GetUserAccessToken(tokenID string, sanitize bool) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10322,9 +10222,9 @@ func (a *OpenTracingAppLayer) GetUserAccessTokens(page int, perPage int) ([]*mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserAccessTokens") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10344,9 +10244,9 @@ func (a *OpenTracingAppLayer) GetUserAccessTokensForUser(userID string, page int span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserAccessTokensForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10366,9 +10266,9 @@ func (a *OpenTracingAppLayer) GetUserByAuth(authData *string, authService string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserByAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10388,9 +10288,9 @@ func (a *OpenTracingAppLayer) GetUserByEmail(email string) (*model.User, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserByEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10410,9 +10310,9 @@ func (a *OpenTracingAppLayer) GetUserByUsername(username string) (*model.User, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserByUsername") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10432,9 +10332,9 @@ func (a *OpenTracingAppLayer) GetUserForLogin(id string, loginId string) (*model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserForLogin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10454,9 +10354,9 @@ func (a *OpenTracingAppLayer) GetUserStatusesByIds(userIDs []string) ([]*model.S span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserStatusesByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10476,9 +10376,9 @@ func (a *OpenTracingAppLayer) GetUserTermsOfService(userID string) (*model.UserT span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserTermsOfService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10498,9 +10398,9 @@ func (a *OpenTracingAppLayer) GetUsers(userIDs []string) ([]*model.User, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10520,9 +10420,9 @@ func (a *OpenTracingAppLayer) GetUsersByGroupChannelIds(c *request.Context, chan span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersByGroupChannelIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10542,9 +10442,9 @@ func (a *OpenTracingAppLayer) GetUsersByIds(userIDs []string, options *store.Use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersByIds") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10564,9 +10464,9 @@ func (a *OpenTracingAppLayer) GetUsersByUsernames(usernames []string, asAdmin bo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersByUsernames") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10586,9 +10486,9 @@ func (a *OpenTracingAppLayer) GetUsersEtag(restrictionsHash string) string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersEtag") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10603,9 +10503,9 @@ func (a *OpenTracingAppLayer) GetUsersFromProfiles(options *model.UserGetOptions span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersFromProfiles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10625,9 +10525,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannel(options *model.UserGetOptions) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10647,9 +10547,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelByAdmin(options *model.UserGetOpt span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelByAdmin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10669,9 +10569,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelByStatus(options *model.UserGetOp span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelByStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10691,9 +10591,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelMap(options *model.UserGetOptions span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelMap") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10713,9 +10613,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelPage(options *model.UserGetOption span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10735,9 +10635,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelPageByAdmin(options *model.UserGe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelPageByAdmin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10757,9 +10657,9 @@ func (a *OpenTracingAppLayer) GetUsersInChannelPageByStatus(options *model.UserG span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInChannelPageByStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10779,9 +10679,9 @@ func (a *OpenTracingAppLayer) GetUsersInTeam(options *model.UserGetOptions) ([]* span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10801,9 +10701,9 @@ func (a *OpenTracingAppLayer) GetUsersInTeamEtag(teamID string, restrictionsHash span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInTeamEtag") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10818,9 +10718,9 @@ func (a *OpenTracingAppLayer) GetUsersInTeamPage(options *model.UserGetOptions, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersInTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10840,9 +10740,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInChannel(teamID string, channelID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10862,9 +10762,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInChannelMap(teamID string, channelID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInChannelMap") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10884,9 +10784,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInChannelPage(teamID string, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInChannelPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10906,9 +10806,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInGroupPage(groupID string, page int, p span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInGroupPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10928,9 +10828,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInTeam(teamID string, groupConstrained span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10950,9 +10850,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInTeamEtag(teamID string, restrictionsH span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInTeamEtag") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10967,9 +10867,9 @@ func (a *OpenTracingAppLayer) GetUsersNotInTeamPage(teamID string, groupConstrai span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersNotInTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -10989,9 +10889,9 @@ func (a *OpenTracingAppLayer) GetUsersPage(options *model.UserGetOptions, asAdmi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11011,9 +10911,9 @@ func (a *OpenTracingAppLayer) GetUsersWithInvalidEmails(page int, perPage int) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersWithInvalidEmails") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11033,9 +10933,9 @@ func (a *OpenTracingAppLayer) GetUsersWithoutTeam(options *model.UserGetOptions) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersWithoutTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11055,9 +10955,9 @@ func (a *OpenTracingAppLayer) GetUsersWithoutTeamPage(options *model.UserGetOpti span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUsersWithoutTeamPage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11077,9 +10977,9 @@ func (a *OpenTracingAppLayer) GetVerifyEmailToken(token string) (*model.Token, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetVerifyEmailToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11099,9 +10999,9 @@ func (a *OpenTracingAppLayer) GetViewUsersRestrictions(userID string) (*model.Vi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetViewUsersRestrictions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11121,9 +11021,9 @@ func (a *OpenTracingAppLayer) GetWarnMetricsBot() (*model.Bot, *model.AppError) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetWarnMetricsBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11143,9 +11043,9 @@ func (a *OpenTracingAppLayer) GetWarnMetricsStatus() (map[string]*model.WarnMetr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetWarnMetricsStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11165,9 +11065,9 @@ func (a *OpenTracingAppLayer) Handle404(w http.ResponseWriter, r *http.Request) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Handle404") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11180,9 +11080,9 @@ func (a *OpenTracingAppLayer) HandleCommandResponse(c request.CTX, command *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandResponse") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11202,9 +11102,9 @@ func (a *OpenTracingAppLayer) HandleCommandResponsePost(c request.CTX, command * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandResponsePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11224,9 +11124,9 @@ func (a *OpenTracingAppLayer) HandleCommandWebhook(c *request.Context, hookID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleCommandWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11246,9 +11146,9 @@ func (a *OpenTracingAppLayer) HandleImages(previewPathList []string, thumbnailPa span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleImages") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11261,9 +11161,9 @@ func (a *OpenTracingAppLayer) HandleIncomingWebhook(c *request.Context, hookID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleIncomingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11283,9 +11183,9 @@ func (a *OpenTracingAppLayer) HandleMessageExportConfig(cfg *model.Config, appCf span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HandleMessageExportConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11298,9 +11198,9 @@ func (a *OpenTracingAppLayer) HasPermissionTo(askingUserId string, permission *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionTo") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11315,9 +11215,9 @@ func (a *OpenTracingAppLayer) HasPermissionToChannel(c request.CTX, askingUserId span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11332,9 +11232,9 @@ func (a *OpenTracingAppLayer) HasPermissionToChannelByPost(askingUserId string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToChannelByPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11349,9 +11249,9 @@ func (a *OpenTracingAppLayer) HasPermissionToReadChannel(c request.CTX, userID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToReadChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11366,9 +11266,9 @@ func (a *OpenTracingAppLayer) HasPermissionToTeam(askingUserId string, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11383,9 +11283,9 @@ func (a *OpenTracingAppLayer) HasPermissionToUser(askingUserId string, userID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasPermissionToUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11400,9 +11300,9 @@ func (a *OpenTracingAppLayer) HasRemote(channelID string, remoteID string) (bool span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasRemote") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11422,9 +11322,9 @@ func (a *OpenTracingAppLayer) HasSharedChannel(channelID string) (bool, error) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HasSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11439,14 +11339,14 @@ func (a *OpenTracingAppLayer) HasSharedChannel(channelID string) (bool, error) { return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) HubRegister(webConn *app.WebConn) { +func (a *OpenTracingAppLayer) HubRegister(webConn *platform.WebConn) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HubRegister") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11454,14 +11354,14 @@ func (a *OpenTracingAppLayer) HubRegister(webConn *app.WebConn) { a.app.HubRegister(webConn) } -func (a *OpenTracingAppLayer) HubUnregister(webConn *app.WebConn) { +func (a *OpenTracingAppLayer) HubUnregister(webConn *platform.WebConn) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HubUnregister") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11474,9 +11374,9 @@ func (a *OpenTracingAppLayer) ImageProxyAdder() func(string) string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ImageProxyAdder") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11491,9 +11391,9 @@ func (a *OpenTracingAppLayer) ImageProxyRemover() (f func(string) string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ImageProxyRemover") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11508,9 +11408,9 @@ func (a *OpenTracingAppLayer) ImportPermissions(jsonl io.Reader) error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ImportPermissions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11530,9 +11430,9 @@ func (a *OpenTracingAppLayer) InitPlugins(c *request.Context, pluginDir string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitPlugins") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11545,9 +11445,9 @@ func (a *OpenTracingAppLayer) InstallPlugin(pluginFile io.ReadSeeker, replace bo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InstallPlugin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11567,9 +11467,9 @@ func (a *OpenTracingAppLayer) InvalidateAllEmailInvites() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllEmailInvites") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11589,9 +11489,9 @@ func (a *OpenTracingAppLayer) InvalidateAllResendInviteEmailJobs() *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllResendInviteEmailJobs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11611,9 +11511,9 @@ func (a *OpenTracingAppLayer) InvalidateCacheForUser(userID string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateCacheForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11626,9 +11526,9 @@ func (a *OpenTracingAppLayer) InviteGuestsToChannels(teamID string, guestsInvite span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InviteGuestsToChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11648,9 +11548,9 @@ func (a *OpenTracingAppLayer) InviteGuestsToChannelsGracefully(teamID string, gu span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InviteGuestsToChannelsGracefully") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11670,9 +11570,9 @@ func (a *OpenTracingAppLayer) InviteNewUsersToTeam(emailList []string, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InviteNewUsersToTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11692,9 +11592,9 @@ func (a *OpenTracingAppLayer) InviteNewUsersToTeamGracefully(memberInvite *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InviteNewUsersToTeamGracefully") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11714,9 +11614,9 @@ func (a *OpenTracingAppLayer) IsCRTEnabledForUser(c request.CTX, userID string) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsCRTEnabledForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11731,9 +11631,9 @@ func (a *OpenTracingAppLayer) IsFirstUserAccount() bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsFirstUserAccount") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11748,9 +11648,9 @@ func (a *OpenTracingAppLayer) IsLeader() bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsLeader") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11765,9 +11665,9 @@ func (a *OpenTracingAppLayer) IsPasswordValid(password string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsPasswordValid") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11787,9 +11687,9 @@ func (a *OpenTracingAppLayer) IsPhase2MigrationCompleted() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsPhase2MigrationCompleted") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11809,9 +11709,9 @@ func (a *OpenTracingAppLayer) IsUserAway(lastActivityAt int64) bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsUserAway") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11826,9 +11726,9 @@ func (a *OpenTracingAppLayer) IsUserSignUpAllowed() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.IsUserSignUpAllowed") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11848,9 +11748,9 @@ func (a *OpenTracingAppLayer) JoinChannel(c request.CTX, channel *model.Channel, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11870,9 +11770,9 @@ func (a *OpenTracingAppLayer) JoinDefaultChannels(c request.CTX, teamID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinDefaultChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11892,9 +11792,9 @@ func (a *OpenTracingAppLayer) JoinUserToTeam(c request.CTX, team *model.Team, us span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.JoinUserToTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11914,9 +11814,9 @@ func (a *OpenTracingAppLayer) LeaveChannel(c request.CTX, channelID string, user span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LeaveChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11936,9 +11836,9 @@ func (a *OpenTracingAppLayer) LeaveTeam(c request.CTX, team *model.Team, user *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LeaveTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11958,9 +11858,9 @@ func (a *OpenTracingAppLayer) License() *model.License { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.License") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11975,9 +11875,9 @@ func (a *OpenTracingAppLayer) LimitedClientConfig() map[string]string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LimitedClientConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -11987,31 +11887,14 @@ func (a *OpenTracingAppLayer) LimitedClientConfig() map[string]string { return resultVar0 } -func (a *OpenTracingAppLayer) LimitedClientConfigWithComputed() map[string]string { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LimitedClientConfigWithComputed") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.LimitedClientConfigWithComputed() - - return resultVar0 -} - func (a *OpenTracingAppLayer) ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Command, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListAllCommands") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12031,9 +11914,9 @@ func (a *OpenTracingAppLayer) ListAutocompleteCommands(teamID string, T i18n.Tra span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListAutocompleteCommands") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12055,9 +11938,9 @@ func (a *OpenTracingAppLayer) ListDirectory(path string) ([]string, *model.AppEr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListDirectory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12077,9 +11960,9 @@ func (a *OpenTracingAppLayer) ListDirectoryRecursively(path string) ([]string, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListDirectoryRecursively") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12099,9 +11982,9 @@ func (a *OpenTracingAppLayer) ListExports() ([]string, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListExports") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12121,9 +12004,9 @@ func (a *OpenTracingAppLayer) ListImports() ([]string, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListImports") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12143,9 +12026,9 @@ func (a *OpenTracingAppLayer) ListPluginKeys(pluginID string, page int, perPage span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListPluginKeys") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12165,9 +12048,9 @@ func (a *OpenTracingAppLayer) ListTeamCommands(teamID string) ([]*model.Command, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ListTeamCommands") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12187,9 +12070,9 @@ func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRec") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12202,9 +12085,9 @@ func (a *OpenTracingAppLayer) LogAuditRecWithLevel(rec *audit.Record, level mlog span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRecWithLevel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12217,9 +12100,9 @@ func (a *OpenTracingAppLayer) LoginByOAuth(c *request.Context, service string, u span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LoginByOAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12239,9 +12122,9 @@ func (a *OpenTracingAppLayer) MakeAuditRecord(event string, initialStatus string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MakeAuditRecord") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12256,9 +12139,9 @@ func (a *OpenTracingAppLayer) MakePermissionError(s *model.Session, permissions span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MakePermissionError") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12278,9 +12161,9 @@ func (a *OpenTracingAppLayer) MarkChannelAsUnreadFromPost(c request.CTX, postID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MarkChannelAsUnreadFromPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12300,9 +12183,9 @@ func (a *OpenTracingAppLayer) MarkChannelsAsViewed(c request.CTX, channelIDs []s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MarkChannelsAsViewed") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12322,9 +12205,9 @@ func (a *OpenTracingAppLayer) MaxPostSize() int { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MaxPostSize") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12339,9 +12222,9 @@ func (a *OpenTracingAppLayer) MentionsToPublicChannels(c request.CTX, message st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MentionsToPublicChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12356,9 +12239,9 @@ func (a *OpenTracingAppLayer) MentionsToTeamMembers(c request.CTX, message strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MentionsToTeamMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12373,9 +12256,9 @@ func (a *OpenTracingAppLayer) MigrateFilenamesToFileInfos(post *model.Post) []*m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MigrateFilenamesToFileInfos") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12390,9 +12273,9 @@ func (a *OpenTracingAppLayer) MigrateIdLDAP(toAttribute string) *model.AppError span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MigrateIdLDAP") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12412,9 +12295,9 @@ func (a *OpenTracingAppLayer) MoveChannel(c request.CTX, team *model.Team, chann span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MoveChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12434,9 +12317,9 @@ func (a *OpenTracingAppLayer) MoveCommand(team *model.Team, command *model.Comma span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MoveCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12456,9 +12339,9 @@ func (a *OpenTracingAppLayer) MoveFile(oldPath string, newPath string) *model.Ap span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.MoveFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12473,31 +12356,14 @@ func (a *OpenTracingAppLayer) MoveFile(oldPath string, newPath string) *model.Ap return resultVar0 } -func (a *OpenTracingAppLayer) NewClusterDiscoveryService() *app.ClusterDiscoveryService { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NewClusterDiscoveryService") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.NewClusterDiscoveryService() - - return resultVar0 -} - func (a *OpenTracingAppLayer) NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NewPluginAPI") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12507,14 +12373,14 @@ func (a *OpenTracingAppLayer) NewPluginAPI(c *request.Context, manifest *model.M return resultVar0 } -func (a *OpenTracingAppLayer) NewWebConn(cfg *app.WebConnConfig) *app.WebConn { +func (a *OpenTracingAppLayer) NewWebConn(cfg *platform.WebConnConfig) *platform.WebConn { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NewWebConn") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12529,9 +12395,9 @@ func (a *OpenTracingAppLayer) NotifyAndSetWarnMetricAck(warnMetricId string, sen span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NotifyAndSetWarnMetricAck") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12551,9 +12417,9 @@ func (a *OpenTracingAppLayer) NotifySessionsExpired() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NotifySessionsExpired") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12573,9 +12439,9 @@ func (a *OpenTracingAppLayer) NotifySharedChannelUserUpdate(user *model.User) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.NotifySharedChannelUserUpdate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12588,9 +12454,9 @@ func (a *OpenTracingAppLayer) OpenInteractiveDialog(request model.OpenDialogRequ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.OpenInteractiveDialog") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12610,9 +12476,9 @@ func (a *OpenTracingAppLayer) OriginChecker() func(*http.Request) bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.OriginChecker") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12627,9 +12493,9 @@ func (a *OpenTracingAppLayer) OverrideIconURLIfEmoji(post *model.Post) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.OverrideIconURLIfEmoji") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12642,9 +12508,9 @@ func (a *OpenTracingAppLayer) PatchBot(botUserId string, botPatch *model.BotPatc span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12664,9 +12530,9 @@ func (a *OpenTracingAppLayer) PatchChannel(c request.CTX, channel *model.Channel span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12686,9 +12552,9 @@ func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(c request.CTX, c span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchChannelModerationsForChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12708,9 +12574,9 @@ func (a *OpenTracingAppLayer) PatchPost(c *request.Context, postID string, patch span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12730,9 +12596,9 @@ func (a *OpenTracingAppLayer) PatchRetentionPolicy(patch *model.RetentionPolicyW span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12752,9 +12618,9 @@ func (a *OpenTracingAppLayer) PatchRole(role *model.Role, patch *model.RolePatch span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchRole") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12774,9 +12640,9 @@ func (a *OpenTracingAppLayer) PatchScheme(scheme *model.Scheme, patch *model.Sch span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12796,9 +12662,9 @@ func (a *OpenTracingAppLayer) PatchTeam(teamID string, patch *model.TeamPatch) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12818,9 +12684,9 @@ func (a *OpenTracingAppLayer) PatchUser(c request.CTX, userID string, patch *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12840,9 +12706,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteAllUsers(c *request.Context) *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteAllUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12862,9 +12728,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteBot(botUserId string) *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12884,9 +12750,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteChannel(c request.CTX, channel *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12906,9 +12772,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeam(c request.CTX, team *model.Tea span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12928,9 +12794,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteTeamId(c request.CTX, teamID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteTeamId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12950,9 +12816,9 @@ func (a *OpenTracingAppLayer) PermanentDeleteUser(c *request.Context, user *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PermanentDeleteUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12972,9 +12838,9 @@ func (a *OpenTracingAppLayer) PluginCommandsForTeam(teamID string) []*model.Comm span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PluginCommandsForTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -12984,14 +12850,14 @@ func (a *OpenTracingAppLayer) PluginCommandsForTeam(teamID string) []*model.Comm return resultVar0 } -func (a *OpenTracingAppLayer) PopulateWebConnConfig(s *model.Session, cfg *app.WebConnConfig, seqVal string) (*app.WebConnConfig, error) { +func (a *OpenTracingAppLayer) PopulateWebConnConfig(s *model.Session, cfg *platform.WebConnConfig, seqVal string) (*platform.WebConnConfig, error) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PopulateWebConnConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13011,9 +12877,9 @@ func (a *OpenTracingAppLayer) PostActionCookieSecret() []byte { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostActionCookieSecret") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13028,9 +12894,9 @@ func (a *OpenTracingAppLayer) PostAddToChannelMessage(c request.CTX, user *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostAddToChannelMessage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13050,9 +12916,9 @@ func (a *OpenTracingAppLayer) PostCountsByDuration(c request.CTX, channelIDs []s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostCountsByDuration") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13072,9 +12938,9 @@ func (a *OpenTracingAppLayer) PostPatchWithProxyRemovedFromImageURLs(patch *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostPatchWithProxyRemovedFromImageURLs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13089,9 +12955,9 @@ func (a *OpenTracingAppLayer) PostUpdateChannelDisplayNameMessage(c request.CTX, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelDisplayNameMessage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13111,9 +12977,9 @@ func (a *OpenTracingAppLayer) PostUpdateChannelHeaderMessage(c request.CTX, user span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelHeaderMessage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13133,9 +12999,9 @@ func (a *OpenTracingAppLayer) PostUpdateChannelPurposeMessage(c request.CTX, use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostUpdateChannelPurposeMessage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13155,9 +13021,9 @@ func (a *OpenTracingAppLayer) PostWithProxyAddedToImageURLs(post *model.Post) *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostWithProxyAddedToImageURLs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13172,9 +13038,9 @@ func (a *OpenTracingAppLayer) PostWithProxyRemovedFromImageURLs(post *model.Post span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PostWithProxyRemovedFromImageURLs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13189,9 +13055,9 @@ func (a *OpenTracingAppLayer) PreparePostForClient(originalPost *model.Post, isN span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PreparePostForClient") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13206,9 +13072,9 @@ func (a *OpenTracingAppLayer) PreparePostForClientWithEmbedsAndImages(c request. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PreparePostForClientWithEmbedsAndImages") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13223,9 +13089,9 @@ func (a *OpenTracingAppLayer) PreparePostListForClient(c request.CTX, originalLi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PreparePostListForClient") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13240,9 +13106,9 @@ func (a *OpenTracingAppLayer) ProcessSlackAttachments(attachments []*model.Slack span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ProcessSlackAttachments") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13257,9 +13123,9 @@ func (a *OpenTracingAppLayer) ProcessSlackText(text string) string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ProcessSlackText") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13274,9 +13140,9 @@ func (a *OpenTracingAppLayer) PromoteGuestToUser(c *request.Context, user *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PromoteGuestToUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13296,9 +13162,9 @@ func (a *OpenTracingAppLayer) Publish(message *model.WebSocketEvent) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Publish") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13311,9 +13177,9 @@ func (a *OpenTracingAppLayer) PublishUserTyping(userID string, channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PublishUserTyping") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13333,9 +13199,9 @@ func (a *OpenTracingAppLayer) PurgeBleveIndexes() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PurgeBleveIndexes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13355,9 +13221,9 @@ func (a *OpenTracingAppLayer) PurgeElasticsearchIndexes() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PurgeElasticsearchIndexes") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13377,9 +13243,9 @@ func (a *OpenTracingAppLayer) ReadFile(path string) ([]byte, *model.AppError) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ReadFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13399,9 +13265,9 @@ func (a *OpenTracingAppLayer) RecycleDatabaseConnection() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RecycleDatabaseConnection") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13414,9 +13280,9 @@ func (a *OpenTracingAppLayer) RegenCommandToken(cmd *model.Command) (*model.Comm span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RegenCommandToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13436,9 +13302,9 @@ func (a *OpenTracingAppLayer) RegenOutgoingWebhookToken(hook *model.OutgoingWebh span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RegenOutgoingWebhookToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13458,9 +13324,9 @@ func (a *OpenTracingAppLayer) RegenerateOAuthAppSecret(app *model.OAuthApp) (*mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RegenerateOAuthAppSecret") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13480,9 +13346,9 @@ func (a *OpenTracingAppLayer) RegenerateTeamInviteId(teamID string) (*model.Team span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RegenerateTeamInviteId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13502,9 +13368,9 @@ func (a *OpenTracingAppLayer) RegisterPluginCommand(pluginID string, command *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RegisterPluginCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13524,9 +13390,9 @@ func (a *OpenTracingAppLayer) ReloadConfig() error { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ReloadConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13546,9 +13412,9 @@ func (a *OpenTracingAppLayer) RemoveAllDeactivatedMembersFromChannel(c request.C span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveAllDeactivatedMembersFromChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13568,9 +13434,9 @@ func (a *OpenTracingAppLayer) RemoveChannelsFromRetentionPolicy(policyID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveChannelsFromRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13590,9 +13456,9 @@ func (a *OpenTracingAppLayer) RemoveConfigListener(id string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveConfigListener") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13605,9 +13471,9 @@ func (a *OpenTracingAppLayer) RemoveCustomStatus(c request.CTX, userID string) * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveCustomStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13627,9 +13493,9 @@ func (a *OpenTracingAppLayer) RemoveDirectory(path string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveDirectory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13649,9 +13515,9 @@ func (a *OpenTracingAppLayer) RemoveFile(path string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13671,9 +13537,9 @@ func (a *OpenTracingAppLayer) RemoveLdapPrivateCertificate() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLdapPrivateCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13693,9 +13559,9 @@ func (a *OpenTracingAppLayer) RemoveLdapPublicCertificate() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLdapPublicCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13715,9 +13581,9 @@ func (a *OpenTracingAppLayer) RemoveRecentCustomStatus(userID string, status *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveRecentCustomStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13737,9 +13603,9 @@ func (a *OpenTracingAppLayer) RemoveSamlIdpCertificate() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveSamlIdpCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13759,9 +13625,9 @@ func (a *OpenTracingAppLayer) RemoveSamlPrivateCertificate() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveSamlPrivateCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13781,9 +13647,9 @@ func (a *OpenTracingAppLayer) RemoveSamlPublicCertificate() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveSamlPublicCertificate") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13803,9 +13669,9 @@ func (a *OpenTracingAppLayer) RemoveTeamIcon(teamID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveTeamIcon") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13825,9 +13691,9 @@ func (a *OpenTracingAppLayer) RemoveTeamsFromRetentionPolicy(policyID string, te span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveTeamsFromRetentionPolicy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13847,9 +13713,9 @@ func (a *OpenTracingAppLayer) RemoveUserFromChannel(c request.CTX, userIDToRemov span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUserFromChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13869,9 +13735,9 @@ func (a *OpenTracingAppLayer) RemoveUserFromTeam(c request.CTX, teamID string, u span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUserFromTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13891,9 +13757,9 @@ func (a *OpenTracingAppLayer) RemoveUsersFromChannelNotMemberOfTeam(c request.CT span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveUsersFromChannelNotMemberOfTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13913,9 +13779,9 @@ func (a *OpenTracingAppLayer) RenameChannel(c request.CTX, channel *model.Channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RenameChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13935,9 +13801,9 @@ func (a *OpenTracingAppLayer) RenameTeam(team *model.Team, newTeamName string, n span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RenameTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13957,9 +13823,9 @@ func (a *OpenTracingAppLayer) RequestLicenseAndAckWarnMetric(c *request.Context, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RequestLicenseAndAckWarnMetric") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -13979,9 +13845,9 @@ func (a *OpenTracingAppLayer) ResetPasswordFromToken(c request.CTX, userSupplied span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetPasswordFromToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14001,9 +13867,9 @@ func (a *OpenTracingAppLayer) ResetPermissionsSystem() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetPermissionsSystem") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14023,9 +13889,9 @@ func (a *OpenTracingAppLayer) ResetSamlAuthDataToEmail(includeDeleted bool, dryR span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetSamlAuthDataToEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14045,9 +13911,9 @@ func (a *OpenTracingAppLayer) RestoreChannel(c request.CTX, channel *model.Chann span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestoreChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14067,9 +13933,9 @@ func (a *OpenTracingAppLayer) RestoreTeam(teamID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestoreTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14089,9 +13955,9 @@ func (a *OpenTracingAppLayer) RestrictUsersGetByPermissions(userID string, optio span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestrictUsersGetByPermissions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14111,9 +13977,9 @@ func (a *OpenTracingAppLayer) RestrictUsersSearchByPermissions(userID string, op span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestrictUsersSearchByPermissions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14133,9 +13999,9 @@ func (a *OpenTracingAppLayer) ReturnSessionToPool(session *model.Session) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ReturnSessionToPool") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14148,9 +14014,9 @@ func (a *OpenTracingAppLayer) RevokeAccessToken(token string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14170,9 +14036,9 @@ func (a *OpenTracingAppLayer) RevokeAllSessions(userID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeAllSessions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14192,9 +14058,9 @@ func (a *OpenTracingAppLayer) RevokeSession(session *model.Session) *model.AppEr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeSession") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14214,9 +14080,9 @@ func (a *OpenTracingAppLayer) RevokeSessionById(sessionID string) *model.AppErro span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeSessionById") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14236,9 +14102,9 @@ func (a *OpenTracingAppLayer) RevokeSessionsForDeviceId(userID string, deviceID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeSessionsForDeviceId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14258,9 +14124,9 @@ func (a *OpenTracingAppLayer) RevokeSessionsFromAllUsers() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeSessionsFromAllUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14280,9 +14146,9 @@ func (a *OpenTracingAppLayer) RevokeUserAccessToken(token *model.UserAccessToken span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RevokeUserAccessToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14302,9 +14168,9 @@ func (a *OpenTracingAppLayer) RolesGrantPermission(roleNames []string, permissio span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RolesGrantPermission") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14319,9 +14185,9 @@ func (a *OpenTracingAppLayer) SanitizePostListMetadataForUser(c request.CTX, pos span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizePostListMetadataForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14341,9 +14207,9 @@ func (a *OpenTracingAppLayer) SanitizePostMetadataForUser(c request.CTX, post *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizePostMetadataForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14363,9 +14229,9 @@ func (a *OpenTracingAppLayer) SanitizeProfile(user *model.User, asAdmin bool) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizeProfile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14378,9 +14244,9 @@ func (a *OpenTracingAppLayer) SanitizeTeam(session model.Session, team *model.Te span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizeTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14395,9 +14261,9 @@ func (a *OpenTracingAppLayer) SanitizeTeams(session model.Session, teams []*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SanitizeTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14412,9 +14278,9 @@ func (a *OpenTracingAppLayer) SaveAdminNotification(userId string, notifyData *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveAdminNotification") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14434,9 +14300,9 @@ func (a *OpenTracingAppLayer) SaveAdminNotifyData(data *model.NotifyAdminData) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveAdminNotifyData") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14451,29 +14317,14 @@ func (a *OpenTracingAppLayer) SaveAdminNotifyData(data *model.NotifyAdminData) ( return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SaveAndBroadcastStatus(status *model.Status) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveAndBroadcastStatus") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.SaveAndBroadcastStatus(status) -} - func (a *OpenTracingAppLayer) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveBrandImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14493,9 +14344,9 @@ func (a *OpenTracingAppLayer) SaveComplianceReport(job *model.Compliance) (*mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveComplianceReport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14515,9 +14366,9 @@ func (a *OpenTracingAppLayer) SaveConfig(newCfg *model.Config, sendConfigChangeC span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14537,9 +14388,9 @@ func (a *OpenTracingAppLayer) SaveReactionForPost(c *request.Context, reaction * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveReactionForPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14559,9 +14410,9 @@ func (a *OpenTracingAppLayer) SaveSharedChannel(c request.CTX, sc *model.SharedC span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14581,9 +14432,9 @@ func (a *OpenTracingAppLayer) SaveSharedChannelRemote(remote *model.SharedChanne span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveSharedChannelRemote") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14603,9 +14454,9 @@ func (a *OpenTracingAppLayer) SaveUserTermsOfService(userID string, termsOfServi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveUserTermsOfService") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14625,9 +14476,9 @@ func (a *OpenTracingAppLayer) SchemesIterator(scope string, batchSize int) func( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SchemesIterator") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14642,9 +14493,9 @@ func (a *OpenTracingAppLayer) SearchAllChannels(c request.CTX, term string, opts span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchAllChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14664,9 +14515,9 @@ func (a *OpenTracingAppLayer) SearchAllTeams(searchOpts *model.TeamSearch) ([]*m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchAllTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14686,9 +14537,9 @@ func (a *OpenTracingAppLayer) SearchArchivedChannels(c request.CTX, teamID strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchArchivedChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14708,9 +14559,9 @@ func (a *OpenTracingAppLayer) SearchChannels(c request.CTX, teamID string, term span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14730,9 +14581,9 @@ func (a *OpenTracingAppLayer) SearchChannelsForUser(c request.CTX, userID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannelsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14752,9 +14603,9 @@ func (a *OpenTracingAppLayer) SearchChannelsUserNotIn(c request.CTX, teamID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchChannelsUserNotIn") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14774,9 +14625,9 @@ func (a *OpenTracingAppLayer) SearchEmoji(name string, prefixOnly bool, limit in span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchEmoji") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14796,9 +14647,9 @@ func (a *OpenTracingAppLayer) SearchEngine() *searchengine.Broker { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchEngine") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14813,9 +14664,9 @@ func (a *OpenTracingAppLayer) SearchFilesInTeamForUser(c *request.Context, terms span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchFilesInTeamForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14835,9 +14686,9 @@ func (a *OpenTracingAppLayer) SearchGroupChannels(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchGroupChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14857,9 +14708,9 @@ func (a *OpenTracingAppLayer) SearchPostsForUser(c *request.Context, terms strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchPostsForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14879,9 +14730,9 @@ func (a *OpenTracingAppLayer) SearchPostsInTeam(teamID string, paramsList []*mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchPostsInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14901,9 +14752,9 @@ func (a *OpenTracingAppLayer) SearchPrivateTeams(searchOpts *model.TeamSearch) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchPrivateTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14923,9 +14774,9 @@ func (a *OpenTracingAppLayer) SearchPublicTeams(searchOpts *model.TeamSearch) ([ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchPublicTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14945,9 +14796,9 @@ func (a *OpenTracingAppLayer) SearchUserAccessTokens(term string) ([]*model.User span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUserAccessTokens") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14967,9 +14818,9 @@ func (a *OpenTracingAppLayer) SearchUsers(props *model.UserSearch, options *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -14989,9 +14840,9 @@ func (a *OpenTracingAppLayer) SearchUsersInChannel(channelID string, term string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersInChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15011,9 +14862,9 @@ func (a *OpenTracingAppLayer) SearchUsersInGroup(groupID string, term string, op span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersInGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15033,9 +14884,9 @@ func (a *OpenTracingAppLayer) SearchUsersInTeam(teamID string, term string, opti span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15055,9 +14906,9 @@ func (a *OpenTracingAppLayer) SearchUsersNotInChannel(teamID string, channelID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersNotInChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15077,9 +14928,9 @@ func (a *OpenTracingAppLayer) SearchUsersNotInGroup(groupID string, term string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersNotInGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15099,9 +14950,9 @@ func (a *OpenTracingAppLayer) SearchUsersNotInTeam(notInTeamId string, term stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersNotInTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15121,9 +14972,9 @@ func (a *OpenTracingAppLayer) SearchUsersWithoutTeam(term string, options *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SearchUsersWithoutTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15143,9 +14994,9 @@ func (a *OpenTracingAppLayer) SendAckToPushProxy(ack *model.PushNotificationAck) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAckToPushProxy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15165,9 +15016,9 @@ func (a *OpenTracingAppLayer) SendAutoResponse(c request.CTX, channel *model.Cha span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponse") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15187,9 +15038,9 @@ func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(c request.CTX, channel span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendAutoResponseIfNecessary") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15209,9 +15060,9 @@ func (a *OpenTracingAppLayer) SendDelinquencyEmail(emailToSend model.Delinquency span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDelinquencyEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15231,9 +15082,9 @@ func (a *OpenTracingAppLayer) SendEmailVerification(user *model.User, newEmail s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEmailVerification") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15253,9 +15104,9 @@ func (a *OpenTracingAppLayer) SendEphemeralPost(c request.CTX, userID string, po span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEphemeralPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15270,9 +15121,9 @@ func (a *OpenTracingAppLayer) SendNoCardPaymentFailedEmail() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendNoCardPaymentFailedEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15292,9 +15143,9 @@ func (a *OpenTracingAppLayer) SendNotifications(c request.CTX, post *model.Post, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendNotifications") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15314,9 +15165,9 @@ func (a *OpenTracingAppLayer) SendNotifyAdminPosts(c *request.Context, workspace span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendNotifyAdminPosts") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15336,9 +15187,9 @@ func (a *OpenTracingAppLayer) SendPasswordReset(email string, siteURL string) (b span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendPasswordReset") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15358,9 +15209,9 @@ func (a *OpenTracingAppLayer) SendPaymentFailedEmail(failedPayment *model.Failed span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendPaymentFailedEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15380,9 +15231,9 @@ func (a *OpenTracingAppLayer) SendTestPushNotification(deviceID string) string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendTestPushNotification") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15397,9 +15248,9 @@ func (a *OpenTracingAppLayer) SendUpgradeConfirmationEmail() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendUpgradeConfirmationEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15419,9 +15270,9 @@ func (a *OpenTracingAppLayer) ServeInterPluginRequest(w http.ResponseWriter, r * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ServeInterPluginRequest") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15434,9 +15285,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionTo(session model.Session, perm span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionTo") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15451,9 +15302,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToAny(session model.Session, p span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToAny") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15468,9 +15319,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToCategory(c request.CTX, sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToCategory") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15485,9 +15336,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannel(c request.CTX, sessi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15502,9 +15353,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannelByPost(session model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToChannelByPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15519,9 +15370,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToChannels(c request.CTX, sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15536,9 +15387,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToCreateJob(session model.Sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToCreateJob") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15553,9 +15404,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToGroup(session model.Session, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15570,9 +15421,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToManageBot(session model.Sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToManageBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15592,9 +15443,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToReadJob(session model.Sessio span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToReadJob") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15609,9 +15460,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToTeam(session model.Session, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15626,9 +15477,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToTeams(c request.CTX, session span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToTeams") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15643,9 +15494,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToUser(session model.Session, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15660,9 +15511,9 @@ func (a *OpenTracingAppLayer) SessionHasPermissionToUserOrBot(session model.Sess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionHasPermissionToUserOrBot") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15677,9 +15528,9 @@ func (a *OpenTracingAppLayer) SessionIsRegistered(session model.Session) bool { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SessionIsRegistered") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15694,9 +15545,9 @@ func (a *OpenTracingAppLayer) SetActiveChannel(c request.CTX, userID string, cha span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetActiveChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15716,9 +15567,9 @@ func (a *OpenTracingAppLayer) SetAutoResponderStatus(user *model.User, oldNotify span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetAutoResponderStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15731,9 +15582,9 @@ func (a *OpenTracingAppLayer) SetChannels(ch *app.Channels) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetChannels") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15746,9 +15597,9 @@ func (a *OpenTracingAppLayer) SetCustomStatus(c request.CTX, userID string, cs * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetCustomStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15768,9 +15619,9 @@ func (a *OpenTracingAppLayer) SetDefaultProfileImage(c request.CTX, user *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetDefaultProfileImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15790,9 +15641,9 @@ func (a *OpenTracingAppLayer) SetPhase2PermissionsMigrationStatus(isComplete boo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetPhase2PermissionsMigrationStatus") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15812,9 +15663,9 @@ func (a *OpenTracingAppLayer) SetPluginKey(pluginID string, key string, value [] span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetPluginKey") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15834,9 +15685,9 @@ func (a *OpenTracingAppLayer) SetPluginKeyWithExpiry(pluginID string, key string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetPluginKeyWithExpiry") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15856,9 +15707,9 @@ func (a *OpenTracingAppLayer) SetPluginKeyWithOptions(pluginID string, key strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetPluginKeyWithOptions") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15878,9 +15729,9 @@ func (a *OpenTracingAppLayer) SetPostReminder(postID string, userID string, targ span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetPostReminder") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15900,9 +15751,9 @@ func (a *OpenTracingAppLayer) SetProfileImage(c request.CTX, userID string, imag span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetProfileImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15922,9 +15773,9 @@ func (a *OpenTracingAppLayer) SetProfileImageFromFile(c request.CTX, userID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetProfileImageFromFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15944,9 +15795,9 @@ func (a *OpenTracingAppLayer) SetProfileImageFromMultiPartFile(c request.CTX, us span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetProfileImageFromMultiPartFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15966,9 +15817,9 @@ func (a *OpenTracingAppLayer) SetRemoteClusterLastPingAt(remoteClusterId string) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetRemoteClusterLastPingAt") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -15988,9 +15839,9 @@ func (a *OpenTracingAppLayer) SetSamlIdpCertificateFromMetadata(data []byte) *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetSamlIdpCertificateFromMetadata") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16010,9 +15861,9 @@ func (a *OpenTracingAppLayer) SetSearchEngine(se *searchengine.Broker) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetSearchEngine") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16025,9 +15876,9 @@ func (a *OpenTracingAppLayer) SetSessionExpireInHours(session *model.Session, ho span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetSessionExpireInHours") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16040,9 +15891,9 @@ func (a *OpenTracingAppLayer) SetStatusAwayIfNeeded(userID string, manual bool) span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusAwayIfNeeded") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16055,9 +15906,9 @@ func (a *OpenTracingAppLayer) SetStatusDoNotDisturb(userID string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusDoNotDisturb") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16070,9 +15921,9 @@ func (a *OpenTracingAppLayer) SetStatusDoNotDisturbTimed(userId string, endtime span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusDoNotDisturbTimed") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16085,9 +15936,9 @@ func (a *OpenTracingAppLayer) SetStatusLastActivityAt(userID string, activityAt span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusLastActivityAt") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16100,9 +15951,9 @@ func (a *OpenTracingAppLayer) SetStatusOffline(userID string, manual bool) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusOffline") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16115,9 +15966,9 @@ func (a *OpenTracingAppLayer) SetStatusOnline(userID string, manual bool) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusOnline") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16130,9 +15981,9 @@ func (a *OpenTracingAppLayer) SetStatusOutOfOffice(userID string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetStatusOutOfOffice") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16145,9 +15996,9 @@ func (a *OpenTracingAppLayer) SetTeamIcon(teamID string, imageData *multipart.Fi span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetTeamIcon") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16167,9 +16018,9 @@ func (a *OpenTracingAppLayer) SetTeamIconFromFile(team *model.Team, file io.Read span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetTeamIconFromFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16189,9 +16040,9 @@ func (a *OpenTracingAppLayer) SetTeamIconFromMultiPartFile(teamID string, file m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetTeamIconFromMultiPartFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16211,9 +16062,9 @@ func (a *OpenTracingAppLayer) SlackImport(c *request.Context, fileData multipart span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SlackImport") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16233,9 +16084,9 @@ func (a *OpenTracingAppLayer) SoftDeleteAllTeamsExcept(teamID string) *model.App span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SoftDeleteAllTeamsExcept") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16255,9 +16106,9 @@ func (a *OpenTracingAppLayer) SoftDeleteTeam(teamID string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SoftDeleteTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16277,9 +16128,9 @@ func (a *OpenTracingAppLayer) SubmitInteractiveDialog(c *request.Context, reques span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SubmitInteractiveDialog") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16299,9 +16150,9 @@ func (a *OpenTracingAppLayer) SwitchEmailToLdap(email string, password string, c span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchEmailToLdap") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16321,9 +16172,9 @@ func (a *OpenTracingAppLayer) SwitchEmailToOAuth(w http.ResponseWriter, r *http. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchEmailToOAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16343,9 +16194,9 @@ func (a *OpenTracingAppLayer) SwitchLdapToEmail(ldapPassword string, code string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchLdapToEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16365,9 +16216,9 @@ func (a *OpenTracingAppLayer) SwitchOAuthToEmail(email string, password string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SwitchOAuthToEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16387,9 +16238,9 @@ func (a *OpenTracingAppLayer) SyncLdap(includeRemovedMembers bool) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SyncLdap") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16402,9 +16253,9 @@ func (a *OpenTracingAppLayer) SyncPlugins() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SyncPlugins") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16424,9 +16275,9 @@ func (a *OpenTracingAppLayer) SyncRolesAndMembership(c request.CTX, syncableID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SyncRolesAndMembership") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16439,9 +16290,9 @@ func (a *OpenTracingAppLayer) SyncSyncableRoles(syncableID string, syncableType span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SyncSyncableRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16461,9 +16312,9 @@ func (a *OpenTracingAppLayer) TeamMembersMinusGroupMembers(teamID string, groupI span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TeamMembersMinusGroupMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16483,9 +16334,9 @@ func (a *OpenTracingAppLayer) TeamMembersToAdd(since int64, teamID *string, incl span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TeamMembersToAdd") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16505,9 +16356,9 @@ func (a *OpenTracingAppLayer) TeamMembersToRemove(teamID *string) ([]*model.Team span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TeamMembersToRemove") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16527,9 +16378,9 @@ func (a *OpenTracingAppLayer) TelemetryId() string { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TelemetryId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16544,9 +16395,9 @@ func (a *OpenTracingAppLayer) TestElasticsearch(cfg *model.Config) *model.AppErr span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestElasticsearch") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16566,9 +16417,9 @@ func (a *OpenTracingAppLayer) TestEmail(userID string, cfg *model.Config) *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16588,9 +16439,9 @@ func (a *OpenTracingAppLayer) TestFileStoreConnection() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestFileStoreConnection") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16610,9 +16461,9 @@ func (a *OpenTracingAppLayer) TestFileStoreConnectionWithConfig(cfg *model.FileS span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestFileStoreConnectionWithConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16632,9 +16483,9 @@ func (a *OpenTracingAppLayer) TestLdap() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestLdap") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16654,9 +16505,9 @@ func (a *OpenTracingAppLayer) TestSiteURL(siteURL string) *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TestSiteURL") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16676,9 +16527,9 @@ func (a *OpenTracingAppLayer) ToggleMuteChannel(c request.CTX, channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ToggleMuteChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16698,9 +16549,9 @@ func (a *OpenTracingAppLayer) TotalWebsocketConnections() int { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TotalWebsocketConnections") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16715,9 +16566,9 @@ func (a *OpenTracingAppLayer) TriggerWebhook(c request.CTX, payload *model.Outgo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.TriggerWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16730,9 +16581,9 @@ func (a *OpenTracingAppLayer) UnregisterPluginCommand(pluginID string, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UnregisterPluginCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16745,9 +16596,9 @@ func (a *OpenTracingAppLayer) UpdateActive(c request.CTX, user *model.User, acti span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateActive") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16767,9 +16618,9 @@ func (a *OpenTracingAppLayer) UpdateBotActive(c request.CTX, botUserId string, a span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateBotActive") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16789,9 +16640,9 @@ func (a *OpenTracingAppLayer) UpdateBotOwner(botUserId string, newOwnerId string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateBotOwner") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16811,9 +16662,9 @@ func (a *OpenTracingAppLayer) UpdateChannel(c request.CTX, channel *model.Channe span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16833,9 +16684,9 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberNotifyProps(c request.CTX, data span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberNotifyProps") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16855,9 +16706,9 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberRoles(c request.CTX, channelID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16877,9 +16728,9 @@ func (a *OpenTracingAppLayer) UpdateChannelMemberSchemeRoles(c request.CTX, chan span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelMemberSchemeRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16899,9 +16750,9 @@ func (a *OpenTracingAppLayer) UpdateChannelPrivacy(c request.CTX, oldChannel *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelPrivacy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16921,9 +16772,9 @@ func (a *OpenTracingAppLayer) UpdateChannelScheme(c request.CTX, channel *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateChannelScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16943,9 +16794,9 @@ func (a *OpenTracingAppLayer) UpdateCommand(oldCmd *model.Command, updatedCmd *m span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateCommand") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16965,9 +16816,9 @@ func (a *OpenTracingAppLayer) UpdateConfig(f func(*model.Config)) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateConfig") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16980,9 +16831,9 @@ func (a *OpenTracingAppLayer) UpdateDNDStatusOfUsers() { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateDNDStatusOfUsers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -16995,9 +16846,9 @@ func (a *OpenTracingAppLayer) UpdateEphemeralPost(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateEphemeralPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17012,9 +16863,9 @@ func (a *OpenTracingAppLayer) UpdateExpiredDNDStatuses() ([]*model.Status, error span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateExpiredDNDStatuses") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17034,9 +16885,9 @@ func (a *OpenTracingAppLayer) UpdateGroup(group *model.Group) (*model.Group, *mo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17056,9 +16907,9 @@ func (a *OpenTracingAppLayer) UpdateGroupSyncable(groupSyncable *model.GroupSync span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateGroupSyncable") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17078,9 +16929,9 @@ func (a *OpenTracingAppLayer) UpdateHashedPassword(user *model.User, newHashedPa span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateHashedPassword") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17100,9 +16951,9 @@ func (a *OpenTracingAppLayer) UpdateHashedPasswordByUserId(userID string, newHas span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateHashedPasswordByUserId") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17122,9 +16973,9 @@ func (a *OpenTracingAppLayer) UpdateIncomingWebhook(oldHook *model.IncomingWebho span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateIncomingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17144,9 +16995,9 @@ func (a *OpenTracingAppLayer) UpdateLastActivityAtIfNeeded(session model.Session span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateLastActivityAtIfNeeded") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17159,9 +17010,9 @@ func (a *OpenTracingAppLayer) UpdateMfa(c request.CTX, activate bool, userID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateMfa") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17181,9 +17032,9 @@ func (a *OpenTracingAppLayer) UpdateMobileAppBadge(userID string) { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateMobileAppBadge") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17196,9 +17047,9 @@ func (a *OpenTracingAppLayer) UpdateOAuthApp(oldApp *model.OAuthApp, updatedApp span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthApp") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17218,9 +17069,9 @@ func (a *OpenTracingAppLayer) UpdateOAuthUserAttrs(userData io.Reader, user *mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOAuthUserAttrs") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17240,9 +17091,9 @@ func (a *OpenTracingAppLayer) UpdateOutgoingWebhook(c request.CTX, oldHook *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateOutgoingWebhook") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17262,9 +17113,9 @@ func (a *OpenTracingAppLayer) UpdatePassword(user *model.User, newPassword strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePassword") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17284,9 +17135,9 @@ func (a *OpenTracingAppLayer) UpdatePasswordAsUser(c request.CTX, userID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePasswordAsUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17306,9 +17157,9 @@ func (a *OpenTracingAppLayer) UpdatePasswordByUserIdSendEmail(c request.CTX, use span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePasswordByUserIdSendEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17328,9 +17179,9 @@ func (a *OpenTracingAppLayer) UpdatePasswordSendEmail(c request.CTX, user *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePasswordSendEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17350,9 +17201,9 @@ func (a *OpenTracingAppLayer) UpdatePost(c *request.Context, post *model.Post, s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17372,9 +17223,9 @@ func (a *OpenTracingAppLayer) UpdatePreferences(userID string, preferences model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePreferences") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17394,9 +17245,9 @@ func (a *OpenTracingAppLayer) UpdateProductNotices() *model.AppError { span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateProductNotices") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17416,9 +17267,9 @@ func (a *OpenTracingAppLayer) UpdateRemoteCluster(rc *model.RemoteCluster) (*mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateRemoteCluster") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17438,9 +17289,9 @@ func (a *OpenTracingAppLayer) UpdateRemoteClusterTopics(remoteClusterId string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateRemoteClusterTopics") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17460,9 +17311,9 @@ func (a *OpenTracingAppLayer) UpdateRole(role *model.Role) (*model.Role, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateRole") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17482,9 +17333,9 @@ func (a *OpenTracingAppLayer) UpdateScheme(scheme *model.Scheme) (*model.Scheme, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17504,9 +17355,9 @@ func (a *OpenTracingAppLayer) UpdateSharedChannel(sc *model.SharedChannel) (*mod span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSharedChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17526,9 +17377,9 @@ func (a *OpenTracingAppLayer) UpdateSharedChannelRemoteCursor(id string, cursor span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSharedChannelRemoteCursor") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17548,9 +17399,9 @@ func (a *OpenTracingAppLayer) UpdateSidebarCategories(c request.CTX, userID stri span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSidebarCategories") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17570,9 +17421,9 @@ func (a *OpenTracingAppLayer) UpdateSidebarCategoryOrder(c request.CTX, userID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateSidebarCategoryOrder") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17592,9 +17443,9 @@ func (a *OpenTracingAppLayer) UpdateTeam(team *model.Team) (*model.Team, *model. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateTeam") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17614,9 +17465,9 @@ func (a *OpenTracingAppLayer) UpdateTeamMemberRoles(teamID string, userID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateTeamMemberRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17636,9 +17487,9 @@ func (a *OpenTracingAppLayer) UpdateTeamMemberSchemeRoles(teamID string, userID span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateTeamMemberSchemeRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17658,9 +17509,9 @@ func (a *OpenTracingAppLayer) UpdateTeamPrivacy(teamID string, teamType string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateTeamPrivacy") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17680,9 +17531,9 @@ func (a *OpenTracingAppLayer) UpdateTeamScheme(team *model.Team) (*model.Team, * span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateTeamScheme") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17702,9 +17553,9 @@ func (a *OpenTracingAppLayer) UpdateThreadFollowForUser(userID string, teamID st span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadFollowForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17724,9 +17575,9 @@ func (a *OpenTracingAppLayer) UpdateThreadFollowForUserFromChannelAdd(c request. span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadFollowForUserFromChannelAdd") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17746,9 +17597,9 @@ func (a *OpenTracingAppLayer) UpdateThreadReadForUser(c request.CTX, currentSess span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadReadForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17768,9 +17619,9 @@ func (a *OpenTracingAppLayer) UpdateThreadReadForUserByPost(c request.CTX, curre span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadReadForUserByPost") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17790,9 +17641,9 @@ func (a *OpenTracingAppLayer) UpdateThreadsReadForUser(userID string, teamID str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateThreadsReadForUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17812,9 +17663,9 @@ func (a *OpenTracingAppLayer) UpdateUser(c request.CTX, user *model.User, sendNo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17834,9 +17685,9 @@ func (a *OpenTracingAppLayer) UpdateUserActive(c request.CTX, userID string, act span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserActive") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17856,9 +17707,9 @@ func (a *OpenTracingAppLayer) UpdateUserAsUser(c request.CTX, user *model.User, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserAsUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17878,9 +17729,9 @@ func (a *OpenTracingAppLayer) UpdateUserAuth(userID string, userAuth *model.User span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserAuth") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17900,9 +17751,9 @@ func (a *OpenTracingAppLayer) UpdateUserRoles(c request.CTX, userID string, newR span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserRoles") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17922,9 +17773,9 @@ func (a *OpenTracingAppLayer) UpdateUserRolesWithUser(c request.CTX, user *model span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateUserRolesWithUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17944,9 +17795,9 @@ func (a *OpenTracingAppLayer) UpdateViewedProductNotices(userID string, noticeId span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateViewedProductNotices") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17966,9 +17817,9 @@ func (a *OpenTracingAppLayer) UpdateViewedProductNoticesForNewUser(userID string span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateViewedProductNoticesForNewUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17981,9 +17832,9 @@ func (a *OpenTracingAppLayer) UpdateWebConnUserActivity(session model.Session, a span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateWebConnUserActivity") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -17996,9 +17847,9 @@ func (a *OpenTracingAppLayer) UploadData(c *request.Context, us *model.UploadSes span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadData") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18018,9 +17869,9 @@ func (a *OpenTracingAppLayer) UploadEmojiImage(id string, imageData *multipart.F span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadEmojiImage") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18040,9 +17891,9 @@ func (a *OpenTracingAppLayer) UploadFile(c request.CTX, data []byte, channelID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18062,9 +17913,9 @@ func (a *OpenTracingAppLayer) UploadFileX(c *request.Context, channelID string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UploadFileX") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18084,9 +17935,9 @@ func (a *OpenTracingAppLayer) UpsertGroupMember(groupID string, userID string) ( span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpsertGroupMember") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18106,9 +17957,9 @@ func (a *OpenTracingAppLayer) UpsertGroupMembers(groupID string, userIDs []strin span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpsertGroupMembers") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18128,9 +17979,9 @@ func (a *OpenTracingAppLayer) UpsertGroupSyncable(groupSyncable *model.GroupSync span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpsertGroupSyncable") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18150,9 +18001,9 @@ func (a *OpenTracingAppLayer) UserAlreadyNotifiedOnRequiredFeature(user string, span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UserAlreadyNotifiedOnRequiredFeature") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18167,9 +18018,9 @@ func (a *OpenTracingAppLayer) UserCanSeeOtherUser(userID string, otherUserId str span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UserCanSeeOtherUser") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18189,9 +18040,9 @@ func (a *OpenTracingAppLayer) UserIsInAdminRoleGroup(userID string, syncableID s span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UserIsInAdminRoleGroup") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18211,9 +18062,9 @@ func (a *OpenTracingAppLayer) VerifyEmailFromToken(c request.CTX, userSuppliedTo span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyEmailFromToken") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18233,9 +18084,9 @@ func (a *OpenTracingAppLayer) VerifyPlugin(plugin io.ReadSeeker, signature io.Re span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyPlugin") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18255,9 +18106,9 @@ func (a *OpenTracingAppLayer) VerifyUserEmail(userID string, email string) *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyUserEmail") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18277,9 +18128,9 @@ func (a *OpenTracingAppLayer) ViewChannel(c request.CTX, view *model.ChannelView span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ViewChannel") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() @@ -18299,9 +18150,9 @@ func (a *OpenTracingAppLayer) WriteFile(fr io.Reader, path string) (int64, *mode span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.WriteFile") a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) + a.app.Srv().Store().SetContext(newCtx) defer func() { - a.app.Srv().Store.SetContext(origCtx) + a.app.Srv().Store().SetContext(origCtx) a.ctx = origCtx }() diff --git a/app/options.go b/app/options.go index 842040e176..15725bf4c3 100644 --- a/app/options.go +++ b/app/options.go @@ -4,8 +4,6 @@ package app import ( - "github.com/pkg/errors" - "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/einterfaces" @@ -23,22 +21,15 @@ type Option func(s *Server) error // The override parameter must be either a store.Store or func(App) store.Store(). func StoreOverride(override any) Option { return func(s *Server) error { - switch o := override.(type) { - case store.Store: - s.newStore = func() (store.Store, error) { - return o, nil - } - return nil + s.platformOptions = append(s.platformOptions, platform.StoreOverride(override)) + return nil + } +} - case func(*Server) store.Store: - s.newStore = func() (store.Store, error) { - return o(s), nil - } - return nil - - default: - return errors.New("invalid StoreOverride") - } +func StoreOverrideWithCache(override store.Store) Option { + return func(s *Server) error { + s.platformOptions = append(s.platformOptions, platform.StoreOverrideWithCache(override)) + return nil } } @@ -48,26 +39,7 @@ func StoreOverride(override any) Option { // config loaded from the dsn on top of the normal defaults func Config(dsn string, readOnly bool, configDefaults *model.Config) Option { return func(s *Server) error { - configStore, err := config.NewStoreFromDSN(dsn, readOnly, configDefaults, true) - if err != nil { - return errors.Wrap(err, "failed to apply Config option") - } - - platformCfg := platform.ServiceConfig{ - ConfigStore: configStore, - StartMetrics: s.startMetrics, - Cluster: s.Cluster, - } - if metricsInterface != nil { - platformCfg.Metrics = metricsInterface(s, *configStore.Get().SqlSettings.DriverName, *configStore.Get().SqlSettings.DataSource) - } - - ps, sErr := platform.New(platformCfg) - if sErr != nil { - return errors.Wrap(sErr, "failed to initialize platform") - } - s.platform = ps - + s.platformOptions = append(s.platformOptions, platform.Config(dsn, readOnly, configDefaults)) return nil } } @@ -75,21 +47,7 @@ func Config(dsn string, readOnly bool, configDefaults *model.Config) Option { // ConfigStore applies the given config store, typically to replace the traditional sources with a memory store for testing. func ConfigStore(configStore *config.Store) Option { return func(s *Server) error { - platformCfg := platform.ServiceConfig{ - ConfigStore: configStore, - StartMetrics: s.startMetrics, - Cluster: s.Cluster, - } - if metricsInterface != nil { - platformCfg.Metrics = metricsInterface(s, *configStore.Get().SqlSettings.DriverName, *configStore.Get().SqlSettings.DataSource) - } - - ps, sErr := platform.New(platformCfg) - if sErr != nil { - return errors.Wrap(sErr, "failed to initialize platform") - } - s.platform = ps - + s.platformOptions = append(s.platformOptions, platform.ConfigStore(configStore)) return nil } } @@ -114,26 +72,25 @@ func JoinCluster(s *Server) error { } func StartMetrics(s *Server) error { - s.startMetrics = true - + s.platformOptions = append(s.platformOptions, platform.StartMetrics()) return nil } -func StartSearchEngine(s *Server) error { - s.startSearchEngine = true - - return nil +func WithLicense(license *model.License) Option { + return func(s *Server) error { + s.platformOptions = append(s.platformOptions, func(p *platform.PlatformService) error { + p.SetLicense(license) + return nil + }) + return nil + } } // SetLogger requires platform service to be initialized before calling. // If not, logger should be set after platform service are initialized. func SetLogger(logger *mlog.Logger) Option { return func(s *Server) error { - if s.platform == nil { - return errors.New("platform service is not initialized") - } - - s.platform.SetLogger(logger) + s.platformOptions = append(s.platformOptions, platform.SetLogger(logger)) return nil } } @@ -155,9 +112,9 @@ func ServerConnector(ch *Channels) AppOption { } } -func setCluster(cluster einterfaces.ClusterInterface) Option { +func SetCluster(impl einterfaces.ClusterInterface) Option { return func(s *Server) error { - s.Cluster = cluster + s.platformOptions = append(s.platformOptions, platform.SetCluster(impl)) return nil } } diff --git a/app/permissions.go b/app/permissions.go index 999fdbd189..a992d0a952 100644 --- a/app/permissions.go +++ b/app/permissions.go @@ -39,52 +39,52 @@ func (s *permissionsServiceWrapper) HasPermissionToChannel(askingUserID string, func (a *App) ResetPermissionsSystem() *model.AppError { // Reset all Teams to not have a scheme. - if err := a.Srv().Store.Team().ResetAllTeamSchemes(); err != nil { + if err := a.Srv().Store().Team().ResetAllTeamSchemes(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.team.reset_all_team_schemes.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Reset all Channels to not have a scheme. - if err := a.Srv().Store.Channel().ResetAllChannelSchemes(); err != nil { + if err := a.Srv().Store().Channel().ResetAllChannelSchemes(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.channel.reset_all_channel_schemes.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Reset all Custom Role assignments to Users. - if err := a.Srv().Store.User().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store().User().ClearAllCustomRoleAssignments(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.user.clear_all_custom_role_assignments.select.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Reset all Custom Role assignments to TeamMembers. - if err := a.Srv().Store.Team().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store().Team().ClearAllCustomRoleAssignments(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.team.clear_all_custom_role_assignments.select.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Reset all Custom Role assignments to ChannelMembers. - if err := a.Srv().Store.Channel().ClearAllCustomRoleAssignments(); err != nil { + if err := a.Srv().Store().Channel().ClearAllCustomRoleAssignments(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.channel.clear_all_custom_role_assignments.select.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Purge all schemes from the database. - if err := a.Srv().Store.Scheme().PermanentDeleteAll(); err != nil { + if err := a.Srv().Store().Scheme().PermanentDeleteAll(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.scheme.permanent_delete_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Purge all roles from the database. - if err := a.Srv().Store.Role().PermanentDeleteAll(); err != nil { + if err := a.Srv().Store().Role().PermanentDeleteAll(); err != nil { return model.NewAppError("ResetPermissionsSystem", "app.role.permanent_delete_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Remove the "System" table entry that marks the advanced permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(model.AdvancedPermissionsMigrationKey); err != nil { + if _, err := a.Srv().Store().System().PermanentDeleteByName(model.AdvancedPermissionsMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Remove the "System" table entry that marks the emoji permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(EmojisPermissionsMigrationKey); err != nil { + if _, err := a.Srv().Store().System().PermanentDeleteByName(EmojisPermissionsMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // Remove the "System" table entry that marks the guest roles permissions migration as done. - if _, err := a.Srv().Store.System().PermanentDeleteByName(GuestRolesCreationMigrationKey); err != nil { + if _, err := a.Srv().Store().System().PermanentDeleteByName(GuestRolesCreationMigrationKey); err != nil { return model.NewAppError("ResetPermissionSystem", "app.system.permanent_delete_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/permissions_migrations.go b/app/permissions_migrations.go index 862a02b207..613adc927f 100644 --- a/app/permissions_migrations.go +++ b/app/permissions_migrations.go @@ -158,7 +158,7 @@ func applyPermissionsMap(role *model.Role, roleMap map[string]map[string]bool, m } func (s *Server) doPermissionsMigration(key string, migrationMap permissionsMap, roles []*model.Role) *model.AppError { - if _, err := s.Store.System().GetByName(key); err == nil { + if _, err := s.Store().System().GetByName(key); err == nil { return nil } @@ -172,7 +172,7 @@ func (s *Server) doPermissionsMigration(key string, migrationMap permissionsMap, for _, role := range roles { role.Permissions = applyPermissionsMap(role, roleMap, migrationMap) - if _, err := s.Store.Role().Save(role); err != nil { + if _, err := s.Store().Role().Save(role); err != nil { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): @@ -183,7 +183,7 @@ func (s *Server) doPermissionsMigration(key string, migrationMap permissionsMap, } } - if err := s.Store.System().SaveOrUpdate(&model.System{Name: key, Value: "true"}); err != nil { + if err := s.Store().System().SaveOrUpdate(&model.System{Name: key, Value: "true"}); err != nil { return model.NewAppError("doPermissionsMigration", "app.system.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return nil @@ -1034,7 +1034,7 @@ func (s *Server) doPermissionsMigrations() error { {Key: model.MigrationKeyAddPlayboosksManageRolesPermissions, Migration: a.getPlaybooksPermissionsAddManageRoles}, } - roles, err := s.Store.Role().GetAll() + roles, err := s.Store().Role().GetAll() if err != nil { return err } diff --git a/app/permissions_test.go b/app/permissions_test.go index 08b6b58f18..cdfef0165e 100644 --- a/app/permissions_test.go +++ b/app/permissions_test.go @@ -280,11 +280,11 @@ func TestMigration(t *testing.T) { func withMigrationMarkedComplete(th *TestHelper, f func()) { // Mark the migration as done. - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) - th.App.Srv().Store.System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().Save(&model.System{Name: model.MigrationKeyAdvancedPermissionsPhase2, Value: "true"}) // Un-mark the migration at the end of the test. defer func() { - th.App.Srv().Store.System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) + th.App.Srv().Store().System().PermanentDeleteByName(model.MigrationKeyAdvancedPermissionsPhase2) }() f() } diff --git a/app/platform/busy.go b/app/platform/busy.go new file mode 100644 index 0000000000..f3cbf5f64a --- /dev/null +++ b/app/platform/busy.go @@ -0,0 +1,155 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "encoding/json" + "fmt" + "sync" + "sync/atomic" + "time" + + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/model" +) + +const ( + TimestampFormat = "Mon Jan 2 15:04:05 -0700 MST 2006" +) + +// Busy represents the busy state of the server. A server marked busy +// will have non-critical services disabled. If a Cluster is provided +// any changes will be propagated to each node. +type Busy struct { + busy int32 // protected via atomic for fast IsBusy calls + mux sync.RWMutex + timer *time.Timer + expires time.Time + + cluster einterfaces.ClusterInterface +} + +// NewBusy creates a new Busy instance with optional cluster which will +// be notified of busy state changes. +func NewBusy(cluster einterfaces.ClusterInterface) *Busy { + return &Busy{cluster: cluster} +} + +// IsBusy returns true if the server has been marked as busy. +func (b *Busy) IsBusy() bool { + if b == nil { + return false + } + return atomic.LoadInt32(&b.busy) != 0 +} + +// Set marks the server as busy for dur duration and notifies cluster nodes. +func (b *Busy) Set(dur time.Duration) { + b.mux.Lock() + defer b.mux.Unlock() + + // minimum 1 second + if dur < (time.Second * 1) { + dur = time.Second * 1 + } + + b.setWithoutNotify(dur) + + if b.cluster != nil { + sbs := &model.ServerBusyState{Busy: true, Expires: b.expires.Unix(), ExpiresTS: b.expires.UTC().Format(TimestampFormat)} + b.notifyServerBusyChange(sbs) + } +} + +// must hold mutex +func (b *Busy) setWithoutNotify(dur time.Duration) { + b.clearWithoutNotify() + atomic.StoreInt32(&b.busy, 1) + b.expires = time.Now().Add(dur) + b.timer = time.AfterFunc(dur, func() { + b.mux.Lock() + b.clearWithoutNotify() + b.mux.Unlock() + }) +} + +// ClearBusy marks the server as not busy and notifies cluster nodes. +func (b *Busy) Clear() { + b.mux.Lock() + defer b.mux.Unlock() + + b.clearWithoutNotify() + + if b.cluster != nil { + sbs := &model.ServerBusyState{Busy: false, Expires: time.Time{}.Unix(), ExpiresTS: ""} + b.notifyServerBusyChange(sbs) + } +} + +// must hold mutex +func (b *Busy) clearWithoutNotify() { + if b.timer != nil { + b.timer.Stop() // don't drain timer.C channel for AfterFunc timers. + } + b.timer = nil + b.expires = time.Time{} + atomic.StoreInt32(&b.busy, 0) +} + +// Expires returns the expected time that the server +// will be marked not busy. This expiry can be extended +// via additional calls to SetBusy. +func (b *Busy) Expires() time.Time { + b.mux.RLock() + defer b.mux.RUnlock() + return b.expires +} + +// notifyServerBusyChange informs all cluster members of a server busy state change. +func (b *Busy) notifyServerBusyChange(sbs *model.ServerBusyState) { + if b.cluster == nil { + return + } + buf, _ := json.Marshal(sbs) + msg := &model.ClusterMessage{ + Event: model.ClusterEventBusyStateChanged, + SendType: model.ClusterSendReliable, + WaitForAllToSend: true, + Data: buf, + } + b.cluster.SendClusterMessage(msg) +} + +// ClusterEventChanged is called when a CLUSTER_EVENT_BUSY_STATE_CHANGED is received. +func (b *Busy) ClusterEventChanged(sbs *model.ServerBusyState) { + b.mux.Lock() + defer b.mux.Unlock() + + if sbs.Busy { + expires := time.Unix(sbs.Expires, 0) + dur := time.Until(expires) + if dur > 0 { + b.setWithoutNotify(dur) + } + } else { + b.clearWithoutNotify() + } +} + +func (b *Busy) ToJSON() ([]byte, error) { + b.mux.RLock() + defer b.mux.RUnlock() + + sbs := &model.ServerBusyState{ + Busy: atomic.LoadInt32(&b.busy) != 0, + Expires: b.expires.Unix(), + ExpiresTS: b.expires.UTC().Format(TimestampFormat), + } + sbsJSON, jsonErr := json.Marshal(sbs) + if jsonErr != nil { + return []byte{}, fmt.Errorf("failed to encode server busy state to JSON: %w", jsonErr) + } + + return sbsJSON, nil +} diff --git a/app/platform/busy_test.go b/app/platform/busy_test.go new file mode 100644 index 0000000000..69695f56d4 --- /dev/null +++ b/app/platform/busy_test.go @@ -0,0 +1,148 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/model" +) + +func TestBusySet(t *testing.T) { + cluster := &ClusterMock{Busy: &Busy{}} + busy := NewBusy(cluster) + + isNotBusy := func() bool { + return !busy.IsBusy() + } + + require.False(t, busy.IsBusy()) + + busy.Set(time.Millisecond * 500) + require.True(t, busy.IsBusy()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) + + // should automatically expire after 500ms. + require.Eventually(t, isNotBusy, time.Second*15, time.Millisecond*100) + // allow a moment for cluster to sync. + require.Eventually(t, func() bool { return compareBusyState(t, busy, cluster.Busy) }, time.Second*15, time.Millisecond*20) + + // test set after auto expiry. + busy.Set(time.Second * 30) + require.True(t, busy.IsBusy()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) + expire := busy.Expires() + require.Greater(t, expire.Unix(), time.Now().Add(time.Second*10).Unix()) + + // test extending existing expiry + busy.Set(time.Minute * 5) + require.True(t, busy.IsBusy()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) + expire = busy.Expires() + require.Greater(t, expire.Unix(), time.Now().Add(time.Minute*2).Unix()) + + busy.Clear() + require.False(t, busy.IsBusy()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) +} + +func TestBusyExpires(t *testing.T) { + cluster := &ClusterMock{Busy: &Busy{}} + busy := NewBusy(cluster) + + isNotBusy := func() bool { + return !busy.IsBusy() + } + + // get expiry before it is set + expire := busy.Expires() + // should be time.Time zero value + require.Equal(t, time.Time{}.Unix(), expire.Unix()) + + // get expiry after it is set + busy.Set(time.Minute * 5) + expire = busy.Expires() + require.Greater(t, expire.Unix(), time.Now().Add(time.Minute*2).Unix()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) + + // get expiry after clear + busy.Clear() + expire = busy.Expires() + // should be time.Time zero value + require.Equal(t, time.Time{}.Unix(), expire.Unix()) + require.True(t, compareBusyState(t, busy, cluster.Busy)) + + // get expiry after auto-expire + busy.Set(time.Millisecond * 100) + require.Eventually(t, isNotBusy, time.Second*5, time.Millisecond*20) + expire = busy.Expires() + // should be time.Time zero value + require.Equal(t, time.Time{}.Unix(), expire.Unix()) + // allow a moment for cluster to sync + require.Eventually(t, func() bool { return compareBusyState(t, busy, cluster.Busy) }, time.Second*15, time.Millisecond*20) +} + +func TestBusyRace(t *testing.T) { + cluster := &ClusterMock{Busy: &Busy{}} + busy := NewBusy(cluster) + + busy.Set(500 * time.Millisecond) + + // We are sleeping in order to let the race trigger. + time.Sleep(time.Second) +} + +func compareBusyState(t *testing.T, busy1 *Busy, busy2 *Busy) bool { + t.Helper() + if busy1.IsBusy() != busy2.IsBusy() { + busy1JSON, _ := busy1.ToJSON() + busy2JSON, _ := busy2.ToJSON() + t.Logf("busy1:%s; busy2:%s\n", busy1JSON, busy2JSON) + return false + } + if busy1.Expires().Unix() != busy2.Expires().Unix() { + busy1JSON, _ := busy1.ToJSON() + busy2JSON, _ := busy2.ToJSON() + t.Logf("busy1:%s; busy2:%s\n", busy1JSON, busy2JSON) + return false + } + return true +} + +// ClusterMock simulates the busy state of a cluster. +type ClusterMock struct { + Busy *Busy +} + +func (c *ClusterMock) SendClusterMessage(msg *model.ClusterMessage) { + var sbs model.ServerBusyState + json.Unmarshal(msg.Data, &sbs) + c.Busy.ClusterEventChanged(&sbs) +} + +func (c *ClusterMock) SendClusterMessageToNode(nodeID string, msg *model.ClusterMessage) error { + return nil +} + +func (c *ClusterMock) StartInterNodeCommunication() {} +func (c *ClusterMock) StopInterNodeCommunication() {} +func (c *ClusterMock) RegisterClusterMessageHandler(event model.ClusterEvent, crm einterfaces.ClusterMessageHandler) { +} +func (c *ClusterMock) GetClusterId() string { return "cluster_mock" } +func (c *ClusterMock) IsLeader() bool { return false } +func (c *ClusterMock) GetMyClusterInfo() *model.ClusterInfo { return nil } +func (c *ClusterMock) GetClusterInfos() []*model.ClusterInfo { return nil } +func (c *ClusterMock) NotifyMsg(buf []byte) {} +func (c *ClusterMock) GetClusterStats() ([]*model.ClusterStats, *model.AppError) { return nil, nil } +func (c *ClusterMock) GetLogs(page, perPage int) ([]string, *model.AppError) { return nil, nil } +func (c *ClusterMock) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { return nil, nil } +func (c *ClusterMock) ConfigChanged(previousConfig *model.Config, newConfig *model.Config, sendToOtherServer bool) *model.AppError { + return nil +} +func (c *ClusterMock) HealthScore() int { return 0 } diff --git a/app/platform/cluster.go b/app/platform/cluster.go index 4964c7d6f0..47722ba007 100644 --- a/app/platform/cluster.go +++ b/app/platform/cluster.go @@ -3,16 +3,250 @@ package platform -import "github.com/mattermost/mattermost-server/v6/einterfaces" +import ( + "errors" + "fmt" + "net/http" + + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/product" + "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store" +) + +// ensure cluster service wrapper implements `product.ClusterService` +var _ product.ClusterService = (*PlatformService)(nil) + +// Ensure KV store wrapper implements `product.KVStoreService` +var _ product.KVStoreService = (*PlatformService)(nil) + +func (ps *PlatformService) Cluster() einterfaces.ClusterInterface { + return ps.clusterIFace +} + +func (ps *PlatformService) NewClusterDiscoveryService() *ClusterDiscoveryService { + ds := &ClusterDiscoveryService{ + ClusterDiscovery: model.ClusterDiscovery{}, + platform: ps, + stop: make(chan bool), + } + + return ds +} func (ps *PlatformService) IsLeader() bool { - if ps.License() != nil && *ps.Config().ClusterSettings.Enable && ps.cluster != nil { - return ps.cluster.IsLeader() + if ps.License() != nil && *ps.Config().ClusterSettings.Enable && ps.clusterIFace != nil { + return ps.clusterIFace.IsLeader() } return true } -func (ps *PlatformService) SetCluster(impl einterfaces.ClusterInterface) { - ps.cluster = impl +func (ps *PlatformService) SetCluster(impl einterfaces.ClusterInterface) { //nolint:unused + ps.clusterIFace = impl +} + +func (ps *PlatformService) PublishPluginClusterEvent(productID string, ev model.PluginClusterEvent, opts model.PluginClusterEventSendOptions) error { + if ps.clusterIFace == nil { + return nil + } + + msg := &model.ClusterMessage{ + Event: model.ClusterEventPluginEvent, + SendType: opts.SendType, + WaitForAllToSend: false, + Props: map[string]string{ + "ProductID": productID, + "EventID": ev.Id, + }, + Data: ev.Data, + } + + // If TargetId is empty we broadcast to all other cluster nodes. + if opts.TargetId == "" { + ps.clusterIFace.SendClusterMessage(msg) + } else { + if err := ps.clusterIFace.SendClusterMessageToNode(opts.TargetId, msg); err != nil { + return fmt.Errorf("failed to send message to cluster node %q: %w", opts.TargetId, err) + } + } + + return nil +} + +func (ps *PlatformService) PublishWebSocketEvent(productID string, event string, payload map[string]any, broadcast *model.WebsocketBroadcast) { + ev := model.NewWebSocketEvent(fmt.Sprintf("custom_%v_%v", productID, event), "", "", "", nil, "") + ev = ev.SetBroadcast(broadcast).SetData(payload) + ps.Publish(ev) +} + +func (ps *PlatformService) SetPluginKeyWithOptions(productID string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) { + if err := options.IsValid(); err != nil { + mlog.Debug("Failed to set plugin key value with options", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + return false, err + } + + updated, err := ps.Store.Plugin().SetWithOptions(productID, key, value, options) + if err != nil { + mlog.Error("Failed to set plugin key value with options", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + var appErr *model.AppError + switch { + case errors.As(err, &appErr): + return false, appErr + default: + return false, model.NewAppError("SetPluginKeyWithOptions", "app.plugin_store.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + } + + // Clean up a previous entry using the hashed key, if it exists. + if err := ps.Store.Plugin().Delete(productID, getKeyHash(key)); err != nil { + mlog.Warn("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + } + + return updated, nil +} + +func (ps *PlatformService) KVGet(productID, key string) ([]byte, *model.AppError) { + if kv, err := ps.Store.Plugin().Get(productID, key); err == nil { + return kv.Value, nil + } else if nfErr := new(store.ErrNotFound); !errors.As(err, &nfErr) { + mlog.Error("Failed to query plugin key value", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + return nil, model.NewAppError("GetPluginKey", "app.plugin_store.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + // Lookup using the hashed version of the key for keys written prior to v5.6. + if kv, err := ps.Store.Plugin().Get(productID, getKeyHash(key)); err == nil { + return kv.Value, nil + } else if nfErr := new(store.ErrNotFound); !errors.As(err, &nfErr) { + mlog.Error("Failed to query plugin key value using hashed key", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + return nil, model.NewAppError("GetPluginKey", "app.plugin_store.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return nil, nil +} + +func (ps *PlatformService) KVDelete(productID, key string) *model.AppError { + if err := ps.Store.Plugin().Delete(productID, getKeyHash(key)); err != nil { + ps.logger.Error("Failed to delete plugin key value", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + // Also delete the key without hashing + if err := ps.Store.Plugin().Delete(productID, key); err != nil { + ps.logger.Error("Failed to delete plugin key value using hashed key", mlog.String("plugin_id", productID), mlog.String("key", key), mlog.Err(err)) + return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return nil +} + +func (ps *PlatformService) KVList(productID string, page, perPage int) ([]string, *model.AppError) { + data, err := ps.Store.Plugin().List(productID, page*perPage, perPage) + if err != nil { + ps.logger.Error("Failed to list plugin key values", mlog.Int("page", page), mlog.Int("perPage", perPage), mlog.Err(err)) + return nil, model.NewAppError("ListPluginKeys", "app.plugin_store.list.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return data, nil +} + +// Registers a given function to be called when the cluster leader may have changed. Returns a unique ID for the +// listener which can later be used to remove it. If clustering is not enabled in this build, the callback will never +// be called. +func (ps *PlatformService) AddClusterLeaderChangedListener(listener func()) string { + id := model.NewId() + ps.clusterLeaderListeners.Store(id, listener) + return id +} + +// Removes a listener function by the unique ID returned when AddConfigListener was called +func (ps *PlatformService) RemoveClusterLeaderChangedListener(id string) { + ps.clusterLeaderListeners.Delete(id) +} + +func (ps *PlatformService) InvokeClusterLeaderChangedListeners() { + ps.logger.Info("Cluster leader changed. Invoking ClusterLeaderChanged listeners.") + // This needs to be run in a separate goroutine otherwise a recursive lock happens + // because the listener function eventually ends up calling .IsLeader(). + // Fixing this would require the changed event to pass the leader directly, but that + // requires a lot of work. + ps.Go(func() { + ps.clusterLeaderListeners.Range(func(_, listener any) bool { + listener.(func())() + return true + }) + }) +} + +func (ps *PlatformService) Publish(message *model.WebSocketEvent) { + if ps.metricsImpl() != nil { + ps.metricsImpl().IncrementWebsocketEvent(message.EventType()) + } + + ps.PublishSkipClusterSend(message) + + if ps.clusterIFace != nil { + data, err := message.ToJSON() + if err != nil { + mlog.Warn("Failed to encode message to JSON", mlog.Err(err)) + } + cm := &model.ClusterMessage{ + Event: model.ClusterEventPublish, + SendType: model.ClusterSendBestEffort, + Data: data, + } + + if message.EventType() == model.WebsocketEventPosted || + message.EventType() == model.WebsocketEventPostEdited || + message.EventType() == model.WebsocketEventDirectAdded || + message.EventType() == model.WebsocketEventGroupAdded || + message.EventType() == model.WebsocketEventAddedToTeam || + message.GetBroadcast().ReliableClusterSend { + cm.SendType = model.ClusterSendReliable + } + + ps.clusterIFace.SendClusterMessage(cm) + } +} + +func (ps *PlatformService) PublishSkipClusterSend(event *model.WebSocketEvent) { + if event.GetBroadcast().UserId != "" { + hub := ps.GetHubForUserId(event.GetBroadcast().UserId) + if hub != nil { + hub.Broadcast(event) + } + } else { + for _, hub := range ps.hubs { + hub.Broadcast(event) + } + } + + // Notify shared channel sync service + ps.SharedChannelSyncHandler(event) +} + +func (ps *PlatformService) ListPluginKeys(pluginID string, page, perPage int) ([]string, *model.AppError) { + data, err := ps.Store.Plugin().List(pluginID, page*perPage, perPage) + if err != nil { + mlog.Error("Failed to list plugin key values", mlog.Int("page", page), mlog.Int("perPage", perPage), mlog.Err(err)) + return nil, model.NewAppError("ListPluginKeys", "app.plugin_store.list.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return data, nil +} + +func (ps *PlatformService) DeletePluginKey(pluginID string, key string) *model.AppError { + if err := ps.Store.Plugin().Delete(pluginID, getKeyHash(key)); err != nil { + mlog.Error("Failed to delete plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) + return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + // Also delete the key without hashing + if err := ps.Store.Plugin().Delete(pluginID, key); err != nil { + mlog.Error("Failed to delete plugin key value using hashed key", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) + return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return nil } diff --git a/app/platform/cluster_discovery.go b/app/platform/cluster_discovery.go new file mode 100644 index 0000000000..452e9dcdef --- /dev/null +++ b/app/platform/cluster_discovery.go @@ -0,0 +1,77 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "time" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +const ( + DiscoveryServiceWritePing = 60 * time.Second +) + +type ClusterDiscoveryService struct { + model.ClusterDiscovery + platform *PlatformService + stop chan bool +} + +func (cds *ClusterDiscoveryService) Start() { + err := cds.platform.Store.ClusterDiscovery().Cleanup() + if err != nil { + mlog.Warn("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err)) + } + + exists, err := cds.platform.Store.ClusterDiscovery().Exists(&cds.ClusterDiscovery) + if err != nil { + mlog.Warn("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) + } else if exists { + if _, err := cds.platform.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil { + mlog.Warn("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) + } + } + + if err := cds.platform.Store.ClusterDiscovery().Save(&cds.ClusterDiscovery); err != nil { + mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) + return + } + + go func() { + mlog.Debug("ClusterDiscoveryService ping writer started", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id)) + ticker := time.NewTicker(DiscoveryServiceWritePing) + defer func() { + ticker.Stop() + if _, err := cds.platform.Store.ClusterDiscovery().Delete(&cds.ClusterDiscovery); err != nil { + mlog.Warn("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) + } + mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id)) + }() + + for { + select { + case <-ticker.C: + if err := cds.platform.Store.ClusterDiscovery().SetLastPingAt(&cds.ClusterDiscovery); err != nil { + mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscoveryID", cds.ClusterDiscovery.Id), mlog.Err(err)) + } + case <-cds.stop: + return + } + } + }() +} + +func (cds *ClusterDiscoveryService) Stop() { + cds.stop <- true +} + +func (ps *PlatformService) GetClusterId() string { + if ps.Cluster() == nil { + return "" + } + + return ps.Cluster().GetClusterId() +} diff --git a/app/cluster_discovery_test.go b/app/platform/cluster_discovery_test.go similarity index 87% rename from app/cluster_discovery_test.go rename to app/platform/cluster_discovery_test.go index 050f289c56..b52739baab 100644 --- a/app/cluster_discovery_test.go +++ b/app/platform/cluster_discovery_test.go @@ -1,7 +1,7 @@ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. -package app +package platform import ( "testing" @@ -14,7 +14,7 @@ func TestClusterDiscoveryService(t *testing.T) { th := Setup(t) defer th.TearDown() - ds := th.App.NewClusterDiscoveryService() + ds := th.Service.NewClusterDiscoveryService() ds.Type = model.CDSTypeApp ds.ClusterName = "ClusterA" ds.AutoFillHostname() diff --git a/app/platform/cluster_handlers.go b/app/platform/cluster_handlers.go new file mode 100644 index 0000000000..3d0e3f74dc --- /dev/null +++ b/app/platform/cluster_handlers.go @@ -0,0 +1,177 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "bytes" + "encoding/json" + "fmt" + "runtime/debug" + + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +func (ps *PlatformService) RegisterClusterHandlers() { + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventPublish, ps.ClusterPublishHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventUpdateStatus, ps.ClusterUpdateStatusHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventInvalidateAllCaches, ps.ClusterInvalidateAllCachesHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, ps.clusterInvalidateCacheForChannelMembersNotifyPropHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForChannelByName, ps.clusterInvalidateCacheForChannelByNameHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUser, ps.clusterInvalidateCacheForUserHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventInvalidateCacheForUserTeams, ps.clusterInvalidateCacheForUserTeamsHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventBusyStateChanged, ps.clusterBusyStateChgHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForUser, ps.clusterClearSessionCacheForUserHandler) + ps.clusterIFace.RegisterClusterMessageHandler(model.ClusterEventClearSessionCacheForAllUsers, ps.clusterClearSessionCacheForAllUsersHandler) + + for e, h := range ps.additionalClusterHandlers { + ps.clusterIFace.RegisterClusterMessageHandler(e, h) + } +} + +func (ps *PlatformService) RegisterClusterMessageHandler(ev model.ClusterEvent, h einterfaces.ClusterMessageHandler) { + ps.additionalClusterHandlers[ev] = h +} + +// ClusterHandlersPreCheck checks whether the platform service is ready to handle cluster messages. +func (ps *PlatformService) ClusterHandlersPreCheck() error { + if ps.Store == nil { + return fmt.Errorf("could not find store") + } + + if ps.statusCache == nil { + return fmt.Errorf("could not find status cache") + } + + return nil +} + +func (ps *PlatformService) ClusterPublishHandler(msg *model.ClusterMessage) { + event, err := model.WebSocketEventFromJSON(bytes.NewReader(msg.Data)) + if err != nil { + ps.logger.Warn("Failed to decode event from JSON", mlog.Err(err)) + return + } + + ps.PublishSkipClusterSend(event) +} + +func (ps *PlatformService) ClusterUpdateStatusHandler(msg *model.ClusterMessage) { + var status model.Status + if jsonErr := json.Unmarshal(msg.Data, &status); jsonErr != nil { + ps.logger.Warn("Failed to decode status from JSON") + } + + ps.statusCache.Set(status.UserId, status) +} + +func (ps *PlatformService) ClusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { + ps.InvalidateAllCachesSkipSend() +} + +func (ps *PlatformService) clusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { + ps.invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(string(msg.Data)) +} + +func (ps *PlatformService) clusterInvalidateCacheForChannelByNameHandler(msg *model.ClusterMessage) { + ps.invalidateCacheForChannelByNameSkipClusterSend(msg.Props["id"], msg.Props["name"]) +} + +func (ps *PlatformService) clusterInvalidateCacheForUserHandler(msg *model.ClusterMessage) { + ps.InvalidateCacheForUserSkipClusterSend(string(msg.Data)) +} + +func (ps *PlatformService) clusterInvalidateCacheForUserTeamsHandler(msg *model.ClusterMessage) { + ps.invalidateWebConnSessionCacheForUser(string(msg.Data)) +} + +func (ps *PlatformService) ClearSessionCacheForUserSkipClusterSend(userID string) { + ps.ClearUserSessionCacheLocal(userID) + ps.invalidateWebConnSessionCacheForUser(userID) +} + +func (ps *PlatformService) ClearSessionCacheForAllUsersSkipClusterSend() { + ps.logger.Info("Purging sessions cache") + ps.ClearAllUsersSessionCacheLocal() +} + +func (ps *PlatformService) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) { + ps.ClearSessionCacheForUserSkipClusterSend(string(msg.Data)) +} + +func (ps *PlatformService) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) { + ps.ClearSessionCacheForAllUsersSkipClusterSend() +} + +func (ps *PlatformService) clusterBusyStateChgHandler(msg *model.ClusterMessage) { + var sbs model.ServerBusyState + if jsonErr := json.Unmarshal(msg.Data, &sbs); jsonErr != nil { + mlog.Warn("Failed to decode server busy state from JSON", mlog.Err(jsonErr)) + } + + ps.Busy.ClusterEventChanged(&sbs) + if sbs.Busy { + ps.logger.Warn("server busy state activated via cluster event - non-critical services disabled", mlog.Int64("expires_sec", sbs.Expires)) + } else { + ps.logger.Info("server busy state cleared via cluster event - non-critical services enabled") + } +} + +func (ps *PlatformService) invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelID string) { + ps.Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channelID) +} + +func (ps *PlatformService) invalidateCacheForChannelByNameSkipClusterSend(teamID, name string) { + if teamID == "" { + teamID = "dm" + } + + ps.Store.Channel().InvalidateChannelByName(teamID, name) +} + +func (ps *PlatformService) InvalidateCacheForUserSkipClusterSend(userID string) { + ps.Store.Channel().InvalidateAllChannelMembersForUser(userID) + ps.invalidateWebConnSessionCacheForUser(userID) +} + +func (ps *PlatformService) invalidateWebConnSessionCacheForUser(userID string) { + hub := ps.GetHubForUserId(userID) + if hub != nil { + hub.InvalidateUser(userID) + } +} + +func (ps *PlatformService) InvalidateAllCachesSkipSend() { + ps.logger.Info("Purging all caches") + ps.ClearAllUsersSessionCacheLocal() + ps.statusCache.Purge() + ps.Store.Team().ClearCaches() + ps.Store.Channel().ClearCaches() + ps.Store.User().ClearCaches() + ps.Store.Post().ClearCaches() + ps.Store.FileInfo().ClearCaches() + ps.Store.Webhook().ClearCaches() + + linkCache.Purge() + ps.LoadLicense() +} + +func (ps *PlatformService) InvalidateAllCaches() *model.AppError { + debug.FreeOSMemory() + ps.InvalidateAllCachesSkipSend() + + if ps.clusterIFace != nil { + + msg := &model.ClusterMessage{ + Event: model.ClusterEventInvalidateAllCaches, + SendType: model.ClusterSendReliable, + WaitForAllToSend: true, + } + + ps.clusterIFace.SendClusterMessage(msg) + } + + return nil +} diff --git a/app/platform/config.go b/app/platform/config.go index ab6c5e44b8..9fab59450e 100644 --- a/app/platform/config.go +++ b/app/platform/config.go @@ -4,24 +4,33 @@ package platform import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/md5" + "crypto/rand" + "crypto/x509" + "encoding/base64" + "encoding/json" "errors" "fmt" "net/http" "reflect" + "strconv" "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/einterfaces" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/product" "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store" ) // ServiceConfig is used to initialize the PlatformService. // The mandatory fields will be checked during the initialization of the service. type ServiceConfig struct { // Mandatory fields - ConfigStore *config.Store - StartMetrics bool // TODO: find an elegant way to start/stop metrics server by default + ConfigStore *config.Store + Store store.Store // Optional fields Metrics einterfaces.MetricsInterface Cluster einterfaces.ClusterInterface @@ -76,14 +85,14 @@ func (ps *PlatformService) SaveConfig(newCfg *model.Config, sendConfigChangeClus return nil, nil, model.NewAppError("saveConfig", "app.save_config.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if ps.serviceConfig.StartMetrics && *ps.Config().MetricsSettings.Enable { + if ps.startMetrics && *ps.Config().MetricsSettings.Enable { ps.RestartMetrics() } else { ps.ShutdownMetrics() } - if ps.cluster != nil { - err := ps.cluster.ConfigChanged(ps.configStore.RemoveEnvironmentOverrides(oldCfg), + if ps.clusterIFace != nil { + err := ps.clusterIFace.ConfigChanged(ps.configStore.RemoveEnvironmentOverrides(oldCfg), ps.configStore.RemoveEnvironmentOverrides(newCfg), sendConfigChangeClusterMessage) if err != nil { return nil, nil, err @@ -166,3 +175,214 @@ func (ps *PlatformService) HasConfigFile(name string) (bool, error) { func (ps *PlatformService) SetConfigReadOnlyFF(readOnly bool) { ps.configStore.SetReadOnlyFF(readOnly) } + +func (ps *PlatformService) ClientConfigHash() string { + return ps.clientConfigHash.Load().(string) +} + +func (ps *PlatformService) regenerateClientConfig() { + clientConfig := config.GenerateClientConfig(ps.Config(), ps.telemetryId, ps.License()) + limitedClientConfig := config.GenerateLimitedClientConfig(ps.Config(), ps.telemetryId, ps.License()) + + if clientConfig["EnableCustomTermsOfService"] == "true" { + termsOfService, err := ps.Store.TermsOfService().GetLatest(true) + if err != nil { + mlog.Err(err) + } else { + clientConfig["CustomTermsOfServiceId"] = termsOfService.Id + limitedClientConfig["CustomTermsOfServiceId"] = termsOfService.Id + } + } + + if key := ps.AsymmetricSigningKey(); key != nil { + der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) + clientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) + limitedClientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) + } + + clientConfigJSON, _ := json.Marshal(clientConfig) + ps.clientConfig.Store(clientConfig) + ps.limitedClientConfig.Store(limitedClientConfig) + ps.clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON))) +} + +// AsymmetricSigningKey will return a private key that can be used for asymmetric signing. +func (ps *PlatformService) AsymmetricSigningKey() *ecdsa.PrivateKey { + if key := ps.asymmetricSigningKey.Load(); key != nil { + return key.(*ecdsa.PrivateKey) + } + return nil +} + +// EnsureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to +// AsymmetricSigningKey will always return a valid signing key. +func (ps *PlatformService) EnsureAsymmetricSigningKey() error { + if ps.AsymmetricSigningKey() != nil { + return nil + } + + var key *model.SystemAsymmetricSigningKey + + value, err := ps.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) + if err == nil { + if err := json.Unmarshal([]byte(value.Value), &key); err != nil { + return err + } + } + + // If we don't already have a key, try to generate one. + if key == nil { + newECDSAKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return err + } + newKey := &model.SystemAsymmetricSigningKey{ + ECDSAKey: &model.SystemECDSAKey{ + Curve: "P-256", + X: newECDSAKey.X, + Y: newECDSAKey.Y, + D: newECDSAKey.D, + }, + } + system := &model.System{ + Name: model.SystemAsymmetricSigningKeyKey, + } + v, err := json.Marshal(newKey) + if err != nil { + return err + } + system.Value = string(v) + // If we were able to save the key, use it, otherwise log the error. + if err = ps.Store.System().Save(system); err != nil { + mlog.Warn("Failed to save AsymmetricSigningKey", mlog.Err(err)) + } else { + key = newKey + } + } + + // If we weren't able to save a new key above, another server must have beat us to it. Get the + // key from the database, and if that fails, error out. + if key == nil { + value, err := ps.Store.System().GetByName(model.SystemAsymmetricSigningKeyKey) + if err != nil { + return err + } + + if err := json.Unmarshal([]byte(value.Value), &key); err != nil { + return err + } + } + + var curve elliptic.Curve + switch key.ECDSAKey.Curve { + case "P-256": + curve = elliptic.P256() + default: + return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve) + } + ps.asymmetricSigningKey.Store(&ecdsa.PrivateKey{ + PublicKey: ecdsa.PublicKey{ + Curve: curve, + X: key.ECDSAKey.X, + Y: key.ECDSAKey.Y, + }, + D: key.ECDSAKey.D, + }) + ps.regenerateClientConfig() + return nil +} + +// LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. +func (ps *PlatformService) LimitedClientConfigWithComputed() map[string]string { + respCfg := map[string]string{} + for k, v := range ps.LimitedClientConfig() { + respCfg[k] = v + } + + // These properties are not configurable, but nevertheless represent configuration expected + // by the client. + respCfg["NoAccounts"] = strconv.FormatBool(ps.IsFirstUserAccount()) + + return respCfg +} + +// ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. +func (ps *PlatformService) ClientConfigWithComputed() map[string]string { + respCfg := map[string]string{} + for k, v := range ps.clientConfig.Load().(map[string]string) { + respCfg[k] = v + } + + // These properties are not configurable, but nevertheless represent configuration expected + // by the client. + respCfg["NoAccounts"] = strconv.FormatBool(ps.IsFirstUserAccount()) + respCfg["MaxPostSize"] = strconv.Itoa(ps.MaxPostSize()) + respCfg["UpgradedFromTE"] = strconv.FormatBool(ps.isUpgradedFromTE()) + respCfg["InstallationDate"] = "" + if installationDate, err := ps.GetSystemInstallDate(); err == nil { + respCfg["InstallationDate"] = strconv.FormatInt(installationDate, 10) + } + if ver, err := ps.Store.GetDBSchemaVersion(); err != nil { + mlog.Error("Could not get the schema version", mlog.Err(err)) + } else { + respCfg["SchemaVersion"] = strconv.Itoa(ver) + } + + return respCfg +} + +func (ps *PlatformService) LimitedClientConfig() map[string]string { + return ps.limitedClientConfig.Load().(map[string]string) +} + +func (ps *PlatformService) IsFirstUserAccount() bool { + cachedSessions, err := ps.sessionCache.Len() + if err != nil { + return false + } + if cachedSessions == 0 { + count, err := ps.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) + if err != nil { + return false + } + if count <= 0 { + return true + } + } + + return false +} + +func (ps *PlatformService) MaxPostSize() int { + maxPostSize := ps.Store.Post().GetMaxPostSize() + if maxPostSize == 0 { + return model.PostMessageMaxRunesV1 + } + + return maxPostSize +} + +func (ps *PlatformService) isUpgradedFromTE() bool { + val, err := ps.Store.System().GetByName(model.SystemUpgradedFromTeId) + if err != nil { + return false + } + return val.Value == "true" +} + +func (ps *PlatformService) GetSystemInstallDate() (int64, *model.AppError) { + systemData, err := ps.Store.System().GetByName(model.SystemInstallationDateKey) + if err != nil { + return 0, model.NewAppError("getSystemInstallDate", "app.system.get_by_name.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + value, err := strconv.ParseInt(systemData.Value, 10, 64) + if err != nil { + return 0, model.NewAppError("getSystemInstallDate", "app.system_install_date.parse_int.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + return value, nil +} + +func (ps *PlatformService) ClientConfig() map[string]string { + return ps.clientConfig.Load().(map[string]string) + +} diff --git a/app/platform/config_test.go b/app/platform/config_test.go index 3dd9ebf19e..af99b47d89 100644 --- a/app/platform/config_test.go +++ b/app/platform/config_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/mattermost/mattermost-server/v6/einterfaces/mocks" @@ -49,11 +50,10 @@ func TestConfigListener(t *testing.T) { } func TestConfigSave(t *testing.T) { - th := Setup(t) - defer th.TearDown() - cm := &mocks.ClusterInterface{} - th.Service.SetCluster(cm) + cm.On("SendClusterMessage", mock.AnythingOfType("*model.ClusterMessage")).Return(nil) + th := SetupWithCluster(t, cm) + defer th.TearDown() t.Run("trigger a config changed event for the cluster", func(t *testing.T) { oldCfg := th.Service.Config() @@ -62,7 +62,6 @@ func TestConfigSave(t *testing.T) { sanitizedOldCfg := th.Service.configStore.RemoveEnvironmentOverrides(oldCfg) sanitizedNewCfg := th.Service.configStore.RemoveEnvironmentOverrides(newCfg) - cm.On("ConfigChanged", sanitizedOldCfg, sanitizedNewCfg, true).Return(nil) _, _, appErr := th.Service.SaveConfig(newCfg, true) diff --git a/app/platform/enterprise.go b/app/platform/enterprise.go new file mode 100644 index 0000000000..37849fb3f3 --- /dev/null +++ b/app/platform/enterprise.go @@ -0,0 +1,33 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/services/searchengine" +) + +var clusterInterface func(*PlatformService) einterfaces.ClusterInterface + +func RegisterClusterInterface(f func(*PlatformService) einterfaces.ClusterInterface) { + clusterInterface = f +} + +var elasticsearchInterface func(*PlatformService) searchengine.SearchEngineInterface + +func RegisterElasticsearchInterface(f func(*PlatformService) searchengine.SearchEngineInterface) { + elasticsearchInterface = f +} + +var licenseInterface func(*PlatformService) einterfaces.LicenseInterface + +func RegisterLicenseInterface(f func(*PlatformService) einterfaces.LicenseInterface) { + licenseInterface = f +} + +var metricsInterface func(*PlatformService, string, string) einterfaces.MetricsInterface + +func RegisterMetricsInterface(f func(*PlatformService, string, string) einterfaces.MetricsInterface) { + metricsInterface = f +} diff --git a/app/platform/errors.go b/app/platform/errors.go new file mode 100644 index 0000000000..52949dd9f5 --- /dev/null +++ b/app/platform/errors.go @@ -0,0 +1,24 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import "errors" + +var ( + AcceptedDomainError = errors.New("the email provided does not belong to an accepted domain") + VerifyUserError = errors.New("could not update verify email field") + UserCountError = errors.New("could not get the total number of the users.") + UserCreationDisabledError = errors.New("user creation is not allowed") + UserStoreIsEmptyError = errors.New("could not check if the user store is empty") + + GetTokenError = errors.New("could not get token") + GetSessionError = errors.New("could not get session") + DeleteTokenError = errors.New("could not delete token") + DeleteSessionError = errors.New("could not delete session") + DeleteAllAccessDataError = errors.New("could not delete all access data") + + DefaultFontError = errors.New("could not get default font") + UserInitialsError = errors.New("could not get user initials") + ImageEncodingError = errors.New("could not encode image") +) diff --git a/app/platform/goroutines.go b/app/platform/goroutines.go new file mode 100644 index 0000000000..91122736cc --- /dev/null +++ b/app/platform/goroutines.go @@ -0,0 +1,47 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import "sync/atomic" + +// Go creates a goroutine, but maintains a record of it to ensure that execution completes before +// the server is shutdown. +func (ps *PlatformService) Go(f func()) { + atomic.AddInt32(&ps.goroutineCount, 1) + + go func() { + f() + + atomic.AddInt32(&ps.goroutineCount, -1) + select { + case ps.goroutineExitSignal <- struct{}{}: + default: + } + }() +} + +// WaitForGoroutines blocks until all goroutines created by App.Go exit. +func (ps *PlatformService) WaitForGoroutines() { + for atomic.LoadInt32(&ps.goroutineCount) != 0 { + <-ps.goroutineExitSignal + } +} + +func (ps *PlatformService) GoBuffered(f func()) { + ps.goroutineBuffered <- struct{}{} + + atomic.AddInt32(&ps.goroutineCount, 1) + + go func() { + f() + + atomic.AddInt32(&ps.goroutineCount, -1) + select { + case ps.goroutineExitSignal <- struct{}{}: + default: + } + + <-ps.goroutineBuffered + }() +} diff --git a/app/platform/helper_test.go b/app/platform/helper_test.go index 17b053093f..20d92653ea 100644 --- a/app/platform/helper_test.go +++ b/app/platform/helper_test.go @@ -6,15 +6,53 @@ package platform import ( "io/ioutil" "path/filepath" + "sync" "testing" "github.com/mattermost/mattermost-server/v6/config" + "github.com/mattermost/mattermost-server/v6/einterfaces" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/store" + "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" + "github.com/mattermost/mattermost-server/v6/testlib" + "github.com/stretchr/testify/mock" ) type TestHelper struct { Service *PlatformService + Suite SuiteIFace + + BasicTeam *model.Team + BasicUser *model.User + BasicUser2 *model.User + BasicChannel *model.Channel + // BasicPost *model.Post + + SystemAdminUser *model.User +} + +var initBasicOnce sync.Once +var userCache struct { + SystemAdminUser *model.User + BasicUser *model.User + BasicUser2 *model.User +} + +type mockSuite struct { +} + +func (ms *mockSuite) SetStatusLastActivityAt(userID string, activityAt int64) {} +func (ms *mockSuite) SetStatusOffline(userID string, manual bool) {} +func (ms *mockSuite) IsUserAway(lastActivityAt int64) bool { return false } +func (ms *mockSuite) SetStatusOnline(userID string, manual bool) {} +func (ms *mockSuite) UpdateLastActivityAtIfNeeded(session model.Session) {} +func (ms *mockSuite) SetStatusAwayIfNeeded(userID string, manual bool) {} +func (ms *mockSuite) GetSession(token string) (*model.Session, *model.AppError) { + return &model.Session{}, nil +} +func (ms *mockSuite) RolesGrantPermission(roleNames []string, permissionId string) bool { return true } +func (ms *mockSuite) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) { + return true, nil } func Setup(tb testing.TB) *TestHelper { @@ -29,6 +67,65 @@ func Setup(tb testing.TB) *TestHelper { return setupTestHelper(dbStore, false, true, tb) } +func (th *TestHelper) InitBasic() *TestHelper { + // create users once and cache them because password hashing is slow + initBasicOnce.Do(func() { + th.SystemAdminUser = th.CreateAdmin() + userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy() + + th.BasicUser = th.CreateUserOrGuest(false) + userCache.BasicUser = th.BasicUser.DeepCopy() + + th.BasicUser2 = th.CreateUserOrGuest(false) + userCache.BasicUser2 = th.BasicUser2.DeepCopy() + }) + // restore cached users + th.SystemAdminUser = userCache.SystemAdminUser.DeepCopy() + th.BasicUser = userCache.BasicUser.DeepCopy() + th.BasicUser2 = userCache.BasicUser2.DeepCopy() + + users := []*model.User{th.SystemAdminUser, th.BasicUser, th.BasicUser2} + mainHelper.GetSQLStore().User().InsertUsers(users) + + th.BasicTeam = th.CreateTeam() + + // th.LinkUserToTeam(th.BasicUser, th.BasicTeam) + // th.LinkUserToTeam(th.BasicUser2, th.BasicTeam) + th.BasicChannel = th.CreateChannel(th.BasicTeam) + // th.BasicPost = th.CreatePost(th.BasicChannel) + return th +} + +func SetupWithStoreMock(tb testing.TB) *TestHelper { + mockStore := testlib.GetMockStoreForSetupFunctions() + th := setupTestHelper(mockStore, false, false, tb) + statusMock := mocks.StatusStore{} + statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil) + statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.StatusOnline}, nil) + statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil) + statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil) + emptyMockStore := mocks.Store{} + emptyMockStore.On("Close").Return(nil) + emptyMockStore.On("Status").Return(&statusMock) + th.Service.Store = &emptyMockStore + return th +} + +func SetupWithCluster(tb testing.TB, cluster einterfaces.ClusterInterface) *TestHelper { + if testing.Short() { + tb.SkipNow() + } + dbStore := mainHelper.GetStore() + dbStore.DropAllTables() + dbStore.MarkSystemRanUnitTests() + mainHelper.PreloadMigrations() + + th := setupTestHelper(dbStore, true, true, tb) + th.Service.clusterIFace = cluster + + return th +} + func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, tb testing.TB) *TestHelper { tempWorkspace, err := ioutil.TempDir("", "apptest") if err != nil { @@ -44,10 +141,14 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo *memoryConfig.LogSettings.EnableSentry = false // disable error reporting during tests *memoryConfig.AnnouncementSettings.AdminNoticesEnabled = false *memoryConfig.AnnouncementSettings.UserNoticesEnabled = false + *memoryConfig.MetricsSettings.Enable = true + *memoryConfig.ServiceSettings.ListenAddress = ":0" + *memoryConfig.MetricsSettings.ListenAddress = ":0" configStore.Set(memoryConfig) ps, err := New(ServiceConfig{ ConfigStore: configStore, + Store: dbStore, }) if err != nil { panic(err) @@ -55,6 +156,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th := &TestHelper{ Service: ps, + Suite: &mockSuite{}, } // Share same configuration with app.TestHelper @@ -79,9 +181,103 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th.Service.SetLicense(nil) } + th.Service.HubStart(th.Suite) + return th } func (th *TestHelper) TearDown() { - // Add cleaning code here + th.Service.ShutdownMetrics() + th.Service.Shutdown() + th.Service.ShutdownConfig() +} + +func (th *TestHelper) CreateTeam() *model.Team { + id := model.NewId() + + team := &model.Team{ + DisplayName: "dn_" + id, + Name: "name" + id, + Email: "success+" + id + "@simulator.amazonses.com", + Type: model.TeamOpen, + } + + var err error + if team, err = th.Service.Store.Team().Save(team); err != nil { + panic(err) + } + return team +} + +func (th *TestHelper) CreateUserOrGuest(guest bool) *model.User { + id := model.NewId() + + user := &model.User{ + Email: "success+" + id + "@simulator.amazonses.com", + Username: "un_" + id, + Nickname: "nn_" + id, + Password: "Password1", + EmailVerified: true, + Roles: model.SystemUserRoleId, + } + + var err error + user, err = th.Service.Store.User().Save(user) + if err != nil { + panic(err) + } + + return user +} + +func (th *TestHelper) CreateAdmin() *model.User { + id := model.NewId() + + user := &model.User{ + Email: "success+" + id + "@simulator.amazonses.com", + Username: "un_" + id, + Nickname: "nn_" + id, + Password: "Password1", + EmailVerified: true, + Roles: model.SystemAdminRoleId + " " + model.SystemUserRoleId, + } + + var err error + user, err = th.Service.Store.User().Save(user) + if err != nil { + panic(err) + } + + return user +} + +type ChannelOption func(*model.Channel) + +func WithShared(v bool) ChannelOption { + return func(channel *model.Channel) { + channel.Shared = model.NewBool(v) + } +} + +func (th *TestHelper) CreateChannel(team *model.Team, options ...ChannelOption) *model.Channel { + id := model.NewId() + + channel := &model.Channel{ + TeamId: team.Id, + DisplayName: "dn_" + id, + Name: "name" + id, + Type: model.ChannelTypeOpen, + } + + for _, option := range options { + option(channel) + } + + var err error + channel, err = th.Service.Store.Channel().Save(channel, 999) + if err != nil { + panic(err) + } + + return channel } diff --git a/app/platform/license.go b/app/platform/license.go new file mode 100644 index 0000000000..23232b9c93 --- /dev/null +++ b/app/platform/license.go @@ -0,0 +1,377 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "os" + "time" + + "github.com/dgrijalva/jwt-go" + "github.com/pkg/errors" + + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/jobs" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/utils" +) + +const ( + LicenseEnv = "MM_LICENSE" + LicenseRenewalURL = "https://customers.mattermost.com/subscribe/renew" + JWTDefaultTokenExpiration = 7 * 24 * time.Hour // 7 days of expiration +) + +var ( + RequestTrialURL = "https://customers.mattermost.com/api/v1/trials" +) + +// JWTClaims custom JWT claims with the needed information for the +// renewal process +type JWTClaims struct { + LicenseID string `json:"license_id"` + ActiveUsers int64 `json:"active_users"` + jwt.StandardClaims +} + +func (ps *PlatformService) LicenseManager() einterfaces.LicenseInterface { + return ps.licenseManager +} + +func (ps *PlatformService) SetLicenseManager(impl einterfaces.LicenseInterface) { + ps.licenseManager = impl +} + +func (ps *PlatformService) License() *model.License { + license, _ := ps.licenseValue.Load().(*model.License) + return license +} + +func (ps *PlatformService) LoadLicense() { + // ENV var overrides all other sources of license. + licenseStr := os.Getenv(LicenseEnv) + if licenseStr != "" { + license, err := utils.LicenseValidator.LicenseFromBytes([]byte(licenseStr)) + if err != nil { + ps.logger.Error("Failed to read license set in environment.", mlog.Err(err)) + return + } + + // skip the restrictions if license is a sanctioned trial + if !license.IsSanctionedTrial() && license.IsTrialLicense() { + canStartTrialLicense, err := ps.licenseManager.CanStartTrial() + if err != nil { + ps.logger.Error("Failed to validate trial eligibility.", mlog.Err(err)) + return + } + + if !canStartTrialLicense { + ps.logger.Info("Cannot start trial multiple times.") + return + } + } + + if ps.ValidateAndSetLicenseBytes([]byte(licenseStr)) { + ps.logger.Info("License key from ENV is valid, unlocking enterprise features.") + } + return + } + + licenseId := "" + props, nErr := ps.Store.System().Get() + if nErr == nil { + licenseId = props[model.SystemActiveLicenseId] + } + + if !model.IsValidId(licenseId) { + // Lets attempt to load the file from disk since it was missing from the DB + license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*ps.Config().ServiceSettings.LicenseFileLocation) + + if license != nil { + if _, err := ps.SaveLicense(licenseBytes); err != nil { + ps.logger.Error("Failed to save license key loaded from disk.", mlog.Err(err)) + } else { + licenseId = license.Id + } + } + } + + record, nErr := ps.Store.License().Get(licenseId) + if nErr != nil { + ps.logger.Error("License key from https://mattermost.com required to unlock enterprise features.", mlog.Err(nErr)) + ps.SetLicense(nil) + return + } + + ps.ValidateAndSetLicenseBytes([]byte(record.Bytes)) + ps.logger.Info("License key valid unlocking enterprise features.") +} + +func (ps *PlatformService) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { + success, licenseStr := utils.LicenseValidator.ValidateLicense(licenseBytes) + if !success { + return nil, model.NewAppError("addLicense", model.InvalidLicenseError, nil, "", http.StatusBadRequest) + } + + var license model.License + if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil { + return nil, model.NewAppError("addLicense", "api.unmarshal_error", nil, "", http.StatusInternalServerError).Wrap(jsonErr) + } + + uniqueUserCount, err := ps.Store.User().Count(model.UserCountOptions{}) + if err != nil { + return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, "", http.StatusBadRequest).Wrap(err) + } + + if uniqueUserCount > int64(*license.Features.Users) { + return nil, model.NewAppError("addLicense", "api.license.add_license.unique_users.app_error", map[string]any{"Users": *license.Features.Users, "Count": uniqueUserCount}, "", http.StatusBadRequest) + } + + if license.IsExpired() { + return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) + } + + if *ps.Config().JobSettings.RunJobs && ps.Jobs != nil { + if err := ps.Jobs.StopWorkers(); err != nil && !errors.Is(err, jobs.ErrWorkersNotRunning) { + ps.logger.Warn("Stopping job server workers failed", mlog.Err(err)) + } + } + + if *ps.Config().JobSettings.RunScheduler && ps.Jobs != nil { + if err := ps.Jobs.StopSchedulers(); err != nil && !errors.Is(err, jobs.ErrSchedulersNotRunning) { + ps.logger.Error("Stopping job server schedulers failed", mlog.Err(err)) + } + } + + defer func() { + // restart job server workers - this handles the edge case where a license file is uploaded, but the job server + // doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from + // functioning as expected + if *ps.Config().JobSettings.RunJobs && ps.Jobs != nil { + if err := ps.Jobs.StartWorkers(); err != nil { + ps.logger.Error("Starting job server workers failed", mlog.Err(err)) + } + } + if *ps.Config().JobSettings.RunScheduler && ps.Jobs != nil { + if err := ps.Jobs.StartSchedulers(); err != nil && !errors.Is(err, jobs.ErrSchedulersRunning) { + ps.logger.Error("Starting job server schedulers failed", mlog.Err(err)) + } + } + }() + + if ok := ps.SetLicense(&license); !ok { + return nil, model.NewAppError("addLicense", model.ExpiredLicenseError, nil, "", http.StatusBadRequest) + } + + record := &model.LicenseRecord{} + record.Id = license.Id + record.Bytes = string(licenseBytes) + + _, nErr := ps.Store.License().Save(record) + if nErr != nil { + ps.RemoveLicense() + var appErr *model.AppError + switch { + case errors.As(nErr, &appErr): + return nil, appErr + default: + return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) + } + } + + sysVar := &model.System{} + sysVar.Name = model.SystemActiveLicenseId + sysVar.Value = license.Id + if err := ps.Store.System().SaveOrUpdate(sysVar); err != nil { + ps.RemoveLicense() + return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) + } + + ps.ReloadConfig() + ps.InvalidateAllCaches() + + return &license, nil +} + +func (ps *PlatformService) SetLicense(license *model.License) bool { + oldLicense := ps.licenseValue.Load() + + defer func() { + for _, listener := range ps.licenseListeners { + if oldLicense == nil { + listener(nil, license) + } else { + listener(oldLicense.(*model.License), license) + } + } + }() + + if license != nil { + license.Features.SetDefaults() + + ps.licenseValue.Store(license) + + ps.clientLicenseValue.Store(utils.GetClientLicense(license)) + return true + } + + ps.licenseValue.Store((*model.License)(nil)) + ps.clientLicenseValue.Store(map[string]string(nil)) + + return false +} + +func (ps *PlatformService) ValidateAndSetLicenseBytes(b []byte) bool { + if success, licenseStr := utils.LicenseValidator.ValidateLicense(b); success { + var license model.License + if jsonErr := json.Unmarshal([]byte(licenseStr), &license); jsonErr != nil { + ps.logger.Warn("Failed to decode license from JSON", mlog.Err(jsonErr)) + return false + } + ps.SetLicense(&license) + return true + } + + ps.logger.Warn("No valid enterprise license found") + return false +} + +func (ps *PlatformService) SetClientLicense(m map[string]string) { + ps.clientLicenseValue.Store(m) +} + +func (ps *PlatformService) ClientLicense() map[string]string { + if clientLicense, _ := ps.clientLicenseValue.Load().(map[string]string); clientLicense != nil { + return clientLicense + } + return map[string]string{"IsLicensed": "false"} +} + +func (ps *PlatformService) RemoveLicense() *model.AppError { + if license, _ := ps.licenseValue.Load().(*model.License); license == nil { + return nil + } + + ps.logger.Info("Remove license.", mlog.String("id", model.SystemActiveLicenseId)) + + sysVar := &model.System{} + sysVar.Name = model.SystemActiveLicenseId + sysVar.Value = "" + + if err := ps.Store.System().SaveOrUpdate(sysVar); err != nil { + return model.NewAppError("RemoveLicense", "app.system.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + ps.SetLicense(nil) + ps.ReloadConfig() + ps.InvalidateAllCaches() + + return nil +} + +func (ps *PlatformService) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string { + id := model.NewId() + ps.licenseListeners[id] = listener + return id +} + +func (ps *PlatformService) RemoveLicenseListener(id string) { + delete(ps.licenseListeners, id) +} + +func (ps *PlatformService) GetSanitizedClientLicense() map[string]string { + return utils.GetSanitizedClientLicense(ps.ClientLicense()) +} + +// RequestTrialLicense request a trial license from the mattermost official license server +func (ps *PlatformService) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { + trialRequestJSON, err := json.Marshal(trialRequest) + if err != nil { + return model.NewAppError("RequestTrialLicense", "api.unmarshal_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + resp, err := http.Post(RequestTrialURL, "application/json", bytes.NewBuffer(trialRequestJSON)) + if err != nil { + return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, "", http.StatusBadRequest).Wrap(err) + } + defer resp.Body.Close() + + // CloudFlare sitting in front of the Customer Portal will block this request with a 451 response code in the event that the request originates from a country sanctioned by the U.S. Government. + if resp.StatusCode == http.StatusUnavailableForLegalReasons { + return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.embargoed", nil, "Request for trial license came from an embargoed country", http.StatusUnavailableForLegalReasons) + } + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, + fmt.Sprintf("Unexpected HTTP status code %q returned by server", resp.Status), http.StatusInternalServerError) + } + + var licenseResponse map[string]string + err = json.NewDecoder(resp.Body).Decode(&licenseResponse) + if err != nil { + ps.logger.Warn("Error decoding license response", mlog.Err(err)) + } + + if _, ok := licenseResponse["license"]; !ok { + return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, licenseResponse["message"], http.StatusBadRequest) + } + + if _, err := ps.SaveLicense([]byte(licenseResponse["license"])); err != nil { + return err + } + + ps.ReloadConfig() + ps.InvalidateAllCaches() + + return nil +} + +// GenerateRenewalToken returns a renewal token that expires after duration expiration +func (ps *PlatformService) GenerateRenewalToken(expiration time.Duration) (string, *model.AppError) { + license := ps.License() + if license == nil { + return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.no_license", nil, "", http.StatusBadRequest) + } + + if *license.Features.Cloud { + return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.bad_license", nil, "", http.StatusBadRequest) + } + + activeUsers, err := ps.Store.User().Count(model.UserCountOptions{}) + if err != nil { + return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", + nil, "", http.StatusInternalServerError).Wrap(err) + } + + expirationTime := time.Now().UTC().Add(expiration) + claims := &JWTClaims{ + LicenseID: license.Id, + ActiveUsers: activeUsers, + StandardClaims: jwt.StandardClaims{ + ExpiresAt: expirationTime.Unix(), + }, + } + + token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + tokenString, err := token.SignedString([]byte(license.Customer.Email)) + if err != nil { + return "", model.NewAppError("GenerateRenewalToken", "app.license.generate_renewal_token.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + return tokenString, nil +} + +// GenerateLicenseRenewalLink returns a link that points to the CWS where clients can renew license +func (ps *PlatformService) GenerateLicenseRenewalLink() (string, string, *model.AppError) { + renewalToken, err := ps.GenerateRenewalToken(JWTDefaultTokenExpiration) + if err != nil { + return "", "", err + } + renewalLink := LicenseRenewalURL + "?token=" + renewalToken + return renewalLink, renewalToken, nil +} diff --git a/app/platform/license_test.go b/app/platform/license_test.go new file mode 100644 index 0000000000..8f875ea91d --- /dev/null +++ b/app/platform/license_test.go @@ -0,0 +1,111 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/mattermost/mattermost-server/v6/model" +) + +func TestLoadLicense(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + th.Service.LoadLicense() + require.Nil(t, th.Service.License(), "shouldn't have a valid license") +} + +func TestSaveLicense(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + b1 := []byte("junk") + + _, err := th.Service.SaveLicense(b1) + require.NotNil(t, err, "shouldn't have saved license") +} + +func TestRemoveLicense(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + err := th.Service.RemoveLicense() + require.Nil(t, err, "should have removed license") +} + +func TestSetLicense(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + l1 := &model.License{} + l1.Features = &model.Features{} + l1.Customer = &model.Customer{} + l1.StartsAt = model.GetMillis() - 1000 + l1.ExpiresAt = model.GetMillis() + 100000 + ok := th.Service.SetLicense(l1) + require.True(t, ok, "license should have worked") + + l3 := &model.License{} + l3.Features = &model.Features{} + l3.Customer = &model.Customer{} + l3.StartsAt = model.GetMillis() + 10000 + l3.ExpiresAt = model.GetMillis() + 100000 + ok = th.Service.SetLicense(l3) + require.True(t, ok, "license should have passed") +} + +func TestGetSanitizedClientLicense(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + setLicense(th, nil) + + m := th.Service.GetSanitizedClientLicense() + + _, ok := m["Name"] + assert.False(t, ok) + _, ok = m["SkuName"] + assert.False(t, ok) + _, ok = m["SkuShortName"] + assert.False(t, ok) +} + +func TestGenerateRenewalToken(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + t.Run("renewal token generated correctly", func(t *testing.T) { + setLicense(th, nil) + token, appErr := th.Service.GenerateRenewalToken(JWTDefaultTokenExpiration) + require.Nil(t, appErr) + require.NotEmpty(t, token) + }) + + t.Run("return error if there is no active license", func(t *testing.T) { + th.Service.SetLicense(nil) + _, appErr := th.Service.GenerateRenewalToken(JWTDefaultTokenExpiration) + require.NotNil(t, appErr) + }) +} + +func setLicense(th *TestHelper, customer *model.Customer) { + l1 := &model.License{} + l1.Features = &model.Features{} + if customer != nil { + l1.Customer = customer + } else { + l1.Customer = &model.Customer{} + l1.Customer.Name = "TestName" + l1.Customer.Email = "test@example.com" + } + l1.SkuName = "SKU NAME" + l1.SkuShortName = "SKU SHORT NAME" + l1.StartsAt = model.GetMillis() - 1000 + l1.ExpiresAt = model.GetMillis() + 100000 + th.Service.SetLicense(l1) +} diff --git a/app/platform/link_cache.go b/app/platform/link_cache.go new file mode 100644 index 0000000000..7a1266fda5 --- /dev/null +++ b/app/platform/link_cache.go @@ -0,0 +1,25 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "time" + + "github.com/mattermost/mattermost-server/v6/services/cache" +) + +const LinkCacheSize = 10000 +const LinkCacheDuration = 1 * time.Hour + +var linkCache = cache.NewLRU(cache.LRUOptions{ + Size: LinkCacheSize, +}) + +func PurgeLinkCache() { + linkCache.Purge() +} + +func LinkCache() cache.Cache { + return linkCache +} diff --git a/app/platform/log.go b/app/platform/log.go index 0cb96dab85..1d2cc8cf33 100644 --- a/app/platform/log.go +++ b/app/platform/log.go @@ -7,6 +7,9 @@ import ( "context" "errors" "fmt" + "io" + "net/http" + "os" "time" "github.com/mattermost/mattermost-server/v6/config" @@ -14,6 +17,10 @@ import ( "github.com/mattermost/mattermost-server/v6/shared/mlog" ) +func (ps *PlatformService) Log() mlog.LoggerIFace { + return ps.logger +} + func (ps *PlatformService) ReconfigureLogger() error { return ps.initLogging() } @@ -82,11 +89,11 @@ func (ps *PlatformService) NotificationsLogger() *mlog.Logger { } func (ps *PlatformService) EnableLoggingMetrics() { - if ps.metrics == nil || ps.metrics.metricsImpl == nil { + if ps.metrics == nil || ps.metricsImpl() == nil { return } - ps.logger.SetMetricsCollector(ps.metrics.metricsImpl.GetLoggerMetricsCollector(), mlog.DefaultMetricsUpdateFreqMillis) + ps.logger.SetMetricsCollector(ps.metricsImpl().GetLoggerMetricsCollector(), mlog.DefaultMetricsUpdateFreqMillis) // logging config needs to be reloaded when metrics collector is added or changed. if err := ps.initLogging(); err != nil { @@ -115,3 +122,75 @@ func (ps *PlatformService) RemoveUnlicensedLogTargets(license *model.License) { return ti.Type != "*targets.Writer" && ti.Type != "*targets.File" }) } + +func (ps *PlatformService) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { + var lines []string + + if *ps.Config().LogSettings.EnableFile { + ps.Log().Flush() + logFile := config.GetLogFileLocation(*ps.Config().LogSettings.FileLocation) + file, err := os.Open(logFile) + if err != nil { + return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + defer file.Close() + + var newLine = []byte{'\n'} + var lineCount int + const searchPos = -1 + b := make([]byte, 1) + var endOffset int64 = 0 + + // if the file exists and it's last byte is '\n' - skip it + var stat os.FileInfo + if stat, err = os.Stat(logFile); err == nil { + if _, err = file.ReadAt(b, stat.Size()-1); err == nil && b[0] == newLine[0] { + endOffset = -1 + } + } + lineEndPos, err := file.Seek(endOffset, io.SeekEnd) + if err != nil { + return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + for { + pos, err := file.Seek(searchPos, io.SeekCurrent) + if err != nil { + return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + _, err = file.ReadAt(b, pos) + if err != nil { + return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + if b[0] == newLine[0] || pos == 0 { + lineCount++ + if lineCount > page*perPage { + line := make([]byte, lineEndPos-pos) + _, err := file.ReadAt(line, pos) + if err != nil { + return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + lines = append(lines, string(line)) + } + if pos == 0 { + break + } + lineEndPos = pos + } + + if len(lines) == perPage { + break + } + } + + for i, j := 0, len(lines)-1; i < j; i, j = i+1, j-1 { + lines[i], lines[j] = lines[j], lines[i] + } + } else { + lines = append(lines, "") + } + + return lines, nil +} diff --git a/app/platform/metrics.go b/app/platform/metrics.go index 4ace86b156..f486f85cbc 100644 --- a/app/platform/metrics.go +++ b/app/platform/metrics.go @@ -35,6 +35,14 @@ type platformMetrics struct { cfgFn func() *model.Config } +func (ps *PlatformService) metricsImpl() einterfaces.MetricsInterface { + if ps.metrics == nil { + return nil + } + + return ps.metrics.metricsImpl +} + // resetMetrics resets the metrics server. Clears the metrics if the metrics are disabled by the config. func (ps *PlatformService) resetMetrics(metricsImpl einterfaces.MetricsInterface, cfgFn func() *model.Config) error { if !*cfgFn().MetricsSettings.Enable { @@ -173,12 +181,13 @@ func (ps *PlatformService) HandleMetrics(route string, h http.Handler) { } func (ps *PlatformService) RestartMetrics() error { - return ps.resetMetrics(ps.serviceConfig.Metrics, ps.serviceConfig.ConfigStore.Get) + return ps.resetMetrics(ps.serviceConfig.Metrics, ps.configStore.Get) } func (ps *PlatformService) Metrics() einterfaces.MetricsInterface { if ps.metrics == nil { return nil } - return ps.metrics.metricsImpl + + return ps.metricsImpl() } diff --git a/app/platform/mocks/SuiteIFace.go b/app/platform/mocks/SuiteIFace.go new file mode 100644 index 0000000000..6b337a8059 --- /dev/null +++ b/app/platform/mocks/SuiteIFace.go @@ -0,0 +1,131 @@ +// Code generated by mockery v2.14.0. DO NOT EDIT. + +// Regenerate this file using `make platform-mocks`. + +package mocks + +import ( + model "github.com/mattermost/mattermost-server/v6/model" + mock "github.com/stretchr/testify/mock" +) + +// SuiteIFace is an autogenerated mock type for the SuiteIFace type +type SuiteIFace struct { + mock.Mock +} + +// GetSession provides a mock function with given fields: token +func (_m *SuiteIFace) GetSession(token string) (*model.Session, *model.AppError) { + ret := _m.Called(token) + + var r0 *model.Session + if rf, ok := ret.Get(0).(func(string) *model.Session); ok { + r0 = rf(token) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*model.Session) + } + } + + var r1 *model.AppError + if rf, ok := ret.Get(1).(func(string) *model.AppError); ok { + r1 = rf(token) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*model.AppError) + } + } + + return r0, r1 +} + +// IsUserAway provides a mock function with given fields: lastActivityAt +func (_m *SuiteIFace) IsUserAway(lastActivityAt int64) bool { + ret := _m.Called(lastActivityAt) + + var r0 bool + if rf, ok := ret.Get(0).(func(int64) bool); ok { + r0 = rf(lastActivityAt) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// RolesGrantPermission provides a mock function with given fields: roleNames, permissionId +func (_m *SuiteIFace) RolesGrantPermission(roleNames []string, permissionId string) bool { + ret := _m.Called(roleNames, permissionId) + + var r0 bool + if rf, ok := ret.Get(0).(func([]string, string) bool); ok { + r0 = rf(roleNames, permissionId) + } else { + r0 = ret.Get(0).(bool) + } + + return r0 +} + +// SetStatusAwayIfNeeded provides a mock function with given fields: userID, manual +func (_m *SuiteIFace) SetStatusAwayIfNeeded(userID string, manual bool) { + _m.Called(userID, manual) +} + +// SetStatusLastActivityAt provides a mock function with given fields: userID, activityAt +func (_m *SuiteIFace) SetStatusLastActivityAt(userID string, activityAt int64) { + _m.Called(userID, activityAt) +} + +// SetStatusOffline provides a mock function with given fields: userID, manual +func (_m *SuiteIFace) SetStatusOffline(userID string, manual bool) { + _m.Called(userID, manual) +} + +// SetStatusOnline provides a mock function with given fields: userID, manual +func (_m *SuiteIFace) SetStatusOnline(userID string, manual bool) { + _m.Called(userID, manual) +} + +// UpdateLastActivityAtIfNeeded provides a mock function with given fields: session +func (_m *SuiteIFace) UpdateLastActivityAtIfNeeded(session model.Session) { + _m.Called(session) +} + +// UserCanSeeOtherUser provides a mock function with given fields: userID, otherUserId +func (_m *SuiteIFace) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) { + ret := _m.Called(userID, otherUserId) + + var r0 bool + if rf, ok := ret.Get(0).(func(string, string) bool); ok { + r0 = rf(userID, otherUserId) + } else { + r0 = ret.Get(0).(bool) + } + + var r1 *model.AppError + if rf, ok := ret.Get(1).(func(string, string) *model.AppError); ok { + r1 = rf(userID, otherUserId) + } else { + if ret.Get(1) != nil { + r1 = ret.Get(1).(*model.AppError) + } + } + + return r0, r1 +} + +type mockConstructorTestingTNewSuiteIFace interface { + mock.TestingT + Cleanup(func()) +} + +// NewSuiteIFace creates a new instance of SuiteIFace. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +func NewSuiteIFace(t mockConstructorTestingTNewSuiteIFace) *SuiteIFace { + mock := &SuiteIFace{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/app/platform/options.go b/app/platform/options.go new file mode 100644 index 0000000000..99d63d8f26 --- /dev/null +++ b/app/platform/options.go @@ -0,0 +1,106 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "fmt" + + "github.com/pkg/errors" + + "github.com/mattermost/mattermost-server/v6/config" + "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store" + "github.com/mattermost/mattermost-server/v6/store/localcachelayer" +) + +type Option func(ps *PlatformService) error + +// By default, the app will use the store specified by the configuration. This allows you to +// construct an app with a different store. +// +// The override parameter must be either a store.Store or func(App) store.Store(). +func StoreOverride(override any) Option { + return func(ps *PlatformService) error { + switch o := override.(type) { + case store.Store: + ps.newStore = func() (store.Store, error) { + return o, nil + } + return nil + + case func(*PlatformService) store.Store: + ps.newStore = func() (store.Store, error) { + return o(ps), nil + } + return nil + + default: + return errors.New("invalid StoreOverride") + } + } +} + +func StoreOverrideWithCache(override store.Store) Option { + return func(ps *PlatformService) error { + ps.newStore = func() (store.Store, error) { + lcl, err := localcachelayer.NewLocalCacheLayer(override, ps.metricsImpl(), ps.clusterIFace, ps.cacheProvider) + if err != nil { + return nil, err + } + return lcl, nil + } + + return nil + } +} + +// Config applies the given config dsn, whether a path to config.json +// or a database connection string. It receives as well a set of +// custom defaults that will be applied for any unset property of the +// config loaded from the dsn on top of the normal defaults +func Config(dsn string, readOnly bool, configDefaults *model.Config) Option { + return func(ps *PlatformService) error { + configStore, err := config.NewStoreFromDSN(dsn, readOnly, configDefaults, true) + if err != nil { + return fmt.Errorf("failed to apply Config option: %w", err) + } + + ps.configStore = configStore + + return nil + } +} + +// ConfigStore applies the given config store, typically to replace the traditional sources with a memory store for testing. +func ConfigStore(configStore *config.Store) Option { + return func(ps *PlatformService) error { + ps.configStore = configStore + + return nil + } +} + +func StartMetrics() Option { + return func(ps *PlatformService) error { + ps.startMetrics = true + return nil + } +} + +func SetLogger(logger *mlog.Logger) Option { + return func(ps *PlatformService) error { + ps.SetLogger(logger) + + return nil + } +} + +func SetCluster(cluster einterfaces.ClusterInterface) Option { + return func(ps *PlatformService) error { + ps.clusterIFace = cluster + return nil + } +} diff --git a/app/platform/searchengine.go b/app/platform/searchengine.go new file mode 100644 index 0000000000..7b3bfcee26 --- /dev/null +++ b/app/platform/searchengine.go @@ -0,0 +1,87 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +func (ps *PlatformService) StartSearchEngine() (string, string) { + if ps.SearchEngine.ElasticsearchEngine != nil && ps.SearchEngine.ElasticsearchEngine.IsActive() { + ps.Go(func() { + if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil { + ps.Log().Error(err.Error()) + } + }) + } + + configListenerId := ps.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { + if ps.SearchEngine == nil { + return + } + ps.SearchEngine.UpdateConfig(newConfig) + + if ps.SearchEngine.ElasticsearchEngine != nil && !*oldConfig.ElasticsearchSettings.EnableIndexing && *newConfig.ElasticsearchSettings.EnableIndexing { + ps.Go(func() { + if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil { + mlog.Error(err.Error()) + } + }) + } else if ps.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.EnableIndexing && !*newConfig.ElasticsearchSettings.EnableIndexing { + ps.Go(func() { + if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil { + mlog.Error(err.Error()) + } + }) + } else if ps.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionURL != *newConfig.ElasticsearchSettings.ConnectionURL || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff { + ps.Go(func() { + if *oldConfig.ElasticsearchSettings.EnableIndexing { + if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil { + mlog.Error(err.Error()) + } + if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil { + mlog.Error(err.Error()) + } + } + }) + } + }) + + licenseListenerId := ps.AddLicenseListener(func(oldLicense, newLicense *model.License) { + if ps.SearchEngine == nil { + return + } + if oldLicense == nil && newLicense != nil { + if ps.SearchEngine.ElasticsearchEngine != nil && ps.SearchEngine.ElasticsearchEngine.IsActive() { + ps.Go(func() { + if err := ps.SearchEngine.ElasticsearchEngine.Start(); err != nil { + mlog.Error(err.Error()) + } + }) + } + } else if oldLicense != nil && newLicense == nil { + if ps.SearchEngine.ElasticsearchEngine != nil { + ps.Go(func() { + if err := ps.SearchEngine.ElasticsearchEngine.Stop(); err != nil { + mlog.Error(err.Error()) + } + }) + } + } + }) + + return configListenerId, licenseListenerId +} + +func (ps *PlatformService) StopSearchEngine() { + ps.RemoveConfigListener(ps.searchConfigListenerId) + ps.RemoveLicenseListener(ps.searchLicenseListenerId) + if ps.SearchEngine != nil && ps.SearchEngine.ElasticsearchEngine != nil && ps.SearchEngine.ElasticsearchEngine.IsActive() { + ps.SearchEngine.ElasticsearchEngine.Stop() + } + if ps.SearchEngine != nil && ps.SearchEngine.BleveEngine != nil && ps.SearchEngine.BleveEngine.IsActive() { + ps.SearchEngine.BleveEngine.Stop() + } +} diff --git a/app/platform/server_license.go b/app/platform/server_license.go deleted file mode 100644 index 3ccc95999b..0000000000 --- a/app/platform/server_license.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. -// See LICENSE.txt for license information. - -package platform - -import ( - "github.com/mattermost/mattermost-server/v6/model" -) - -// License returns the license stored in the server struct. -// This should be removed with MM-45839 -func (ps *PlatformService) License() *model.License { - license, _ := ps.licenseValue.Load().(*model.License) - return license -} - -func (ps *PlatformService) SetLicense(license *model.License) { - ps.licenseValue.Store(license) -} diff --git a/app/platform/service.go b/app/platform/service.go index 4f85ac5c52..69cba002e0 100644 --- a/app/platform/service.go +++ b/app/platform/service.go @@ -5,57 +5,293 @@ package platform import ( "fmt" + "hash/maphash" + "net/http" + "runtime" "sync" "sync/atomic" "github.com/mattermost/mattermost-server/v6/app/featureflag" "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/einterfaces" + "github.com/mattermost/mattermost-server/v6/jobs" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/plugin" + "github.com/mattermost/mattermost-server/v6/services/cache" + "github.com/mattermost/mattermost-server/v6/services/searchengine" + "github.com/mattermost/mattermost-server/v6/services/searchengine/bleveengine" "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store" + "github.com/mattermost/mattermost-server/v6/store/localcachelayer" + "github.com/mattermost/mattermost-server/v6/store/retrylayer" + "github.com/mattermost/mattermost-server/v6/store/searchlayer" + "github.com/mattermost/mattermost-server/v6/store/sqlstore" + "github.com/mattermost/mattermost-server/v6/store/timerlayer" ) // PlatformService is the service for the platform related tasks. It is // responsible for non-entity related functionalities that are required // by a product such as database access, configuration access, licensing etc. type PlatformService struct { - serviceConfig ServiceConfig + sqlStore *sqlstore.SqlStore + Store store.Store + newStore func() (store.Store, error) + + WebSocketRouter *WebSocketRouter + + serviceConfig *ServiceConfig configStore *config.Store + cacheProvider cache.Provider + statusCache cache.Cache + sessionCache cache.Cache + sessionPool sync.Pool + + asymmetricSigningKey atomic.Value + clientConfig atomic.Value + clientConfigHash atomic.Value + limitedClientConfig atomic.Value + logger *mlog.Logger notificationsLogger *mlog.Logger - metrics *platformMetrics + startMetrics bool + metrics *platformMetrics featureFlagSynchronizerMutex sync.Mutex featureFlagSynchronizer *featureflag.Synchronizer featureFlagStop chan struct{} featureFlagStopped chan struct{} - licenseValue atomic.Value - telemetryId string + licenseValue atomic.Value + clientLicenseValue atomic.Value + licenseListeners map[string]func(*model.License, *model.License) + licenseManager einterfaces.LicenseInterface - cluster einterfaces.ClusterInterface + telemetryId string + configListenerId string + licenseListenerId string + + clusterLeaderListeners sync.Map + clusterIFace einterfaces.ClusterInterface + Busy *Busy + + SearchEngine *searchengine.Broker + searchConfigListenerId string + searchLicenseListenerId string + + Jobs *jobs.JobServer + + hubs []*Hub + hashSeed maphash.Seed + + goroutineCount int32 + goroutineExitSignal chan struct{} + goroutineBuffered chan struct{} + + additionalClusterHandlers map[model.ClusterEvent]einterfaces.ClusterMessageHandler + sharedChannelService SharedChannelServiceIFace + + pluginEnv *plugin.Environment } // New creates a new PlatformService. -func New(sc ServiceConfig) (*PlatformService, error) { +func New(sc ServiceConfig, options ...Option) (*PlatformService, error) { if err := sc.validate(); err != nil { return nil, err } + // Step 0: Create the PlatformService. + // ConfigStore is and should be handled on a upper level. ps := &PlatformService{ - serviceConfig: sc, - configStore: sc.ConfigStore, - cluster: sc.Cluster, + serviceConfig: &sc, + Store: sc.Store, + configStore: sc.ConfigStore, + clusterIFace: sc.Cluster, + hashSeed: maphash.MakeSeed(), + goroutineExitSignal: make(chan struct{}, 1), + goroutineBuffered: make(chan struct{}, runtime.NumCPU()), + WebSocketRouter: &WebSocketRouter{ + handlers: make(map[string]webSocketHandler), + }, + sessionPool: sync.Pool{ + New: func() any { + return &model.Session{} + }, + }, + licenseListeners: map[string]func(*model.License, *model.License){}, + additionalClusterHandlers: map[model.ClusterEvent]einterfaces.ClusterMessageHandler{}, } + // Step 1: Cache provider. + // At the moment we only have this implementation + // in the future the cache provider will be built based on the loaded config + ps.cacheProvider = cache.NewProvider() + if err2 := ps.cacheProvider.Connect(); err2 != nil { + return nil, fmt.Errorf("unable to connect to cache provider: %w", err2) + } + + // Apply options, some of the options overrides the default config actually. + for _, option := range options { + if err := option(ps); err != nil { + return nil, fmt.Errorf("failed to apply option: %w", err) + } + } + + // Step 2: Start logging. if err := ps.initLogging(); err != nil { return nil, fmt.Errorf("failed to initialize logging: %w", err) } - if err := ps.resetMetrics(sc.Metrics, ps.configStore.Get); err != nil { + // This is called after initLogging() to avoid a race condition. + mlog.Info("Server is initializing...", mlog.String("go_version", runtime.Version())) + + // Step 3: Search Engine + searchEngine := searchengine.NewBroker(ps.Config()) + bleveEngine := bleveengine.NewBleveEngine(ps.Config()) + if err := bleveEngine.Start(); err != nil { return nil, err } + searchEngine.RegisterBleveEngine(bleveEngine) + ps.SearchEngine = searchEngine + + // Step 4: Init Enterprise + // Depends on step 3 (s.SearchEngine must be non-nil) + ps.initEnterprise() + + // Step 5: Store. + // Depends on Step 1 (config), 4 (metrics, cluster) and 5 (cacheProvider). + if ps.newStore == nil { + ps.newStore = func() (store.Store, error) { + ps.sqlStore = sqlstore.New(ps.Config().SqlSettings, ps.Metrics()) + + lcl, err2 := localcachelayer.NewLocalCacheLayer( + retrylayer.New(ps.sqlStore), + ps.Metrics(), + ps.clusterIFace, + ps.cacheProvider, + ) + if err2 != nil { + return nil, fmt.Errorf("cannot create local cache layer: %w", err2) + } + + searchStore := searchlayer.NewSearchLayer( + lcl, + ps.SearchEngine, + ps.Config(), + ) + + ps.AddConfigListener(func(prevCfg, cfg *model.Config) { + searchStore.UpdateConfig(cfg) + }) + + license := ps.License() + ps.sqlStore.UpdateLicense(license) + ps.AddLicenseListener(func(oldLicense, newLicense *model.License) { + ps.sqlStore.UpdateLicense(newLicense) + }) + + return timerlayer.New( + searchStore, + ps.Metrics(), + ), nil + } + } + + var err error + ps.Store, err = ps.newStore() + if err != nil { + return nil, fmt.Errorf("cannot create store: %w", err) + } + + // Needed before loading license + ps.statusCache, err = ps.cacheProvider.NewCache(&cache.CacheOptions{ + Size: model.StatusCacheSize, + Striped: true, + StripedBuckets: maxInt(runtime.NumCPU()-1, 1), + }) + if err != nil { + return nil, fmt.Errorf("unable to create status cache: %w", err) + } + + ps.sessionCache, err = ps.cacheProvider.NewCache(&cache.CacheOptions{ + Size: model.SessionCacheSize, + Striped: true, + StripedBuckets: maxInt(runtime.NumCPU()-1, 1), + }) + if err != nil { + return nil, fmt.Errorf("could not create session cache: %w", err) + } + + if model.BuildEnterpriseReady == "true" { + ps.LoadLicense() + } + + if metricsInterface != nil { + sc.Metrics = metricsInterface(ps, *ps.configStore.Get().SqlSettings.DriverName, *ps.configStore.Get().SqlSettings.DataSource) + } + + if ps.startMetrics { + if err = ps.resetMetrics(sc.Metrics, ps.configStore.Get); err != nil { + return nil, err + } + } + + if err = ps.EnsureAsymmetricSigningKey(); err != nil { + return nil, fmt.Errorf("unable to ensure asymmetric signing key: %w", err) + } + + ps.Busy = NewBusy(ps.clusterIFace) + + ps.configListenerId = ps.AddConfigListener(func(_, _ *model.Config) { + ps.regenerateClientConfig() + + message := model.NewWebSocketEvent(model.WebsocketEventConfigChanged, "", "", "", nil, "") + + message.Add("config", ps.ClientConfigWithComputed()) + ps.Go(func() { + ps.Publish(message) + }) + + if err = ps.ReconfigureLogger(); err != nil { + mlog.Error("Error re-configuring logging after config change", mlog.Err(err)) + return + } + }) + ps.licenseListenerId = ps.AddLicenseListener(func(oldLicense, newLicense *model.License) { + ps.regenerateClientConfig() + + message := model.NewWebSocketEvent(model.WebsocketEventLicenseChanged, "", "", "", nil, "") + message.Add("license", ps.GetSanitizedClientLicense()) + ps.Go(func() { + ps.Publish(message) + }) + + }) + + // Enable developer settings if this is a "dev" build + if model.BuildNumber == "dev" { + ps.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = true }) + } + + ps.AddLicenseListener(func(oldLicense, newLicense *model.License) { + if (oldLicense == nil && newLicense == nil) || !ps.startMetrics { + return + } + + if oldLicense != nil && newLicense != nil && *oldLicense.Features.Metrics == *newLicense.Features.Metrics { + return + } + + if err := ps.RestartMetrics(); err != nil { + ps.logger.Error("Failed to reset metrics server", mlog.Err(err)) + } + }) + + ps.SearchEngine.UpdateConfig(ps.Config()) + searchConfigListenerId, searchLicenseListenerId := ps.StartSearchEngine() + ps.searchConfigListenerId = searchConfigListenerId + ps.searchLicenseListenerId = searchLicenseListenerId return ps, nil } @@ -69,6 +305,8 @@ func (ps *PlatformService) ShutdownMetrics() error { } func (ps *PlatformService) ShutdownConfig() error { + ps.RemoveConfigListener(ps.configListenerId) + if ps.configStore != nil { err := ps.configStore.Close() if err != nil { @@ -86,3 +324,90 @@ func (ps *PlatformService) SetTelemetryId(id string) { func (ps *PlatformService) SetLogger(logger *mlog.Logger) { ps.logger = logger } + +func (ps *PlatformService) initEnterprise() { + if clusterInterface != nil && ps.clusterIFace == nil { + ps.clusterIFace = clusterInterface(ps) + } + + if elasticsearchInterface != nil { + ps.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(ps)) + } + + if licenseInterface != nil { + ps.licenseManager = licenseInterface(ps) + } +} + +func (ps *PlatformService) TotalWebsocketConnections() int { + // This method is only called after the hub is initialized. + // Therefore, no mutex is needed to protect s.hubs. + count := int64(0) + for _, hub := range ps.hubs { + count = count + atomic.LoadInt64(&hub.connectionCount) + } + + return int(count) +} + +func (ps *PlatformService) Shutdown() error { + ps.HubStop() + + ps.RemoveLicenseListener(ps.licenseListenerId) + + if ps.Store != nil { + ps.Store.Close() + } + + if ps.cacheProvider != nil { + if err := ps.cacheProvider.Close(); err != nil { + return fmt.Errorf("unable to cleanly shutdown cache: %w", err) + } + } + + return nil +} + +func (ps *PlatformService) CacheProvider() cache.Provider { + return ps.cacheProvider +} + +func (ps *PlatformService) StatusCache() cache.Cache { + return ps.statusCache +} + +// SetSqlStore is used for plugin testing +func (ps *PlatformService) SetSqlStore(s *sqlstore.SqlStore) { + ps.sqlStore = s +} + +func (ps *PlatformService) SetSharedChannelService(s SharedChannelServiceIFace) { + ps.sharedChannelService = s +} + +func (ps *PlatformService) SetPluginsEnvironment(env *plugin.Environment) { + ps.pluginEnv = env +} + +// GetPluginStatuses meant to be used by cluster implementation +func (ps *PlatformService) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { + if ps.pluginEnv == nil { + return nil, model.NewAppError("GetPluginStatuses", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) + } + + pluginStatuses, err := ps.pluginEnv.Statuses() + if err != nil { + return nil, model.NewAppError("GetPluginStatuses", "app.plugin.get_statuses.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + // Add our cluster ID + for _, status := range pluginStatuses { + if ps.Cluster() != nil { + status.ClusterId = ps.Cluster().GetClusterId() + } else { + status.ClusterId = "" + } + } + + return pluginStatuses, nil +} diff --git a/app/platform/service_test.go b/app/platform/service_test.go new file mode 100644 index 0000000000..e53afaae98 --- /dev/null +++ b/app/platform/service_test.go @@ -0,0 +1,85 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "os" + "testing" + + "github.com/mattermost/mattermost-server/v6/config" + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/store/storetest" + "github.com/stretchr/testify/require" +) + +func TestReadReplicaDisabledBasedOnLicense(t *testing.T) { + cfg := model.Config{} + cfg.SetDefaults() + driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") + if driverName == "" { + driverName = model.DatabaseDriverPostgres + } + dsn := "" + if driverName == model.DatabaseDriverPostgres { + dsn = os.Getenv("TEST_DATABASE_POSTGRESQL_DSN") + } else { + dsn = os.Getenv("TEST_DATABASE_MYSQL_DSN") + } + cfg.SqlSettings = *storetest.MakeSqlSettings(driverName, false) + if dsn != "" { + cfg.SqlSettings.DataSource = &dsn + } + cfg.SqlSettings.DataSourceReplicas = []string{*cfg.SqlSettings.DataSource} + cfg.SqlSettings.DataSourceSearchReplicas = []string{*cfg.SqlSettings.DataSource} + + t.Run("Read Replicas with no License", func(t *testing.T) { + configStore := config.NewTestMemoryStore() + configStore.Set(&cfg) + ps, err := New(ServiceConfig{ + ConfigStore: configStore, + }) + require.NoError(t, err) + require.Same(t, ps.sqlStore.GetMasterX(), ps.sqlStore.GetReplicaX()) + require.Len(t, ps.Config().SqlSettings.DataSourceReplicas, 1) + }) + + t.Run("Read Replicas With License", func(t *testing.T) { + configStore := config.NewTestMemoryStore() + configStore.Set(&cfg) + ps, err := New(ServiceConfig{ + ConfigStore: configStore, + }, func(ps *PlatformService) error { + ps.licenseValue.Store(model.NewTestLicense()) + return nil + }) + require.NoError(t, err) + require.NotSame(t, ps.sqlStore.GetMasterX(), ps.sqlStore.GetReplicaX()) + require.Len(t, ps.Config().SqlSettings.DataSourceReplicas, 1) + }) + + t.Run("Search Replicas with no License", func(t *testing.T) { + configStore := config.NewTestMemoryStore() + configStore.Set(&cfg) + ps, err := New(ServiceConfig{ + ConfigStore: configStore, + }) + require.NoError(t, err) + require.Same(t, ps.sqlStore.GetMasterX(), ps.sqlStore.GetSearchReplicaX()) + require.Len(t, ps.Config().SqlSettings.DataSourceSearchReplicas, 1) + }) + + t.Run("Search Replicas With License", func(t *testing.T) { + configStore := config.NewTestMemoryStore() + configStore.Set(&cfg) + ps, err := New(ServiceConfig{ + ConfigStore: configStore, + }, func(ps *PlatformService) error { + ps.licenseValue.Store(model.NewTestLicense()) + return nil + }) + require.NoError(t, err) + require.NotSame(t, ps.sqlStore.GetMasterX(), ps.sqlStore.GetSearchReplicaX()) + require.Len(t, ps.Config().SqlSettings.DataSourceSearchReplicas, 1) + }) +} diff --git a/app/platform/session.go b/app/platform/session.go new file mode 100644 index 0000000000..1b085f7dd1 --- /dev/null +++ b/app/platform/session.go @@ -0,0 +1,262 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "context" + "fmt" + "time" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store/sqlstore" +) + +func (ps *PlatformService) ReturnSessionToPool(session *model.Session) { + if session != nil { + session.Id = "" + ps.sessionPool.Put(session) + } +} + +func (ps *PlatformService) CreateSession(session *model.Session) (*model.Session, error) { + session.Token = "" + + session, err := ps.Store.Session().Save(session) + if err != nil { + return nil, err + } + + ps.AddSessionToCache(session) + + return session, nil +} + +func (ps *PlatformService) GetSessionContext(ctx context.Context, token string) (*model.Session, error) { + return ps.Store.Session().Get(ctx, token) +} + +func (ps *PlatformService) GetSessions(userID string) ([]*model.Session, error) { + return ps.Store.Session().GetSessions(userID) +} + +func (ps *PlatformService) AddSessionToCache(session *model.Session) { + ps.sessionCache.SetWithExpiry(session.Token, session, time.Duration(int64(*ps.Config().ServiceSettings.SessionCacheInMinutes))*time.Minute) +} + +func (ps *PlatformService) SessionCacheLength() int { + if l, err := ps.sessionCache.Len(); err == nil { + return l + } + return 0 +} + +func (ps *PlatformService) ClearUserSessionCacheLocal(userID string) { + if keys, err := ps.sessionCache.Keys(); err == nil { + var session *model.Session + for _, key := range keys { + if err := ps.sessionCache.Get(key, &session); err == nil { + if session.UserId == userID { + ps.sessionCache.Remove(key) + if m := ps.metricsImpl(); m != nil { + m.IncrementMemCacheInvalidationCounterSession() + } + } + } + } + } +} + +func (ps *PlatformService) ClearAllUsersSessionCacheLocal() { + ps.sessionCache.Purge() +} + +func (ps *PlatformService) ClearUserSessionCache(userID string) { + ps.ClearUserSessionCacheLocal(userID) + + if ps.clusterIFace != nil { + msg := &model.ClusterMessage{ + Event: model.ClusterEventClearSessionCacheForUser, + SendType: model.ClusterSendReliable, + Data: []byte(userID), + } + ps.clusterIFace.SendClusterMessage(msg) + } +} + +func (ps *PlatformService) ClearAllUsersSessionCache() { + ps.ClearAllUsersSessionCacheLocal() + + if ps.clusterIFace != nil { + msg := &model.ClusterMessage{ + Event: model.ClusterEventClearSessionCacheForAllUsers, + SendType: model.ClusterSendReliable, + } + ps.clusterIFace.SendClusterMessage(msg) + } +} + +func (ps *PlatformService) GetSession(token string) (*model.Session, error) { + var session = ps.sessionPool.Get().(*model.Session) + if err := ps.sessionCache.Get(token, session); err == nil { + if m := ps.metricsImpl(); m != nil { + m.IncrementMemCacheHitCounterSession() + } + } else { + if m := ps.metricsImpl(); m != nil { + m.IncrementMemCacheMissCounterSession() + } + } + + if session.Id != "" { + return session, nil + } + + return ps.GetSessionContext(sqlstore.WithMaster(context.Background()), token) +} + +func (ps *PlatformService) GetSessionByID(sessionID string) (*model.Session, error) { + return ps.Store.Session().Get(context.Background(), sessionID) +} + +func (ps *PlatformService) RevokeSessionsFromAllUsers() error { + // revoke tokens before sessions so they can't be used to relogin + nErr := ps.Store.OAuth().RemoveAllAccessData() + if nErr != nil { + return fmt.Errorf("%s: %w", nErr.Error(), DeleteAllAccessDataError) + } + err := ps.Store.Session().RemoveAllSessions() + if err != nil { + return err + } + + ps.ClearAllUsersSessionCache() + return nil +} + +func (ps *PlatformService) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) error { + sessions, err := ps.Store.Session().GetSessions(userID) + if err != nil { + return err + } + for _, session := range sessions { + if session.DeviceId == deviceID && session.Id != currentSessionId { + mlog.Debug("Revoking sessionId for userId. Re-login with the same device Id", mlog.String("session_id", session.Id), mlog.String("user_id", userID)) + if err := ps.RevokeSession(session); err != nil { + mlog.Warn("Could not revoke session for device", mlog.String("device_id", deviceID), mlog.Err(err)) + } + } + } + + return nil +} + +func (ps *PlatformService) RevokeSession(session *model.Session) error { + if session.IsOAuth { + if err := ps.RevokeAccessToken(session.Token); err != nil { + return err + } + } else { + if err := ps.Store.Session().Remove(session.Id); err != nil { + return fmt.Errorf("%s: %w", err.Error(), DeleteSessionError) + } + } + + ps.ClearUserSessionCache(session.UserId) + + return nil +} + +func (ps *PlatformService) RevokeAccessToken(token string) error { + session, _ := ps.GetSession(token) + + defer ps.ReturnSessionToPool(session) + + schan := make(chan error, 1) + go func() { + schan <- ps.Store.Session().Remove(token) + close(schan) + }() + + if _, err := ps.Store.OAuth().GetAccessData(token); err != nil { + return fmt.Errorf("%s: %w", err.Error(), GetTokenError) + } + + if err := ps.Store.OAuth().RemoveAccessData(token); err != nil { + return fmt.Errorf("%s: %w", err.Error(), DeleteTokenError) + } + + if err := <-schan; err != nil { + return fmt.Errorf("%s: %w", err.Error(), DeleteSessionError) + } + + if session != nil { + ps.ClearUserSessionCache(session.UserId) + } + + return nil +} + +// SetSessionExpireInHours sets the session's expiry the specified number of hours +// relative to either the session creation date or the current time, depending +// on the `ExtendSessionOnActivity` config setting. +func (ps *PlatformService) SetSessionExpireInHours(session *model.Session, hours int) { + if session.CreateAt == 0 || *ps.Config().ServiceSettings.ExtendSessionLengthWithActivity { + session.ExpiresAt = model.GetMillis() + (1000 * 60 * 60 * int64(hours)) + } else { + session.ExpiresAt = session.CreateAt + (1000 * 60 * 60 * int64(hours)) + } +} + +func (ps *PlatformService) ExtendSessionExpiry(session *model.Session, newExpiry int64) error { + if err := ps.Store.Session().UpdateExpiresAt(session.Id, newExpiry); err != nil { + return err + } + + // Update local cache. No need to invalidate cache for cluster as the session cache timeout + // ensures each node will get an extended expiry within the next 10 minutes. + // Worst case is another node may generate a redundant expiry update. + session.ExpiresAt = newExpiry + ps.AddSessionToCache(session) + + return nil +} + +func (ps *PlatformService) UpdateSessionsIsGuest(userID string, isGuest bool) error { + sessions, err := ps.GetSessions(userID) + if err != nil { + return err + } + + for _, session := range sessions { + session.AddProp(model.SessionPropIsGuest, fmt.Sprintf("%t", isGuest)) + err := ps.Store.Session().UpdateProps(session) + if err != nil { + mlog.Warn("Unable to update isGuest session", mlog.Err(err)) + continue + } + ps.AddSessionToCache(session) + } + return nil +} + +func (ps *PlatformService) RevokeAllSessions(userID string) error { + sessions, err := ps.Store.Session().GetSessions(userID) + if err != nil { + return fmt.Errorf("%s: %w", err.Error(), GetSessionError) + } + for _, session := range sessions { + if session.IsOAuth { + ps.RevokeAccessToken(session.Token) + } else { + if err := ps.Store.Session().Remove(session.Id); err != nil { + return fmt.Errorf("%s: %w", err.Error(), DeleteSessionError) + } + } + } + + ps.ClearUserSessionCache(userID) + + return nil +} diff --git a/app/users/session_test.go b/app/platform/session_test.go similarity index 79% rename from app/users/session_test.go rename to app/platform/session_test.go index 4197a28cc8..fcad0361c5 100644 --- a/app/users/session_test.go +++ b/app/platform/session_test.go @@ -1,7 +1,7 @@ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. -package users +package platform import ( "testing" @@ -33,23 +33,23 @@ func TestCache(t *testing.T) { UserId: model.NewId(), } - th.service.sessionCache.SetWithExpiry(session.Token, session, 5*time.Minute) - th.service.sessionCache.SetWithExpiry(session2.Token, session2, 5*time.Minute) + th.Service.sessionCache.SetWithExpiry(session.Token, session, 5*time.Minute) + th.Service.sessionCache.SetWithExpiry(session2.Token, session2, 5*time.Minute) - keys, err := th.service.sessionCache.Keys() + keys, err := th.Service.sessionCache.Keys() require.NoError(t, err) require.NotEmpty(t, keys) - th.service.ClearUserSessionCache(session.UserId) + th.Service.ClearUserSessionCache(session.UserId) - rkeys, err := th.service.sessionCache.Keys() + rkeys, err := th.Service.sessionCache.Keys() require.NoError(t, err) require.Lenf(t, rkeys, len(keys)-1, "should have one less: %d - %d != 1", len(keys), len(rkeys)) require.NotEmpty(t, rkeys) - th.service.ClearAllUsersSessionCache() + th.Service.ClearAllUsersSessionCache() - rkeys, err = th.service.sessionCache.Keys() + rkeys, err = th.Service.sessionCache.Keys() require.NoError(t, err) require.Empty(t, rkeys) } @@ -79,7 +79,7 @@ func TestSetSessionExpireInHours(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - th.UpdateConfig(func(cfg *model.Config) { + th.Service.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExtendSessionLengthWithActivity = tt.extend }) var create int64 @@ -91,7 +91,7 @@ func TestSetSessionExpireInHours(t *testing.T) { CreateAt: create, ExpiresAt: model.GetMillis() + dayInMillis, } - th.service.SetSessionExpireInHours(session, tt.days*24) + th.Service.SetSessionExpireInHours(session, tt.days*24) // must be within 5 seconds of expected time. require.GreaterOrEqual(t, session.ExpiresAt, tt.want-grace) @@ -104,7 +104,7 @@ func TestOAuthRevokeAccessToken(t *testing.T) { th := Setup(t) defer th.TearDown() - err := th.service.RevokeAccessToken(model.NewRandomString(16)) + err := th.Service.RevokeAccessToken(model.NewRandomString(16)) require.Error(t, err, "Should have failed due to an incorrect token") session := &model.Session{} @@ -112,10 +112,10 @@ func TestOAuthRevokeAccessToken(t *testing.T) { session.UserId = model.NewId() session.Token = model.NewId() session.Roles = model.SystemUserRoleId - th.service.SetSessionExpireInHours(session, 24) + th.Service.SetSessionExpireInHours(session, 24) - session, _ = th.service.CreateSession(session) - err = th.service.RevokeAccessToken(session.Token) + session, _ = th.Service.CreateSession(session) + err = th.Service.RevokeAccessToken(session.Token) require.Error(t, err, "Should have failed does not have an access token") accessData := &model.AccessData{} @@ -125,9 +125,9 @@ func TestOAuthRevokeAccessToken(t *testing.T) { accessData.ClientId = model.NewId() accessData.ExpiresAt = session.ExpiresAt - _, nErr := th.service.oAuthStore.SaveAccessData(accessData) + _, nErr := th.Service.Store.OAuth().SaveAccessData(accessData) require.NoError(t, nErr) - err = th.service.RevokeAccessToken(accessData.Token) + err = th.Service.RevokeAccessToken(accessData.Token) require.NoError(t, err) } diff --git a/app/shared_channel_notifier.go b/app/platform/shared_channel_notifier.go similarity index 76% rename from app/shared_channel_notifier.go rename to app/platform/shared_channel_notifier.go index 59aaefb1b8..2e0bdafc9e 100644 --- a/app/shared_channel_notifier.go +++ b/app/platform/shared_channel_notifier.go @@ -1,7 +1,7 @@ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. -package app +package platform import ( "context" @@ -29,10 +29,13 @@ var sharedChannelEventsForInvitation model.StringArray = []string{ // SharedChannelSyncHandler is called when a websocket event is received by a cluster node. // Only on the leader node it will notify the sync service to perform necessary updates to the remote for the given // shared channel. -func (s *Server) SharedChannelSyncHandler(event *model.WebSocketEvent) { - syncService := s.GetSharedChannelSyncService() +func (ps *PlatformService) SharedChannelSyncHandler(event *model.WebSocketEvent) { + syncService := ps.sharedChannelService + if syncService == nil { + return + } if isEligibleForEvents(syncService, event, sharedChannelEventsForSync) { - err := handleContentSync(s, syncService, event) + err := handleContentSync(ps, syncService, event) if err != nil { mlog.Warn( err.Error(), @@ -41,7 +44,7 @@ func (s *Server) SharedChannelSyncHandler(event *model.WebSocketEvent) { ) } } else if isEligibleForEvents(syncService, event, sharedChannelEventsForInvitation) { - err := handleInvitation(s, syncService, event) + err := handleInvitation(ps, syncService, event) if err != nil { mlog.Warn( err.Error(), @@ -68,8 +71,8 @@ func syncServiceEnabled(syncService SharedChannelServiceIFace) bool { syncService.Active() } -func handleContentSync(s *Server, syncService SharedChannelServiceIFace, event *model.WebSocketEvent) error { - channel, err := findChannel(s, event.GetBroadcast().ChannelId) +func handleContentSync(ps *PlatformService, syncService SharedChannelServiceIFace, event *model.WebSocketEvent) error { + channel, err := findChannel(ps, event.GetBroadcast().ChannelId) if err != nil { return err } @@ -81,8 +84,8 @@ func handleContentSync(s *Server, syncService SharedChannelServiceIFace, event * return nil } -func handleInvitation(s *Server, syncService SharedChannelServiceIFace, event *model.WebSocketEvent) error { - channel, err := findChannel(s, event.GetBroadcast().ChannelId) +func handleInvitation(ps *PlatformService, syncService SharedChannelServiceIFace, event *model.WebSocketEvent) error { + channel, err := findChannel(ps, event.GetBroadcast().ChannelId) if err != nil { return err } @@ -91,7 +94,7 @@ func handleInvitation(s *Server, syncService SharedChannelServiceIFace, event *m return nil } - creator, err := getUserFromEvent(s, event, "creator_id") + creator, err := getUserFromEvent(ps, event, "creator_id") if err != nil { return err } @@ -103,7 +106,7 @@ func handleInvitation(s *Server, syncService SharedChannelServiceIFace, event *m return nil } - participant, err := getUserFromEvent(s, event, "teammate_id") + participant, err := getUserFromEvent(ps, event, "teammate_id") if err != nil { return err } @@ -112,7 +115,7 @@ func handleInvitation(s *Server, syncService SharedChannelServiceIFace, event *m return nil } - rc, err := s.Store.RemoteCluster().Get(*participant.RemoteId) + rc, err := ps.Store.RemoteCluster().Get(*participant.RemoteId) if err != nil { return errors.Wrap(err, fmt.Sprintf("couldn't find remote cluster %s, for creating shared channel invitation for a DM", *participant.RemoteId)) } @@ -120,13 +123,13 @@ func handleInvitation(s *Server, syncService SharedChannelServiceIFace, event *m return syncService.SendChannelInvite(channel, creator.Id, rc, sharedchannel.WithDirectParticipantID(creator.Id), sharedchannel.WithDirectParticipantID(participant.Id)) } -func getUserFromEvent(s *Server, event *model.WebSocketEvent, key string) (*model.User, error) { +func getUserFromEvent(ps *PlatformService, event *model.WebSocketEvent, key string) (*model.User, error) { userID, ok := event.GetData()[key].(string) if !ok || userID == "" { return nil, fmt.Errorf("received websocket message that is eligible for sending an invitation but message does not have `%s` present", key) } - user, err := s.Store.User().Get(context.Background(), userID) + user, err := ps.Store.User().Get(context.Background(), userID) if err != nil { return nil, errors.Wrap(err, "couldn't find user for creating shared channel invitation for a DM") } @@ -134,7 +137,7 @@ func getUserFromEvent(s *Server, event *model.WebSocketEvent, key string) (*mode return user, nil } -func findChannel(server *Server, channelId string) (*model.Channel, error) { +func findChannel(server *PlatformService, channelId string) (*model.Channel, error) { channel, err := server.Store.Channel().Get(channelId, true) if err != nil { return nil, errors.Wrap(err, "received websocket message that is eligible for shared channel sync but channel does not exist") diff --git a/app/shared_channel_notifier_test.go b/app/platform/shared_channel_notifier_test.go similarity index 71% rename from app/shared_channel_notifier_test.go rename to app/platform/shared_channel_notifier_test.go index 6800cc8957..e439b76a71 100644 --- a/app/shared_channel_notifier_test.go +++ b/app/platform/shared_channel_notifier_test.go @@ -1,14 +1,14 @@ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. -package app +package platform import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/mattermost/mattermost-server/v6/model" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestServerSyncSharedChannelHandler(t *testing.T) { @@ -18,9 +18,9 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService := NewMockSharedChannelService(nil) mockService.active = false - th.App.ch.srv.SetSharedChannelSyncService(mockService) + th.Service.SetSharedChannelService(mockService) - th.App.ch.srv.SharedChannelSyncHandler(&model.WebSocketEvent{}) + th.Service.SharedChannelSyncHandler(&model.WebSocketEvent{}) assert.Empty(t, mockService.channelNotifications) }) @@ -30,12 +30,12 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService := NewMockSharedChannelService(nil) mockService.active = true - th.App.ch.srv.SetSharedChannelSyncService(mockService) - channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) + th.Service.SetSharedChannelService(mockService) + channel := th.CreateChannel(th.BasicTeam, WithShared(true)) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventAddedToTeam, model.NewId(), channel.Id, "", nil, "") - th.App.ch.srv.SharedChannelSyncHandler(websocketEvent) + th.Service.SharedChannelSyncHandler(websocketEvent) assert.Empty(t, mockService.channelNotifications) }) @@ -45,11 +45,11 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService := NewMockSharedChannelService(nil) mockService.active = true - th.App.ch.srv.SetSharedChannelSyncService(mockService) + th.Service.SetSharedChannelService(mockService) websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), model.NewId(), "", nil, "") - th.App.ch.srv.SharedChannelSyncHandler(websocketEvent) + th.Service.SharedChannelSyncHandler(websocketEvent) assert.Empty(t, mockService.channelNotifications) }) @@ -59,13 +59,13 @@ func TestServerSyncSharedChannelHandler(t *testing.T) { mockService := NewMockSharedChannelService(nil) mockService.active = true - th.App.ch.srv.SetSharedChannelSyncService(mockService) + th.Service.SetSharedChannelService(mockService) - channel := th.CreateChannel(th.Context, th.BasicTeam, WithShared(true)) - websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, model.NewId(), channel.Id, "", nil, "") + channel := th.CreateChannel(th.BasicTeam, WithShared(true)) + websocketEvent := model.NewWebSocketEvent(model.WebsocketEventPosted, th.BasicTeam.Id, channel.Id, "", nil, "") - th.App.ch.srv.SharedChannelSyncHandler(websocketEvent) - assert.Len(t, mockService.channelNotifications, 1) + th.Service.SharedChannelSyncHandler(websocketEvent) + require.Len(t, mockService.channelNotifications, 1) assert.Equal(t, channel.Id, mockService.channelNotifications[0]) }) } diff --git a/app/platform/shared_channel_service_iface.go b/app/platform/shared_channel_service_iface.go new file mode 100644 index 0000000000..acb55977d9 --- /dev/null +++ b/app/platform/shared_channel_service_iface.go @@ -0,0 +1,72 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/services/sharedchannel" +) + +// SharedChannelServiceIFace is the interface to the shared channel service +type SharedChannelServiceIFace interface { + Shutdown() error + Start() error + NotifyChannelChanged(channelId string) + NotifyUserProfileChanged(userID string) + SendChannelInvite(channel *model.Channel, userId string, rc *model.RemoteCluster, options ...sharedchannel.InviteOption) error + Active() bool +} + +type MockOptionSharedChannelService func(service *mockSharedChannelService) + +func MockOptionSharedChannelServiceWithActive(active bool) MockOptionSharedChannelService { + return func(mrcs *mockSharedChannelService) { + mrcs.active = active + } +} + +func NewMockSharedChannelService(service SharedChannelServiceIFace, options ...MockOptionSharedChannelService) *mockSharedChannelService { + mrcs := &mockSharedChannelService{service, true, []string{}, []string{}, 0} + for _, option := range options { + option(mrcs) + } + return mrcs +} + +type mockSharedChannelService struct { + SharedChannelServiceIFace + active bool + channelNotifications []string + userProfileNotifications []string + numInvitations int +} + +func (mrcs *mockSharedChannelService) NotifyChannelChanged(channelId string) { + mrcs.channelNotifications = append(mrcs.channelNotifications, channelId) +} + +func (mrcs *mockSharedChannelService) NotifyUserProfileChanged(userId string) { + mrcs.userProfileNotifications = append(mrcs.userProfileNotifications, userId) +} + +func (mrcs *mockSharedChannelService) Shutdown() error { + return nil +} + +func (mrcs *mockSharedChannelService) Start() error { + return nil +} + +func (mrcs *mockSharedChannelService) Active() bool { + return mrcs.active +} + +func (mrcs *mockSharedChannelService) SendChannelInvite(channel *model.Channel, userId string, rc *model.RemoteCluster, options ...sharedchannel.InviteOption) error { + mrcs.numInvitations += 1 + return nil +} + +func (mrcs *mockSharedChannelService) NumInvitations() int { + return mrcs.numInvitations +} diff --git a/app/platform/status.go b/app/platform/status.go new file mode 100644 index 0000000000..b133d3e2f7 --- /dev/null +++ b/app/platform/status.go @@ -0,0 +1,214 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "encoding/json" + "errors" + "net/http" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" + "github.com/mattermost/mattermost-server/v6/store" +) + +func (ps *PlatformService) AddStatusCacheSkipClusterSend(status *model.Status) { + ps.statusCache.Set(status.UserId, status) +} + +func (ps *PlatformService) AddStatusCache(status *model.Status) { + ps.AddStatusCacheSkipClusterSend(status) + + if ps.Cluster() != nil { + statusJSON, err := json.Marshal(status) + if err != nil { + ps.logger.Warn("Failed to encode status to JSON", mlog.Err(err)) + } + msg := &model.ClusterMessage{ + Event: model.ClusterEventUpdateStatus, + SendType: model.ClusterSendBestEffort, + Data: statusJSON, + } + ps.Cluster().SendClusterMessage(msg) + } +} + +func (ps *PlatformService) GetAllStatuses() map[string]*model.Status { + if !*ps.Config().ServiceSettings.EnableUserStatuses { + return map[string]*model.Status{} + } + + statusMap := map[string]*model.Status{} + if userIDs, err := ps.statusCache.Keys(); err == nil { + for _, userID := range userIDs { + status := ps.GetStatusFromCache(userID) + if status != nil { + statusMap[userID] = status + } + } + } + return statusMap +} + +func (ps *PlatformService) GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) { + if !*ps.Config().ServiceSettings.EnableUserStatuses { + return map[string]any{}, nil + } + + statusMap := map[string]any{} + metrics := ps.Metrics() + + missingUserIds := []string{} + for _, userID := range userIDs { + var status *model.Status + if err := ps.statusCache.Get(userID, &status); err == nil { + statusMap[userID] = status.Status + if metrics != nil { + metrics.IncrementMemCacheHitCounter("Status") + } + } else { + missingUserIds = append(missingUserIds, userID) + if metrics != nil { + metrics.IncrementMemCacheMissCounter("Status") + } + } + } + + if len(missingUserIds) > 0 { + statuses, err := ps.Store.Status().GetByIds(missingUserIds) + if err != nil { + return nil, model.NewAppError("GetStatusesByIds", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + for _, s := range statuses { + ps.AddStatusCacheSkipClusterSend(s) + statusMap[s.UserId] = s.Status + } + + } + + // For the case where the user does not have a row in the Status table and cache + for _, userID := range missingUserIds { + if _, ok := statusMap[userID]; !ok { + statusMap[userID] = model.StatusOffline + } + } + + return statusMap, nil +} + +// GetUserStatusesByIds used by apiV4 +func (ps *PlatformService) GetUserStatusesByIds(userIDs []string) ([]*model.Status, *model.AppError) { + if !*ps.Config().ServiceSettings.EnableUserStatuses { + return []*model.Status{}, nil + } + + var statusMap []*model.Status + metrics := ps.Metrics() + + missingUserIds := []string{} + for _, userID := range userIDs { + var status *model.Status + if err := ps.statusCache.Get(userID, &status); err == nil { + statusMap = append(statusMap, status) + if metrics != nil { + metrics.IncrementMemCacheHitCounter("Status") + } + } else { + missingUserIds = append(missingUserIds, userID) + if metrics != nil { + metrics.IncrementMemCacheMissCounter("Status") + } + } + } + + if len(missingUserIds) > 0 { + statuses, err := ps.Store.Status().GetByIds(missingUserIds) + if err != nil { + return nil, model.NewAppError("GetUserStatusesByIds", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + + for _, s := range statuses { + ps.AddStatusCacheSkipClusterSend(s) + } + + statusMap = append(statusMap, statuses...) + + } + + // For the case where the user does not have a row in the Status table and cache + // remove the existing ids from missingUserIds and then create a offline state for the missing ones + // This also return the status offline for the non-existing Ids in the system + for i := 0; i < len(missingUserIds); i++ { + missingUserId := missingUserIds[i] + for _, userMap := range statusMap { + if missingUserId == userMap.UserId { + missingUserIds = append(missingUserIds[:i], missingUserIds[i+1:]...) + i-- + break + } + } + } + for _, userID := range missingUserIds { + statusMap = append(statusMap, &model.Status{UserId: userID, Status: "offline"}) + } + + return statusMap, nil +} + +func (ps *PlatformService) BroadcastStatus(status *model.Status) { + if ps.Busy.IsBusy() { + // this is considered a non-critical service and will be disabled when server busy. + return + } + event := model.NewWebSocketEvent(model.WebsocketEventStatusChange, "", "", status.UserId, nil, "") + event.Add("status", status.Status) + event.Add("user_id", status.UserId) + ps.Publish(event) +} + +func (ps *PlatformService) SaveAndBroadcastStatus(status *model.Status) { + ps.AddStatusCache(status) + + if err := ps.Store.Status().SaveOrUpdate(status); err != nil { + mlog.Warn("Failed to save status", mlog.String("user_id", status.UserId), mlog.Err(err)) + } + + ps.BroadcastStatus(status) +} + +func (ps *PlatformService) GetStatusFromCache(userID string) *model.Status { + var status *model.Status + if err := ps.statusCache.Get(userID, &status); err == nil { + statusCopy := &model.Status{} + *statusCopy = *status + return statusCopy + } + + return nil +} + +func (ps *PlatformService) GetStatus(userID string) (*model.Status, *model.AppError) { + if !*ps.Config().ServiceSettings.EnableUserStatuses { + return &model.Status{}, nil + } + + status := ps.GetStatusFromCache(userID) + if status != nil { + return status, nil + } + + status, err := ps.Store.Status().Get(userID) + if err != nil { + var nfErr *store.ErrNotFound + switch { + case errors.As(err, &nfErr): + return nil, model.NewAppError("GetStatus", "app.status.get.missing.app_error", nil, "", http.StatusNotFound).Wrap(err) + default: + return nil, model.NewAppError("GetStatus", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + } + + return status, nil +} diff --git a/app/platform/status_test.go b/app/platform/status_test.go new file mode 100644 index 0000000000..c0dabc5c98 --- /dev/null +++ b/app/platform/status_test.go @@ -0,0 +1,39 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/mattermost/mattermost-server/v6/model" +) + +func TestSaveStatus(t *testing.T) { + th := Setup(t).InitBasic() + defer th.TearDown() + + user := th.BasicUser + + for _, statusString := range []string{ + model.StatusOnline, + model.StatusAway, + model.StatusDnd, + model.StatusOffline, + } { + t.Run(statusString, func(t *testing.T) { + status := &model.Status{ + UserId: user.Id, + Status: statusString, + } + + th.Service.SaveAndBroadcastStatus(status) + + after, err := th.Service.GetStatus(user.Id) + require.Nil(t, err, "failed to get status after save: %v", err) + require.Equal(t, statusString, after.Status, "failed to save status, got %v, expected %v", after.Status, statusString) + }) + } +} diff --git a/app/platform/utils.go b/app/platform/utils.go new file mode 100644 index 0000000000..240e35655d --- /dev/null +++ b/app/platform/utils.go @@ -0,0 +1,22 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "crypto/sha256" + "encoding/base64" +) + +func getKeyHash(key string) string { + hash := sha256.New() + hash.Write([]byte(key)) + return base64.StdEncoding.EncodeToString(hash.Sum(nil)) +} + +func maxInt(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/app/platform/web_conn.go b/app/platform/web_conn.go new file mode 100644 index 0000000000..2107333428 --- /dev/null +++ b/app/platform/web_conn.go @@ -0,0 +1,836 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/gorilla/websocket" + "github.com/vmihailenco/msgpack/v5" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/plugin" + "github.com/mattermost/mattermost-server/v6/shared/i18n" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +const ( + sendQueueSize = 256 + sendSlowWarn = (sendQueueSize * 50) / 100 + sendFullWarn = (sendQueueSize * 95) / 100 + writeWaitTime = 30 * time.Second + pongWaitTime = 100 * time.Second + pingInterval = (pongWaitTime * 6) / 10 + authCheckInterval = 5 * time.Second + webConnMemberCacheTime = 1000 * 60 * 30 // 30 minutes + deadQueueSize = 128 // Approximated from /proc/sys/net/core/wmem_default / 2048 (avg msg size) +) + +const ( + reconnectFound = "success" + reconnectNotFound = "failure" + reconnectLossless = "lossless" +) + +const websocketMessagePluginPrefix = "custom_" + +type pluginWSPostedHook struct { + connectionID string + userID string + req *model.WebSocketRequest +} + +type WebConnConfig struct { + WebSocket *websocket.Conn + Session model.Session + TFunc i18n.TranslateFunc + Locale string + ConnectionID string + Active bool + ReuseCount int + + // These aren't necessary to be exported to api layer. + sequence int + activeQueue chan model.WebSocketMessage + deadQueue []*model.WebSocketEvent + deadQueuePointer int +} + +// WebConn represents a single websocket connection to a user. +// It contains all the necessary state to manage sending/receiving data to/from +// a websocket. +type WebConn struct { + sessionExpiresAt int64 // This should stay at the top for 64-bit alignment of 64-bit words accessed atomically + Platform *PlatformService + Suite SuiteIFace + PluginsEnvironment func() *plugin.Environment + WebSocket *websocket.Conn + T i18n.TranslateFunc + Locale string + Sequence int64 + UserId string + + allChannelMembers map[string]string + lastAllChannelMembersTime int64 + lastUserActivityAt int64 + send chan model.WebSocketMessage + // deadQueue behaves like a queue of a finite size + // which is used to store all messages that are sent via the websocket. + // It basically acts as the user-space socket buffer, and is used + // to resuscitate any messages that might have got lost when the connection is broken. + // It is implemented by using a circular buffer to keep it fast. + deadQueue []*model.WebSocketEvent + // Pointer which indicates the next slot to insert. + // It is only to be incremented during writing or clearing the queue. + deadQueuePointer int + // active indicates whether there is an open websocket connection attached + // to this webConn or not. + // It is not used as an atomic, because there is no need to. + // So do not use this outside the web hub. + active bool + // reuseCount indicates how many times this connection has been reused. + // This is used to differentiate between a fresh connection and + // a reused connection. + // It's theoretically possible for this number to wrap around. But we + // leave that as an edge-case. + reuseCount int + sessionToken atomic.Value + session atomic.Value + connectionID atomic.Value + endWritePump chan struct{} + pumpFinished chan struct{} + pluginPosted chan pluginWSPostedHook +} + +// CheckConnResult indicates whether a connectionID was present in the hub or not. +// And if so, contains the active and dead queue details. +type CheckConnResult struct { + ConnectionID string + UserID string + ActiveQueue chan model.WebSocketMessage + DeadQueue []*model.WebSocketEvent + DeadQueuePointer int + ReuseCount int +} + +// PopulateWebConnConfig checks if the connection id already exists in the hub, +// and if so, accordingly populates the other fields of the webconn. +func (ps *PlatformService) PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) { + if !model.IsValidId(cfg.ConnectionID) { + return nil, fmt.Errorf("invalid connection id: %s", cfg.ConnectionID) + } + + // This does not handle reconnect requests across nodes in a cluster. + // It falls back to the non-reliable case in that scenario. + res := ps.CheckWebConn(s.UserId, cfg.ConnectionID) + if res == nil { + // If the connection is not present, then we assume either timeout, + // or server restart. In that case, we set a new one. + cfg.ConnectionID = model.NewId() + } else { + // Connection is present, we get the active queue, dead queue + cfg.activeQueue = res.ActiveQueue + cfg.deadQueue = res.DeadQueue + cfg.deadQueuePointer = res.DeadQueuePointer + cfg.Active = false + cfg.ReuseCount = res.ReuseCount + // Now we get the sequence number + if seqVal == "" { + // Sequence_number must be sent with connection id. + // A client must be either non-compliant or fully compliant. + return nil, errors.New("sequence number not present in websocket request") + } + var err error + cfg.sequence, err = strconv.Atoi(seqVal) + if err != nil || cfg.sequence < 0 { + return nil, fmt.Errorf("invalid sequence number %s in query param: %v", seqVal, err) + } + } + return cfg, nil +} + +// NewWebConn returns a new WebConn instance. +func (ps *PlatformService) NewWebConn(cfg *WebConnConfig, suite SuiteIFace, envFn func() *plugin.Environment) *WebConn { + if cfg.Session.UserId != "" { + ps.Go(func() { + suite.SetStatusOnline(cfg.Session.UserId, false) + suite.UpdateLastActivityAtIfNeeded(cfg.Session) + }) + } + + // Disable TCP_NO_DELAY for higher throughput + var tcpConn *net.TCPConn + switch conn := cfg.WebSocket.UnderlyingConn().(type) { + case *net.TCPConn: + tcpConn = conn + case *tls.Conn: + newConn, ok := conn.NetConn().(*net.TCPConn) + if ok { + tcpConn = newConn + } + } + + if tcpConn != nil { + err := tcpConn.SetNoDelay(false) + if err != nil { + mlog.Warn("Error in setting NoDelay socket opts", mlog.Err(err)) + } + } + + if cfg.activeQueue == nil { + cfg.activeQueue = make(chan model.WebSocketMessage, sendQueueSize) + } + + if cfg.deadQueue == nil { + cfg.deadQueue = make([]*model.WebSocketEvent, deadQueueSize) + } + + wc := &WebConn{ + Platform: ps, + Suite: suite, + PluginsEnvironment: envFn, + send: cfg.activeQueue, + deadQueue: cfg.deadQueue, + deadQueuePointer: cfg.deadQueuePointer, + Sequence: int64(cfg.sequence), + WebSocket: cfg.WebSocket, + lastUserActivityAt: model.GetMillis(), + UserId: cfg.Session.UserId, + T: cfg.TFunc, + Locale: cfg.Locale, + active: cfg.Active, + reuseCount: cfg.ReuseCount, + endWritePump: make(chan struct{}), + pumpFinished: make(chan struct{}), + pluginPosted: make(chan pluginWSPostedHook, 10), + } + + wc.SetSession(&cfg.Session) + wc.SetSessionToken(cfg.Session.Token) + wc.SetSessionExpiresAt(cfg.Session.ExpiresAt) + wc.SetConnectionID(cfg.ConnectionID) + + if pluginsEnvironment := wc.PluginsEnvironment(); pluginsEnvironment != nil { + wc.Platform.Go(func() { + pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { + hooks.OnWebSocketConnect(wc.GetConnectionID(), wc.UserId) + return true + }, plugin.OnWebSocketConnectID) + }) + } + + return wc +} + +func (wc *WebConn) pluginPostedConsumer(wg *sync.WaitGroup) { + defer wg.Done() + + for msg := range wc.pluginPosted { + if pluginsEnvironment := wc.PluginsEnvironment(); pluginsEnvironment != nil { + pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { + hooks.WebSocketMessageHasBeenPosted(msg.connectionID, msg.userID, msg.req) + return true + }, plugin.WebSocketMessageHasBeenPostedID) + } + } +} + +// Close closes the WebConn. +func (wc *WebConn) Close() { + wc.WebSocket.Close() + <-wc.pumpFinished +} + +// GetSessionExpiresAt returns the time at which the session expires. +func (wc *WebConn) GetSessionExpiresAt() int64 { + return atomic.LoadInt64(&wc.sessionExpiresAt) +} + +// SetSessionExpiresAt sets the time at which the session expires. +func (wc *WebConn) SetSessionExpiresAt(v int64) { + atomic.StoreInt64(&wc.sessionExpiresAt, v) +} + +// GetSessionToken returns the session token of the connection. +func (wc *WebConn) GetSessionToken() string { + return wc.sessionToken.Load().(string) +} + +// SetSessionToken sets the session token of the connection. +func (wc *WebConn) SetSessionToken(v string) { + wc.sessionToken.Store(v) +} + +// SetConnectionID sets the connection id of the connection. +func (wc *WebConn) SetConnectionID(id string) { + wc.connectionID.Store(id) +} + +// GetConnectionID returns the connection id of the connection. +func (wc *WebConn) GetConnectionID() string { + return wc.connectionID.Load().(string) +} + +// areAllInactive returns whether all of the connections +// are inactive or not. +func areAllInactive(conns []*WebConn) bool { + for _, conn := range conns { + if conn.active { + return false + } + } + return true +} + +// GetSession returns the session of the connection. +func (wc *WebConn) GetSession() *model.Session { + return wc.session.Load().(*model.Session) +} + +// SetSession sets the session of the connection. +func (wc *WebConn) SetSession(v *model.Session) { + if v != nil { + v = v.DeepCopy() + } + + wc.session.Store(v) +} + +// Pump starts the WebConn instance. After this, the websocket +// is ready to send/receive messages. +func (wc *WebConn) Pump() { + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + wc.writePump() + }() + + wg.Add(1) + go wc.pluginPostedConsumer(&wg) + + wc.readPump() + close(wc.endWritePump) + close(wc.pluginPosted) + wg.Wait() + wc.Platform.HubUnregister(wc) + close(wc.pumpFinished) + + if pluginsEnvironment := wc.PluginsEnvironment(); pluginsEnvironment != nil { + wc.Platform.Go(func() { + pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { + hooks.OnWebSocketDisconnect(wc.GetConnectionID(), wc.UserId) + return true + }, plugin.OnWebSocketDisconnectID) + }) + } +} + +func (wc *WebConn) readPump() { + defer func() { + wc.WebSocket.Close() + }() + wc.WebSocket.SetReadLimit(model.SocketMaxMessageSizeKb) + wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)) + wc.WebSocket.SetPongHandler(func(string) error { + if err := wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)); err != nil { + return err + } + if wc.IsAuthenticated() { + wc.Platform.Go(func() { + wc.Suite.SetStatusAwayIfNeeded(wc.UserId, false) + }) + } + return nil + }) + + for { + msgType, rd, err := wc.WebSocket.NextReader() + if err != nil { + wc.logSocketErr("websocket.NextReader", err) + return + } + + var decoder interface { + Decode(v any) error + } + if msgType == websocket.TextMessage { + decoder = json.NewDecoder(rd) + } else { + decoder = msgpack.NewDecoder(rd) + } + var req model.WebSocketRequest + if err = decoder.Decode(&req); err != nil { + wc.logSocketErr("websocket.Decode", err) + return + } + + // Messages which actions are prefixed with the plugin prefix + // should only be dispatched to the plugins + if !strings.HasPrefix(req.Action, websocketMessagePluginPrefix) { + wc.Platform.WebSocketRouter.ServeWebSocket(wc, &req) + } + + clonedReq, err := req.Clone() + if err != nil { + wc.logSocketErr("websocket.cloneRequest", err) + continue + } + + wc.pluginPosted <- pluginWSPostedHook{wc.GetConnectionID(), wc.UserId, clonedReq} + } +} + +func (wc *WebConn) writePump() { + ticker := time.NewTicker(pingInterval) + authTicker := time.NewTicker(authCheckInterval) + + defer func() { + ticker.Stop() + authTicker.Stop() + wc.WebSocket.Close() + }() + + if wc.Sequence != 0 { + if ok, index := wc.isInDeadQueue(wc.Sequence); ok { + if err := wc.drainDeadQueue(index); err != nil { + wc.logSocketErr("websocket.drainDeadQueue", err) + return + } + if m := wc.Platform.metricsImpl(); m != nil { + m.IncrementWebsocketReconnectEvent(reconnectFound) + } + } else if wc.hasMsgLoss() { + // If the seq number is not in dead queue, but it was supposed to be, + // then generate a different connection ID, + // and set sequence to 0, and clear dead queue. + wc.clearDeadQueue() + wc.SetConnectionID(model.NewId()) + wc.Sequence = 0 + + // Send hello message + msg := wc.createHelloMessage() + wc.addToDeadQueue(msg) + if err := wc.writeMessage(msg); err != nil { + wc.logSocketErr("websocket.sendHello", err) + return + } + if m := wc.Platform.metricsImpl(); m != nil { + m.IncrementWebsocketReconnectEvent(reconnectNotFound) + } + } else { + if m := wc.Platform.metricsImpl(); m != nil { + m.IncrementWebsocketReconnectEvent(reconnectLossless) + } + } + } + + var buf bytes.Buffer + // 2k is seen to be a good heuristic under which 98.5% of message sizes remain. + buf.Grow(1024 * 2) + enc := json.NewEncoder(&buf) + + for { + select { + case msg, ok := <-wc.send: + if !ok { + wc.writeMessageBuf(websocket.CloseMessage, []byte{}) + return + } + + evt, evtOk := msg.(*model.WebSocketEvent) + + buf.Reset() + var err error + if evtOk { + evt = evt.SetSequence(wc.Sequence) + err = evt.Encode(enc) + wc.Sequence++ + } else { + err = enc.Encode(msg) + } + if err != nil { + mlog.Warn("Error in encoding websocket message", mlog.Err(err)) + continue + } + + if len(wc.send) >= sendFullWarn { + logData := []mlog.Field{ + mlog.String("user_id", wc.UserId), + mlog.String("type", msg.EventType()), + mlog.Int("size", buf.Len()), + } + if evtOk { + logData = append(logData, mlog.String("channel_id", evt.GetBroadcast().ChannelId)) + } + + mlog.Warn("websocket.full", logData...) + } + + if evtOk { + wc.addToDeadQueue(evt) + } + + if err := wc.writeMessageBuf(websocket.TextMessage, buf.Bytes()); err != nil { + wc.logSocketErr("websocket.send", err) + return + } + + if m := wc.Platform.metricsImpl(); m != nil { + m.IncrementWebSocketBroadcast(msg.EventType()) + } + case <-ticker.C: + if err := wc.writeMessageBuf(websocket.PingMessage, []byte{}); err != nil { + wc.logSocketErr("websocket.ticker", err) + return + } + + case <-wc.endWritePump: + return + + case <-authTicker.C: + if wc.GetSessionToken() == "" { + mlog.Debug("websocket.authTicker: did not authenticate", mlog.Any("ip_address", wc.WebSocket.RemoteAddr())) + return + } + authTicker.Stop() + } + } +} + +// writeMessageBuf is a helper utility that wraps the write to the socket +// along with setting the write deadline. +func (wc *WebConn) writeMessageBuf(msgType int, data []byte) error { + wc.WebSocket.SetWriteDeadline(time.Now().Add(writeWaitTime)) + return wc.WebSocket.WriteMessage(msgType, data) +} + +func (wc *WebConn) writeMessage(msg *model.WebSocketEvent) error { + // We don't use the encoder from the write pump because it's unwieldy to pass encoders + // around, and this is only called during initialization of the webConn. + var buf bytes.Buffer + err := msg.Encode(json.NewEncoder(&buf)) + if err != nil { + mlog.Warn("Error in encoding websocket message", mlog.Err(err)) + return nil + } + wc.Sequence++ + + return wc.writeMessageBuf(websocket.TextMessage, buf.Bytes()) +} + +// addToDeadQueue appends a message to the dead queue. +func (wc *WebConn) addToDeadQueue(msg *model.WebSocketEvent) { + wc.deadQueue[wc.deadQueuePointer] = msg + wc.deadQueuePointer = (wc.deadQueuePointer + 1) % deadQueueSize +} + +// hasMsgLoss indicates whether the next wanted sequence is right after +// the latest element in the dead queue, which would mean there is no message loss. +func (wc *WebConn) hasMsgLoss() bool { + var index int + // deadQueuePointer = 0 means either no msg written or the pointer + // has rolled over to its starting position. + if wc.deadQueuePointer == 0 { + // If last entry is nil, it means no msg is written. + if wc.deadQueue[deadQueueSize-1] == nil { + return false + } + // If it's not nil, that means it has rolled over to start, and we + // check the last position. + index = deadQueueSize - 1 + } else { // deadQueuePointer != 0 means it's somewhere in the middle. + index = wc.deadQueuePointer - 1 + } + + if wc.deadQueue[index].GetSequence() == wc.Sequence-1 { + return false + } + return true +} + +// isInDeadQueue checks whether a given sequence number is in the dead queue or not. +// And if it is, it returns that index. +func (wc *WebConn) isInDeadQueue(seq int64) (bool, int) { + // Can be optimized to traverse backwards from deadQueuePointer + // Hopefully, traversing 128 elements is not too much overhead. + for i := 0; i < deadQueueSize; i++ { + elem := wc.deadQueue[i] + if elem == nil { + return false, 0 + } + + if elem.GetSequence() == seq { + return true, i + } + } + return false, 0 +} + +func (wc *WebConn) clearDeadQueue() { + for i := 0; i < deadQueueSize; i++ { + if wc.deadQueue[i] == nil { + break + } + wc.deadQueue[i] = nil + } + wc.deadQueuePointer = 0 +} + +// drainDeadQueue will write all messages from a given index to the socket. +// It is called with the assumption that the item with wc.Sequence is present +// in it, because otherwise it would have been cleared from WebConn. +func (wc *WebConn) drainDeadQueue(index int) error { + if wc.deadQueue[0] == nil { + // Empty queue + return nil + } + + // This means pointer hasn't rolled over. + if wc.deadQueue[wc.deadQueuePointer] == nil { + // Clear till the end of queue. + for i := index; i < wc.deadQueuePointer; i++ { + if err := wc.writeMessage(wc.deadQueue[i]); err != nil { + return err + } + } + return nil + } + + // We go on until next sequence number is smaller than previous one. + // Which means it has rolled over. + currPtr := index + for { + if err := wc.writeMessage(wc.deadQueue[currPtr]); err != nil { + return err + } + oldSeq := wc.deadQueue[currPtr].GetSequence() // TODO: possibly move this + currPtr = (currPtr + 1) % deadQueueSize // to for loop condition + newSeq := wc.deadQueue[currPtr].GetSequence() + if oldSeq > newSeq { + break + } + } + return nil +} + +// InvalidateCache resets all internal data of the WebConn. +func (wc *WebConn) InvalidateCache() { + wc.allChannelMembers = nil + wc.lastAllChannelMembersTime = 0 + wc.SetSession(nil) + wc.SetSessionExpiresAt(0) +} + +// IsAuthenticated returns whether the given WebConn is authenticated or not. +func (wc *WebConn) IsAuthenticated() bool { + // Check the expiry to see if we need to check for a new session + if wc.GetSessionExpiresAt() < model.GetMillis() { + if wc.GetSessionToken() == "" { + return false + } + + session, err := wc.Suite.GetSession(wc.GetSessionToken()) + if err != nil { + if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { + mlog.Debug("Invalid session.", mlog.Err(err)) + } else { + mlog.Error("Could not get session", mlog.String("session_token", wc.GetSessionToken()), mlog.Err(err)) + } + + wc.SetSessionToken("") + wc.SetSession(nil) + wc.SetSessionExpiresAt(0) + return false + } + + wc.SetSession(session) + wc.SetSessionExpiresAt(session.ExpiresAt) + } + + return true +} + +func (wc *WebConn) createHelloMessage() *model.WebSocketEvent { + ee := wc.Platform.LicenseManager() != nil + + msg := model.NewWebSocketEvent(model.WebsocketEventHello, "", "", wc.UserId, nil, "") + msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, + model.BuildNumber, + wc.Platform.ClientConfigHash(), + ee)) + msg.Add("connection_id", wc.connectionID.Load()) + return msg +} + +func (wc *WebConn) ShouldSendEventToGuest(msg *model.WebSocketEvent) bool { + var userID string + var canSee bool + + switch msg.EventType() { + case model.WebsocketEventUserUpdated: + user, ok := msg.GetData()["user"].(*model.User) + if !ok { + mlog.Debug("webhub.shouldSendEvent: user not found in message", mlog.Any("user", msg.GetData()["user"])) + return false + } + userID = user.Id + case model.WebsocketEventNewUser: + userID = msg.GetData()["user_id"].(string) + default: + return true + } + + canSee, err := wc.Suite.UserCanSeeOtherUser(wc.UserId, userID) + if err != nil { + mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) + return false + } + + return canSee +} + +// ShouldSendEvent returns whether the message should be sent or not. +func (wc *WebConn) ShouldSendEvent(msg *model.WebSocketEvent) bool { + // IMPORTANT: Do not send event if WebConn does not have a session + if !wc.IsAuthenticated() { + return false + } + + // When the pump starts to get slow we'll drop non-critical + // messages. We should skip those frames before they are + // queued to wc.send buffered channel. + if len(wc.send) >= sendSlowWarn { + switch msg.EventType() { + case model.WebsocketEventTyping, + model.WebsocketEventStatusChange, + model.WebsocketEventChannelViewed: + mlog.Warn( + "websocket.slow: dropping message", + mlog.String("user_id", wc.UserId), + mlog.String("type", msg.EventType()), + ) + return false + } + } + + // If the event contains sanitized data, only send to users that don't have permission to + // see sensitive data. Prevents admin clients from receiving events with bad data + var hasReadPrivateDataPermission *bool + if msg.GetBroadcast().ContainsSanitizedData { + hasReadPrivateDataPermission = model.NewBool(wc.Suite.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) + + if *hasReadPrivateDataPermission { + return false + } + } + + // If the event contains sensitive data, only send to users with permission to see it + if msg.GetBroadcast().ContainsSensitiveData { + if hasReadPrivateDataPermission == nil { + hasReadPrivateDataPermission = model.NewBool(wc.Suite.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) + } + + if !*hasReadPrivateDataPermission { + return false + } + } + + // If the event is destined to a specific connection + if msg.GetBroadcast().ConnectionId != "" { + return wc.GetConnectionID() == msg.GetBroadcast().ConnectionId + } + + // If the event is destined to a specific user + if msg.GetBroadcast().UserId != "" { + return wc.UserId == msg.GetBroadcast().UserId + } + + if wc.GetConnectionID() == msg.GetBroadcast().OmitConnectionId { + return false + } + + // if the user is omitted don't send the message + if len(msg.GetBroadcast().OmitUsers) > 0 { + if _, ok := msg.GetBroadcast().OmitUsers[wc.UserId]; ok { + return false + } + } + + // Only report events to users who are in the channel for the event + if msg.GetBroadcast().ChannelId != "" { + if model.GetMillis()-wc.lastAllChannelMembersTime > webConnMemberCacheTime { + wc.allChannelMembers = nil + wc.lastAllChannelMembersTime = 0 + } + + if wc.allChannelMembers == nil { + result, err := wc.Platform.Store.Channel().GetAllChannelMembersForUser(wc.UserId, false, false) + if err != nil { + mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) + return false + } + wc.allChannelMembers = result + wc.lastAllChannelMembersTime = model.GetMillis() + } + + if _, ok := wc.allChannelMembers[msg.GetBroadcast().ChannelId]; ok { + return true + } + return false + } + + // Only report events to users who are in the team for the event + if msg.GetBroadcast().TeamId != "" { + return wc.isMemberOfTeam(msg.GetBroadcast().TeamId) + } + + if wc.GetSession().Props[model.SessionPropIsGuest] == "true" { + return wc.ShouldSendEventToGuest(msg) + } + + return true +} + +// IsMemberOfTeam returns whether the user of the WebConn +// is a member of the given teamID or not. +func (wc *WebConn) isMemberOfTeam(teamID string) bool { + currentSession := wc.GetSession() + + if currentSession == nil || currentSession.Token == "" { + session, err := wc.Suite.GetSession(wc.GetSessionToken()) + if err != nil { + if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { + mlog.Debug("Invalid session.", mlog.Err(err)) + } else { + mlog.Error("Could not get session", mlog.String("session_token", wc.GetSessionToken()), mlog.Err(err)) + } + return false + } + wc.SetSession(session) + currentSession = session + } + + return currentSession.GetTeamByTeamId(teamID) != nil +} + +func (wc *WebConn) logSocketErr(source string, err error) { + // browsers will appear as CloseNoStatusReceived + if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) { + mlog.Debug(source+": client side closed socket", mlog.String("user_id", wc.UserId)) + } else { + mlog.Debug(source+": closing websocket", mlog.String("user_id", wc.UserId), mlog.Err(err)) + } +} diff --git a/app/platform/web_conn_test.go b/app/platform/web_conn_test.go new file mode 100644 index 0000000000..b12232bd61 --- /dev/null +++ b/app/platform/web_conn_test.go @@ -0,0 +1,228 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "bytes" + "net" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/plugin" +) + +func TestWebConnAddDeadQueue(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + wc := th.Service.NewWebConn(&WebConnConfig{ + WebSocket: &websocket.Conn{}, + }, th.Suite, func() *plugin.Environment { return nil }) + + for i := 0; i < 2; i++ { + msg := &model.WebSocketEvent{} + msg = msg.SetSequence(int64(i)) + wc.addToDeadQueue(msg) + } + + for i := 0; i < 2; i++ { + assert.Equal(t, int64(i), wc.deadQueue[i].GetSequence()) + } + + // Should push out the first two elements + for i := 0; i < deadQueueSize; i++ { + msg := &model.WebSocketEvent{} + msg = msg.SetSequence(int64(i + 2)) + wc.addToDeadQueue(msg) + } + for i := 0; i < deadQueueSize; i++ { + assert.Equal(t, int64(i+2), wc.deadQueue[(i+2)%deadQueueSize].GetSequence()) + } +} + +func TestWebConnIsInDeadQueue(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + wc := th.Service.NewWebConn(&WebConnConfig{ + WebSocket: &websocket.Conn{}, + }, th.Suite, func() *plugin.Environment { return nil }) + + var i int + for ; i < 2; i++ { + msg := &model.WebSocketEvent{} + msg = msg.SetSequence(int64(i)) + wc.addToDeadQueue(msg) + } + + wc.Sequence = int64(0) + ok, ind := wc.isInDeadQueue(wc.Sequence) + assert.True(t, ok) + assert.Equal(t, 0, ind) + assert.True(t, wc.hasMsgLoss()) + wc.Sequence = int64(1) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.True(t, ok) + assert.Equal(t, 1, ind) + assert.True(t, wc.hasMsgLoss()) + wc.Sequence = int64(2) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.False(t, ok) + assert.Equal(t, 0, ind) + assert.False(t, wc.hasMsgLoss()) + + for ; i < deadQueueSize+2; i++ { + msg := &model.WebSocketEvent{} + msg = msg.SetSequence(int64(i)) + wc.addToDeadQueue(msg) + } + + wc.Sequence = int64(129) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.True(t, ok) + assert.Equal(t, 1, ind) + wc.Sequence = int64(128) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.True(t, ok) + assert.Equal(t, 0, ind) + wc.Sequence = int64(2) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.True(t, ok) + assert.Equal(t, 2, ind) + assert.True(t, wc.hasMsgLoss()) + wc.Sequence = int64(0) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.False(t, ok) + assert.Equal(t, 0, ind) + wc.Sequence = int64(130) + ok, ind = wc.isInDeadQueue(wc.Sequence) + assert.False(t, ok) + assert.Equal(t, 0, ind) + assert.False(t, wc.hasMsgLoss()) +} + +func TestWebConnClearDeadQueue(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + wc := th.Service.NewWebConn(&WebConnConfig{ + WebSocket: &websocket.Conn{}, + }, th.Suite, func() *plugin.Environment { return nil }) + + var i int + for ; i < 2; i++ { + msg := &model.WebSocketEvent{} + msg = msg.SetSequence(int64(i)) + wc.addToDeadQueue(msg) + } + + wc.clearDeadQueue() + + assert.Equal(t, 0, wc.deadQueuePointer) +} + +func TestWebConnDrainDeadQueue(t *testing.T) { + th := Setup(t) + defer th.TearDown() + + var dialConn = func(t *testing.T, th *TestHelper, addr net.Addr) *WebConn { + d := websocket.Dialer{} + c, _, err := d.Dial("ws://"+addr.String()+"/ws", nil) + require.NoError(t, err) + + cfg := &WebConnConfig{ + WebSocket: c, + } + return th.Service.NewWebConn(cfg, th.Suite, func() *plugin.Environment { return nil }) + } + + t.Run("Empty Queue", func(t *testing.T) { + var handler = func(t *testing.T) http.HandlerFunc { + return func(w http.ResponseWriter, req *http.Request) { + upgrader := &websocket.Upgrader{} + conn, err := upgrader.Upgrade(w, req, nil) + cnt := 0 + for err == nil { + _, _, err = conn.ReadMessage() + cnt++ + } + assert.Equal(t, 1, cnt) + if _, ok := err.(*websocket.CloseError); !ok { + require.NoError(t, err) + } + } + } + s := httptest.NewServer(handler(t)) + defer s.Close() + + wc := dialConn(t, th, s.Listener.Addr()) + defer wc.WebSocket.Close() + wc.clearDeadQueue() + + err := wc.drainDeadQueue(0) + require.NoError(t, err) + }) + + var handler = func(t *testing.T, seqNum int64, limit int) http.HandlerFunc { + return func(w http.ResponseWriter, req *http.Request) { + upgrader := &websocket.Upgrader{} + conn, err := upgrader.Upgrade(w, req, nil) + var buf []byte + i := seqNum + for err == nil { + _, buf, err = conn.ReadMessage() + if err != nil && len(buf) > 0 { + ev, jsonErr := model.WebSocketEventFromJSON(bytes.NewReader(buf)) + require.NoError(t, jsonErr) + require.LessOrEqual(t, int(i), limit) + assert.Equal(t, i, ev.GetSequence()) + i++ + } + } + if _, ok := err.(*websocket.CloseError); !ok { + require.NoError(t, err) + } + } + } + + run := func(seqNum int64, limit int) { + s := httptest.NewServer(handler(t, seqNum, limit)) + defer s.Close() + + wc := dialConn(t, th, s.Listener.Addr()) + defer wc.WebSocket.Close() + + for i := 0; i < limit; i++ { + msg := model.NewWebSocketEvent("", "", "", "", map[string]bool{}, "") + msg = msg.SetSequence(int64(i)) + wc.addToDeadQueue(msg) + } + wc.Sequence = seqNum + ok, index := wc.isInDeadQueue(wc.Sequence) + require.True(t, ok) + + err := wc.drainDeadQueue(index) + require.NoError(t, err) + } + + t.Run("Half-full Queue", func(t *testing.T) { + t.Run("Middle", func(t *testing.T) { run(int64(2), 10) }) + t.Run("Beginning", func(t *testing.T) { run(int64(0), 10) }) + t.Run("End", func(t *testing.T) { run(int64(9), 10) }) + t.Run("Full", func(t *testing.T) { run(int64(deadQueueSize-1), deadQueueSize) }) + }) + + t.Run("Cycled Queue", func(t *testing.T) { + t.Run("First un-overwritten", func(t *testing.T) { run(int64(10), deadQueueSize+10) }) + t.Run("End", func(t *testing.T) { run(int64(127), deadQueueSize+10) }) + t.Run("Cycled End", func(t *testing.T) { run(int64(137), deadQueueSize+10) }) + t.Run("Overwritten First", func(t *testing.T) { run(int64(128), deadQueueSize+10) }) + }) +} diff --git a/app/platform/web_hub.go b/app/platform/web_hub.go new file mode 100644 index 0000000000..6352be02f8 --- /dev/null +++ b/app/platform/web_hub.go @@ -0,0 +1,666 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "hash/maphash" + "runtime" + "runtime/debug" + "strconv" + "sync/atomic" + "time" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +const ( + broadcastQueueSize = 4096 + inactiveConnReaperInterval = 5 * time.Minute +) + +type SuiteIFace interface { + SetStatusLastActivityAt(userID string, activityAt int64) + SetStatusOffline(userID string, manual bool) + IsUserAway(lastActivityAt int64) bool + SetStatusOnline(userID string, manual bool) + UpdateLastActivityAtIfNeeded(session model.Session) + SetStatusAwayIfNeeded(userID string, manual bool) + GetSession(token string) (*model.Session, *model.AppError) + RolesGrantPermission(roleNames []string, permissionId string) bool + UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError) +} + +type webConnActivityMessage struct { + userID string + sessionToken string + activityAt int64 +} + +type webConnDirectMessage struct { + conn *WebConn + msg model.WebSocketMessage +} + +type webConnSessionMessage struct { + userID string + sessionToken string + isRegistered chan bool +} + +type webConnCheckMessage struct { + userID string + connectionID string + result chan *CheckConnResult +} + +// Hub is the central place to manage all websocket connections in the server. +// It handles different websocket events and sending messages to individual +// user connections. +type Hub struct { + // connectionCount should be kept first. + // See https://github.com/mattermost/mattermost-server/pull/7281 + connectionCount int64 + platform *PlatformService + connectionIndex int + register chan *WebConn + unregister chan *WebConn + broadcast chan *model.WebSocketEvent + stop chan struct{} + didStop chan struct{} + invalidateUser chan string + activity chan *webConnActivityMessage + directMsg chan *webConnDirectMessage + explicitStop bool + checkRegistered chan *webConnSessionMessage + checkConn chan *webConnCheckMessage +} + +// newWebHub creates a new Hub. +func newWebHub(ps *PlatformService) *Hub { + return &Hub{ + platform: ps, + register: make(chan *WebConn), + unregister: make(chan *WebConn), + broadcast: make(chan *model.WebSocketEvent, broadcastQueueSize), + stop: make(chan struct{}), + didStop: make(chan struct{}), + invalidateUser: make(chan string), + activity: make(chan *webConnActivityMessage), + directMsg: make(chan *webConnDirectMessage), + checkRegistered: make(chan *webConnSessionMessage), + checkConn: make(chan *webConnCheckMessage), + } +} + +// HubStart starts all the hubs. +func (ps *PlatformService) HubStart(suite SuiteIFace) { + // Total number of hubs is twice the number of CPUs. + numberOfHubs := runtime.NumCPU() * 2 + ps.logger.Info("Starting websocket hubs", mlog.Int("number_of_hubs", numberOfHubs)) + + hubs := make([]*Hub, numberOfHubs) + + for i := 0; i < numberOfHubs; i++ { + hubs[i] = newWebHub(ps) + hubs[i].connectionIndex = i + hubs[i].Start(suite) + } + // Assigning to the hubs slice without any mutex is fine because it is only assigned once + // during the start of the program and always read from after that. + ps.hubs = hubs +} + +func (ps *PlatformService) InvalidateCacheForWebhook(webhookID string) { + ps.Store.Webhook().InvalidateWebhookCache(webhookID) +} + +// HubStop stops all the hubs. +func (ps *PlatformService) HubStop() { + ps.logger.Info("stopping websocket hub connections") + + for _, hub := range ps.hubs { + hub.Stop() + } +} + +// GetHubForUserId returns the hub for a given user id. +func (ps *PlatformService) GetHubForUserId(userID string) *Hub { + // TODO: check if caching the userID -> hub mapping + // is worth the memory tradeoff. + // https://mattermost.atlassian.net/browse/MM-26629. + var hash maphash.Hash + hash.SetSeed(ps.hashSeed) + hash.Write([]byte(userID)) + index := hash.Sum64() % uint64(len(ps.hubs)) + + return ps.hubs[int(index)] +} + +// HubRegister registers a connection to a hub. +func (ps *PlatformService) HubRegister(webConn *WebConn) { + hub := ps.GetHubForUserId(webConn.UserId) + if hub != nil { + if metrics := ps.metricsImpl(); metrics != nil { + metrics.IncrementWebSocketBroadcastUsersRegistered(strconv.Itoa(hub.connectionIndex), 1) + } + hub.Register(webConn) + } +} + +// HubUnregister unregisters a connection from a hub. +func (ps *PlatformService) HubUnregister(webConn *WebConn) { + hub := ps.GetHubForUserId(webConn.UserId) + if hub != nil { + if metrics := ps.metricsImpl(); metrics != nil { + metrics.DecrementWebSocketBroadcastUsersRegistered(strconv.Itoa(hub.connectionIndex), 1) + } + hub.Unregister(webConn) + } +} + +func (ps *PlatformService) InvalidateCacheForChannel(channel *model.Channel) { + ps.Store.Channel().InvalidateChannel(channel.Id) + ps.invalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) + + if ps.clusterIFace != nil { + nameMsg := &model.ClusterMessage{ + Event: model.ClusterEventInvalidateCacheForChannelByName, + SendType: model.ClusterSendBestEffort, + Props: make(map[string]string), + } + + nameMsg.Props["name"] = channel.Name + if channel.TeamId == "" { + nameMsg.Props["id"] = "dm" + } else { + nameMsg.Props["id"] = channel.TeamId + } + + ps.clusterIFace.SendClusterMessage(nameMsg) + } +} + +func (ps *PlatformService) InvalidateCacheForChannelMembers(channelID string) { + ps.Store.User().InvalidateProfilesInChannelCache(channelID) + ps.Store.Channel().InvalidateMemberCount(channelID) + ps.Store.Channel().InvalidateGuestCount(channelID) +} + +func (ps *PlatformService) InvalidateCacheForChannelMembersNotifyProps(channelID string) { + ps.invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelID) + + if ps.clusterIFace != nil { + msg := &model.ClusterMessage{ + Event: model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, + SendType: model.ClusterSendBestEffort, + Data: []byte(channelID), + } + ps.clusterIFace.SendClusterMessage(msg) + } +} + +func (ps *PlatformService) InvalidateCacheForChannelPosts(channelID string) { + ps.Store.Channel().InvalidatePinnedPostCount(channelID) + ps.Store.Post().InvalidateLastPostTimeCache(channelID) +} + +func (ps *PlatformService) InvalidateCacheForUser(userID string) { + ps.InvalidateCacheForUserSkipClusterSend(userID) + + ps.Store.User().InvalidateProfilesInChannelCacheByUser(userID) + ps.Store.User().InvalidateProfileCacheForUser(userID) + + if ps.clusterIFace != nil { + msg := &model.ClusterMessage{ + Event: model.ClusterEventInvalidateCacheForUser, + SendType: model.ClusterSendBestEffort, + Data: []byte(userID), + } + ps.clusterIFace.SendClusterMessage(msg) + } +} + +func (ps *PlatformService) InvalidateCacheForUserTeams(userID string) { + ps.invalidateWebConnSessionCacheForUser(userID) + ps.Store.Team().InvalidateAllTeamIdsForUser(userID) + + if ps.clusterIFace != nil { + msg := &model.ClusterMessage{ + Event: model.ClusterEventInvalidateCacheForUserTeams, + SendType: model.ClusterSendBestEffort, + Data: []byte(userID), + } + ps.clusterIFace.SendClusterMessage(msg) + } +} + +// UpdateWebConnUserActivity sets the LastUserActivityAt of the hub for the given session. +func (ps *PlatformService) UpdateWebConnUserActivity(session model.Session, activityAt int64) { + hub := ps.GetHubForUserId(session.UserId) + if hub != nil { + hub.UpdateActivity(session.UserId, session.Token, activityAt) + } +} + +// SessionIsRegistered determines if a specific session has been registered +func (ps *PlatformService) SessionIsRegistered(session model.Session) bool { + hub := ps.GetHubForUserId(session.UserId) + if hub != nil { + return hub.IsRegistered(session.UserId, session.Token) + } + + return false +} + +func (ps *PlatformService) CheckWebConn(userID, connectionID string) *CheckConnResult { + hub := ps.GetHubForUserId(userID) + if hub != nil { + return hub.CheckConn(userID, connectionID) + } + return nil +} + +// Register registers a connection to the hub. +func (h *Hub) Register(webConn *WebConn) { + select { + case h.register <- webConn: + case <-h.stop: + } +} + +// Unregister unregisters a connection from the hub. +func (h *Hub) Unregister(webConn *WebConn) { + select { + case h.unregister <- webConn: + case <-h.stop: + } +} + +// Determines if a user's session is registered a connection from the hub. +func (h *Hub) IsRegistered(userID, sessionToken string) bool { + ws := &webConnSessionMessage{ + userID: userID, + sessionToken: sessionToken, + isRegistered: make(chan bool), + } + select { + case h.checkRegistered <- ws: + return <-ws.isRegistered + case <-h.stop: + } + return false +} + +func (h *Hub) CheckConn(userID, connectionID string) *CheckConnResult { + req := &webConnCheckMessage{ + userID: userID, + connectionID: connectionID, + result: make(chan *CheckConnResult), + } + select { + case h.checkConn <- req: + return <-req.result + case <-h.stop: + } + return nil +} + +// Broadcast broadcasts the message to all connections in the hub. +func (h *Hub) Broadcast(message *model.WebSocketEvent) { + // XXX: The hub nil check is because of the way we setup our tests. We call + // `app.NewServer()` which returns a server, but only after that, we call + // `wsapi.Init()` to initialize the hub. But in the `NewServer` call + // itself proceeds to broadcast some messages happily. This needs to be + // fixed once the wsapi cyclic dependency with server/app goes away. + // And possibly, we can look into doing the hub initialization inside + // NewServer itself. + if h != nil && message != nil { + if metrics := h.platform.metricsImpl(); metrics != nil { + metrics.IncrementWebSocketBroadcastBufferSize(strconv.Itoa(h.connectionIndex), 1) + } + select { + case h.broadcast <- message: + case <-h.stop: + } + } +} + +// InvalidateUser invalidates the cache for the given user. +func (h *Hub) InvalidateUser(userID string) { + select { + case h.invalidateUser <- userID: + case <-h.stop: + } +} + +// UpdateActivity sets the LastUserActivityAt field for the connection +// of the user. +func (h *Hub) UpdateActivity(userID, sessionToken string, activityAt int64) { + select { + case h.activity <- &webConnActivityMessage{ + userID: userID, + sessionToken: sessionToken, + activityAt: activityAt, + }: + case <-h.stop: + } +} + +// SendMessage sends the given message to the given connection. +func (h *Hub) SendMessage(conn *WebConn, msg model.WebSocketMessage) { + select { + case h.directMsg <- &webConnDirectMessage{ + conn: conn, + msg: msg, + }: + case <-h.stop: + } +} + +// Stop stops the hub. +func (h *Hub) Stop() { + close(h.stop) + <-h.didStop +} + +// Start starts the hub. +func (h *Hub) Start(suite SuiteIFace) { + var doStart func() + var doRecoverableStart func() + var doRecover func() + + doStart = func() { + mlog.Debug("Hub is starting", mlog.Int("index", h.connectionIndex)) + + ticker := time.NewTicker(inactiveConnReaperInterval) + defer ticker.Stop() + + connIndex := newHubConnectionIndex(inactiveConnReaperInterval) + + for { + select { + case webSessionMessage := <-h.checkRegistered: + conns := connIndex.ForUser(webSessionMessage.userID) + var isRegistered bool + for _, conn := range conns { + if !conn.active { + continue + } + if conn.GetSessionToken() == webSessionMessage.sessionToken { + isRegistered = true + } + } + webSessionMessage.isRegistered <- isRegistered + case req := <-h.checkConn: + var res *CheckConnResult + conn := connIndex.RemoveInactiveByConnectionID(req.userID, req.connectionID) + if conn != nil { + res = &CheckConnResult{ + ConnectionID: req.connectionID, + UserID: req.userID, + ActiveQueue: conn.send, + DeadQueue: conn.deadQueue, + DeadQueuePointer: conn.deadQueuePointer, + ReuseCount: conn.reuseCount + 1, + } + } + req.result <- res + case <-ticker.C: + connIndex.RemoveInactiveConnections() + case webConn := <-h.register: + // Mark the current one as active. + // There is no need to check if it was inactive or not, + // we will anyways need to make it active. + webConn.active = true + + connIndex.Add(webConn) + atomic.StoreInt64(&h.connectionCount, int64(connIndex.AllActive())) + + if webConn.IsAuthenticated() && webConn.reuseCount == 0 { + // The hello message should only be sent when the reuseCount is 0. + // i.e in server restart, or long timeout, or fresh connection case. + // In case of seq number not found in dead queue, it is handled by + // the webconn write pump. + webConn.send <- webConn.createHelloMessage() + } + case webConn := <-h.unregister: + // If already removed (via queue full), then removing again becomes a noop. + // But if not removed, mark inactive. + webConn.active = false + + atomic.StoreInt64(&h.connectionCount, int64(connIndex.AllActive())) + + if webConn.UserId == "" { + continue + } + + conns := connIndex.ForUser(webConn.UserId) + if len(conns) == 0 || areAllInactive(conns) { + h.platform.Go(func() { + suite.SetStatusOffline(webConn.UserId, false) + }) + continue + } + var latestActivity int64 = 0 + for _, conn := range conns { + if !conn.active { + continue + } + if conn.lastUserActivityAt > latestActivity { + latestActivity = conn.lastUserActivityAt + } + } + + if suite.IsUserAway(latestActivity) { + h.platform.Go(func() { + suite.SetStatusLastActivityAt(webConn.UserId, latestActivity) + }) + } + case userID := <-h.invalidateUser: + for _, webConn := range connIndex.ForUser(userID) { + webConn.InvalidateCache() + } + case activity := <-h.activity: + for _, webConn := range connIndex.ForUser(activity.userID) { + if !webConn.active { + continue + } + if webConn.GetSessionToken() == activity.sessionToken { + webConn.lastUserActivityAt = activity.activityAt + } + } + case directMsg := <-h.directMsg: + if !connIndex.Has(directMsg.conn) { + continue + } + select { + case directMsg.conn.send <- directMsg.msg: + default: + mlog.Error("webhub.broadcast: cannot send, closing websocket for user", mlog.String("user_id", directMsg.conn.UserId)) + close(directMsg.conn.send) + connIndex.Remove(directMsg.conn) + } + case msg := <-h.broadcast: + if metrics := h.platform.metricsImpl(); metrics != nil { + metrics.DecrementWebSocketBroadcastBufferSize(strconv.Itoa(h.connectionIndex), 1) + } + msg = msg.PrecomputeJSON() + broadcast := func(webConn *WebConn) { + if !connIndex.Has(webConn) { + return + } + if webConn.ShouldSendEvent(msg) { + select { + case webConn.send <- msg: + default: + mlog.Error("webhub.broadcast: cannot send, closing websocket for user", mlog.String("user_id", webConn.UserId)) + close(webConn.send) + connIndex.Remove(webConn) + } + } + } + + if connID := msg.GetBroadcast().ConnectionId; connID != "" { + if webConn := connIndex.byConnectionId[connID]; webConn != nil { + broadcast(webConn) + continue + } + } else if msg.GetBroadcast().UserId != "" { + candidates := connIndex.ForUser(msg.GetBroadcast().UserId) + for _, webConn := range candidates { + broadcast(webConn) + } + continue + } + + candidates := connIndex.All() + for webConn := range candidates { + broadcast(webConn) + } + case <-h.stop: + for webConn := range connIndex.All() { + webConn.Close() + suite.SetStatusOffline(webConn.UserId, false) + } + + h.explicitStop = true + close(h.didStop) + + return + } + } + } + + doRecoverableStart = func() { + defer doRecover() + doStart() + } + + doRecover = func() { + if !h.explicitStop { + if r := recover(); r != nil { + mlog.Error("Recovering from Hub panic.", mlog.Any("panic", r)) + } else { + mlog.Error("Webhub stopped unexpectedly. Recovering.") + } + + mlog.Error(string(debug.Stack())) + + go doRecoverableStart() + } + } + + go doRecoverableStart() +} + +// hubConnectionIndex provides fast addition, removal, and iteration of web connections. +// It requires 3 functionalities which need to be very fast: +// - check if a connection exists or not. +// - get all connections for a given userID. +// - get all connections. +type hubConnectionIndex struct { + // byUserId stores the list of connections for a given userID + byUserId map[string][]*WebConn + // byConnection serves the dual purpose of storing the index of the webconn + // in the value of byUserId map, and also to get all connections. + byConnection map[*WebConn]int + byConnectionId map[string]*WebConn + // staleThreshold is the limit beyond which inactive connections + // will be deleted. + staleThreshold time.Duration +} + +func newHubConnectionIndex(interval time.Duration) *hubConnectionIndex { + return &hubConnectionIndex{ + byUserId: make(map[string][]*WebConn), + byConnection: make(map[*WebConn]int), + byConnectionId: make(map[string]*WebConn), + staleThreshold: interval, + } +} + +func (i *hubConnectionIndex) Add(wc *WebConn) { + i.byUserId[wc.UserId] = append(i.byUserId[wc.UserId], wc) + i.byConnection[wc] = len(i.byUserId[wc.UserId]) - 1 + i.byConnectionId[wc.GetConnectionID()] = wc +} + +func (i *hubConnectionIndex) Remove(wc *WebConn) { + wc.Platform.ReturnSessionToPool(wc.GetSession()) + + userConnIndex, ok := i.byConnection[wc] + if !ok { + return + } + + // get the conn slice. + userConnections := i.byUserId[wc.UserId] + // get the last connection. + last := userConnections[len(userConnections)-1] + // set the slot that we are trying to remove to be the last connection. + userConnections[userConnIndex] = last + // remove the last connection from the slice. + i.byUserId[wc.UserId] = userConnections[:len(userConnections)-1] + // set the index of the connection that was moved to the new index. + i.byConnection[last] = userConnIndex + + delete(i.byConnection, wc) + delete(i.byConnectionId, wc.GetConnectionID()) +} + +func (i *hubConnectionIndex) Has(wc *WebConn) bool { + _, ok := i.byConnection[wc] + return ok +} + +// ForUser returns all connections for a user ID. +func (i *hubConnectionIndex) ForUser(id string) []*WebConn { + return i.byUserId[id] +} + +// All returns the full webConn index. +func (i *hubConnectionIndex) All() map[*WebConn]int { + return i.byConnection +} + +// RemoveInactiveByConnectionID removes an inactive connection for the given +// userID and connectionID. +func (i *hubConnectionIndex) RemoveInactiveByConnectionID(userID, connectionID string) *WebConn { + // To handle empty sessions. + if userID == "" { + return nil + } + for _, conn := range i.ForUser(userID) { + if conn.GetConnectionID() == connectionID && !conn.active { + i.Remove(conn) + return conn + } + } + return nil +} + +// RemoveInactiveConnections removes all inactive connections whose lastUserActivityAt +// exceeded staleThreshold. +func (i *hubConnectionIndex) RemoveInactiveConnections() { + now := model.GetMillis() + for conn := range i.byConnection { + if !conn.active && now-conn.lastUserActivityAt > i.staleThreshold.Milliseconds() { + i.Remove(conn) + } + } +} + +// AllActive returns the number of active connections. +// This is only called during register/unregister so we can take +// a bit of perf hit here. +func (i *hubConnectionIndex) AllActive() int { + cnt := 0 + for conn := range i.byConnection { + if conn.active { + cnt++ + } + } + return cnt +} diff --git a/app/web_hub_test.go b/app/platform/web_hub_test.go similarity index 77% rename from app/web_hub_test.go rename to app/platform/web_hub_test.go index 470553791c..a3e1c8d0ae 100644 --- a/app/web_hub_test.go +++ b/app/platform/web_hub_test.go @@ -1,7 +1,7 @@ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. -package app +package platform import ( "net" @@ -15,8 +15,9 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" - "github.com/mattermost/mattermost-server/v6/app/users" + platform_mocks "github.com/mattermost/mattermost-server/v6/app/platform/mocks" "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/plugin" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" "github.com/mattermost/mattermost-server/v6/testlib" @@ -38,12 +39,7 @@ func dummyWebsocketHandler(t *testing.T) http.HandlerFunc { } } -func registerDummyWebConn(t *testing.T, a *App, addr net.Addr, userID string) *WebConn { - session, appErr := a.CreateSession(&model.Session{ - UserId: userID, - }) - require.Nil(t, appErr) - +func registerDummyWebConn(t *testing.T, th *TestHelper, addr net.Addr, session *model.Session) *WebConn { d := websocket.Dialer{} c, _, err := d.Dial("ws://"+addr.String()+"/ws", nil) require.NoError(t, err) @@ -54,8 +50,8 @@ func registerDummyWebConn(t *testing.T, a *App, addr net.Addr, userID string) *W TFunc: i18n.IdentityTfunc(), Locale: "en", } - wc := a.NewWebConn(cfg) - a.HubRegister(wc) + wc := th.Service.NewWebConn(cfg, th.Suite, func() *plugin.Environment { return nil }) + th.Service.HubRegister(wc) go wc.Pump() return wc } @@ -67,10 +63,15 @@ func TestHubStopWithMultipleConnections(t *testing.T) { s := httptest.NewServer(dummyWebsocketHandler(t)) defer s.Close() - th.Server.HubStart() - wc1 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) - wc2 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) - wc3 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) + session, err := th.Service.CreateSession(&model.Session{ + UserId: th.BasicUser.Id, + }) + require.NoError(t, err) + + th.Service.HubStart(th.Suite) + wc1 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + wc2 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + wc3 := registerDummyWebConn(t, th, s.Listener.Addr(), session) defer wc1.Close() defer wc2.Close() defer wc3.Close() @@ -85,17 +86,22 @@ func TestHubStopRaceCondition(t *testing.T) { // So we just use this quick hack for the test. s := httptest.NewServer(dummyWebsocketHandler(t)) - th.Server.HubStart() - wc1 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) + session, err := th.Service.CreateSession(&model.Session{ + UserId: th.BasicUser.Id, + }) + require.NoError(t, err) + + th.Service.HubStart(th.Suite) + wc1 := registerDummyWebConn(t, th, s.Listener.Addr(), session) defer wc1.Close() - hub := th.App.Srv().hubs[0] - th.Server.HubStop() + hub := th.Service.hubs[0] + th.Service.HubStop() done := make(chan bool) go func() { - wc4 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) - wc5 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) + wc4 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + wc5 := registerDummyWebConn(t, th, s.Listener.Addr(), session) hub.Register(wc4) hub.Register(wc5) @@ -131,7 +137,7 @@ func TestHubSessionRevokeRace(t *testing.T) { LastActivityAt: 10000, } - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.Service.Store.(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) @@ -163,35 +169,28 @@ func TestHubSessionRevokeRace(t *testing.T) { mockStore.On("System").Return(&mockSystemStore) mockStore.On("GetDBSchemaVersion").Return(1, nil) - userService, err := users.New(users.ServiceConfig{ - UserStore: &mockUserStore, - SessionStore: &mockSessionStore, - OAuthStore: &mockOAuthStore, - ConfigFn: th.App.ch.srv.platform.Config, - Metrics: th.App.Metrics(), - Cluster: th.App.Cluster(), - LicenseFn: th.App.ch.srv.License, - }) - require.NoError(t, err) - th.App.ch.srv.userService = userService - // This needs to be false for the condition to trigger - th.App.UpdateConfig(func(cfg *model.Config) { + th.Service.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExtendSessionLengthWithActivity = false }) s := httptest.NewServer(dummyWebsocketHandler(t)) defer s.Close() - wc1 := registerDummyWebConn(t, th.App, s.Listener.Addr(), "testid") - hub := th.App.GetHubForUserId(wc1.UserId) + session, err := th.Service.CreateSession(&model.Session{ + UserId: "testid", + }) + require.NoError(t, err) + + wc1 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + hub := th.Service.GetHubForUserId(wc1.UserId) done := make(chan bool) time.Sleep(time.Second) // We override the LastActivityAt which happens in NewWebConn. // This is needed to call RevokeSessionById which triggers the race. - th.App.ch.srv.userService.AddSessionToCache(sess1) + th.Service.AddSessionToCache(sess1) go func() { for i := 0; i <= broadcastQueueSize; i++ { @@ -225,30 +224,34 @@ func TestHubConnIndex(t *testing.T) { // User1 wc1 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } wc1.SetConnectionID(model.NewId()) wc1.SetSession(&model.Session{}) // User2 wc2 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } wc2.SetConnectionID(model.NewId()) wc2.SetSession(&model.Session{}) wc3 := &WebConn{ - App: th.App, - UserId: wc2.UserId, + Platform: th.Service, + Suite: th.Suite, + UserId: wc2.UserId, } wc3.SetConnectionID(model.NewId()) wc3.SetSession(&model.Session{}) wc4 := &WebConn{ - App: th.App, - UserId: wc2.UserId, + Platform: th.Service, + Suite: th.Suite, + UserId: wc2.UserId, } wc4.SetConnectionID(model.NewId()) wc4.SetSession(&model.Session{}) @@ -311,8 +314,9 @@ func TestHubConnIndexByConnectionId(t *testing.T) { // User1 wc1ID := model.NewId() wc1 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } wc1.SetConnectionID(wc1ID) wc1.SetSession(&model.Session{}) @@ -320,16 +324,18 @@ func TestHubConnIndexByConnectionId(t *testing.T) { // User2 wc2ID := model.NewId() wc2 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } wc2.SetConnectionID(wc2ID) wc2.SetSession(&model.Session{}) wc3ID := model.NewId() wc3 := &WebConn{ - App: th.App, - UserId: wc2.UserId, + Platform: th.Service, + Suite: th.Suite, + UserId: wc2.UserId, } wc3.SetConnectionID(wc3ID) wc3.SetSession(&model.Session{}) @@ -369,26 +375,26 @@ func TestHubConnIndexInactive(t *testing.T) { // User1 wc1 := &WebConn{ - App: th.App, - UserId: model.NewId(), - active: true, + Platform: th.Service, + UserId: model.NewId(), + active: true, } wc1.SetConnectionID("conn1") wc1.SetSession(&model.Session{}) // User2 wc2 := &WebConn{ - App: th.App, - UserId: model.NewId(), - active: true, + Platform: th.Service, + UserId: model.NewId(), + active: true, } wc2.SetConnectionID("conn2") wc2.SetSession(&model.Session{}) wc3 := &WebConn{ - App: th.App, - UserId: wc2.UserId, - active: false, + Platform: th.Service, + UserId: wc2.UserId, + active: false, } wc3.SetConnectionID("conn3") wc3.SetSession(&model.Session{}) @@ -420,17 +426,18 @@ func TestHubConnIndexInactive(t *testing.T) { func TestReliableWebSocketSend(t *testing.T) { testCluster := &testlib.FakeClusterInterface{} - th := SetupWithClusterMock(t, testCluster) + th := SetupWithCluster(t, testCluster) defer th.TearDown() ev := model.NewWebSocketEvent("test_unreliable_event", "", "", "", nil, "") ev = ev.SetBroadcast(&model.WebsocketBroadcast{}) - th.App.Publish(ev) + th.Service.Publish(ev) ev2 := model.NewWebSocketEvent("test_reliable_event", "", "", "", nil, "") + ev2 = ev2.SetBroadcast(&model.WebsocketBroadcast{ ReliableClusterSend: true, }) - th.App.Publish(ev2) + th.Service.Publish(ev2) messages := testCluster.GetMessages() @@ -455,28 +462,42 @@ func TestHubIsRegistered(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() + session, err := th.Service.CreateSession(&model.Session{ + UserId: th.BasicUser.Id, + }) + require.NoError(t, err) + + mockSuite := &platform_mocks.SuiteIFace{} + mockSuite.On("SetStatusOnline", th.BasicUser.Id, false).Return() + mockSuite.On("UpdateLastActivityAtIfNeeded", *session).Return() + mockSuite.On("GetSession", session.Token).Return(session, nil) + mockSuite.On("IsUserAway", mock.Anything).Return(false) + mockSuite.On("SetStatusOffline", th.BasicUser.Id, false).Return() + + th.Suite = mockSuite + s := httptest.NewServer(dummyWebsocketHandler(t)) defer s.Close() - th.Server.HubStart() - wc1 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) - wc2 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) - wc3 := registerDummyWebConn(t, th.App, s.Listener.Addr(), th.BasicUser.Id) + th.Service.HubStart(th.Suite) + wc1 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + wc2 := registerDummyWebConn(t, th, s.Listener.Addr(), session) + wc3 := registerDummyWebConn(t, th, s.Listener.Addr(), session) defer wc1.Close() defer wc2.Close() defer wc3.Close() session1 := wc1.session.Load().(*model.Session) - assert.True(t, th.App.SessionIsRegistered(*session1)) - assert.True(t, th.App.SessionIsRegistered(*wc2.session.Load().(*model.Session))) - assert.True(t, th.App.SessionIsRegistered(*wc3.session.Load().(*model.Session))) + assert.True(t, th.Service.SessionIsRegistered(*session1)) + assert.True(t, th.Service.SessionIsRegistered(*wc2.session.Load().(*model.Session))) + assert.True(t, th.Service.SessionIsRegistered(*wc3.session.Load().(*model.Session))) - session4, appErr := th.App.CreateSession(&model.Session{ + session4, err := th.Service.CreateSession(&model.Session{ UserId: th.BasicUser2.Id, }) - require.Nil(t, appErr) - assert.False(t, th.App.SessionIsRegistered(*session4)) + require.NoError(t, err) + assert.False(t, th.Service.SessionIsRegistered(*session4)) } // Always run this with -benchtime=0.1s @@ -488,14 +509,16 @@ func BenchmarkHubConnIndex(b *testing.B) { // User1 wc1 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } // User2 wc2 := &WebConn{ - App: th.App, - UserId: model.NewId(), + Platform: th.Service, + Suite: th.Suite, + UserId: model.NewId(), } b.ResetTimer() b.Run("Add", func(b *testing.B) { @@ -529,10 +552,10 @@ func BenchmarkGetHubForUserId(b *testing.B) { th := Setup(b).InitBasic() defer th.TearDown() - th.Server.HubStart() + th.Service.HubStart(th.Suite) b.ResetTimer() for i := 0; i < b.N; i++ { - hubSink = th.Server.GetHubForUserId(th.BasicUser.Id) + hubSink = th.Service.GetHubForUserId(th.BasicUser.Id) } } diff --git a/app/platform/websocket_router.go b/app/platform/websocket_router.go new file mode 100644 index 0000000000..2b465dffb6 --- /dev/null +++ b/app/platform/websocket_router.go @@ -0,0 +1,113 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package platform + +import ( + "net/http" + + "github.com/mattermost/mattermost-server/v6/model" + "github.com/mattermost/mattermost-server/v6/shared/i18n" + "github.com/mattermost/mattermost-server/v6/shared/mlog" +) + +type webSocketHandler interface { + ServeWebSocket(*WebConn, *model.WebSocketRequest) +} + +type WebSocketRouter struct { + handlers map[string]webSocketHandler +} + +func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) { + wr.handlers[action] = handler +} + +func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { + if r.Action == "" { + err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) + returnWebSocketError(conn.Platform, conn, r, err) + return + } + + if r.Seq <= 0 { + err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_seq.app_error", nil, "", http.StatusBadRequest) + returnWebSocketError(conn.Platform, conn, r, err) + return + } + + if r.Action == model.WebsocketAuthenticationChallenge { + if conn.GetSessionToken() != "" { + return + } + + token, ok := r.Data["token"].(string) + if !ok { + conn.WebSocket.Close() + return + } + + session, err := conn.Suite.GetSession(token) + if err != nil { + conn.WebSocket.Close() + return + } + conn.SetSession(session) + conn.SetSessionToken(session.Token) + conn.UserId = session.UserId + + conn.Platform.HubRegister(conn) + + conn.Platform.Go(func() { + conn.Suite.SetStatusOnline(session.UserId, false) + conn.Suite.UpdateLastActivityAtIfNeeded(*session) + }) + + resp := model.NewWebSocketResponse(model.StatusOk, r.Seq, nil) + hub := conn.Platform.GetHubForUserId(conn.UserId) + if hub == nil { + return + } + hub.SendMessage(conn, resp) + + return + } + + if !conn.IsAuthenticated() { + err := model.NewAppError("ServeWebSocket", "api.web_socket_router.not_authenticated.app_error", nil, "", http.StatusUnauthorized) + returnWebSocketError(conn.Platform, conn, r, err) + return + } + + handler, ok := wr.handlers[r.Action] + if !ok { + err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_action.app_error", nil, "", http.StatusInternalServerError) + returnWebSocketError(conn.Platform, conn, r, err) + return + } + + handler.ServeWebSocket(conn, r) +} + +func returnWebSocketError(ps *PlatformService, conn *WebConn, r *model.WebSocketRequest, err *model.AppError) { + logF := mlog.Error + if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { + logF = mlog.Debug + } + logF( + "websocket routing error.", + mlog.Int64("seq", r.Seq), + mlog.String("user_id", conn.UserId), + mlog.String("system_message", err.SystemMessage(i18n.T)), + mlog.Err(err), + ) + + hub := ps.GetHubForUserId(conn.UserId) + if hub == nil { + return + } + + err.DetailedError = "" + errorResp := model.NewWebSocketError(r.Seq, err) + hub.SendMessage(conn, errorResp) +} diff --git a/app/plugin.go b/app/plugin.go index 00cabfdbc2..50b750f11c 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -93,6 +93,7 @@ func (ch *Channels) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment defer ch.pluginsLock.Unlock() ch.pluginsEnvironment = pluginsEnvironment + ch.srv.Platform().SetPluginsEnvironment(pluginsEnvironment) } func (ch *Channels) syncPluginsActiveState() { @@ -148,7 +149,7 @@ func (ch *Channels) syncPluginsActiveState() { if deactivated && plugin.Manifest.HasClient() { message := model.NewWebSocketEvent(model.WebsocketEventPluginDisabled, "", "", "", nil, "") message.Add("manifest", plugin.Manifest.ClientManifest()) - ch.srv.Publish(message) + ch.srv.platform.Publish(message) } }(plugin) } @@ -198,6 +199,10 @@ func (a *App) InitPlugins(c *request.Context, pluginDir, webappPluginDir string) func (ch *Channels) initPlugins(c *request.Context, pluginDir, webappPluginDir string) { // Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment. + defer func() { + ch.srv.Platform().SetPluginsEnvironment(ch.pluginsEnvironment) + }() + ch.pluginsLock.RLock() pluginsEnvironment := ch.pluginsEnvironment ch.pluginsLock.RUnlock() @@ -840,9 +845,9 @@ func (ch *Channels) notifyPluginEnabled(manifest *model.Manifest) error { var statuses model.PluginStatuses - if ch.srv.Cluster != nil { + if ch.srv.platform.Cluster() != nil { var err *model.AppError - statuses, err = ch.srv.Cluster.GetPluginStatuses() + statuses, err = ch.srv.platform.Cluster().GetPluginStatuses() if err != nil { return err } @@ -868,7 +873,7 @@ func (ch *Channels) notifyPluginEnabled(manifest *model.Manifest) error { // Notify all cluster peer clients. message := model.NewWebSocketEvent(model.WebsocketEventPluginEnabled, "", "", "", nil, "") message.Add("manifest", manifest.ClientManifest()) - ch.srv.Publish(message) + ch.srv.platform.Publish(message) return nil } diff --git a/app/plugin_api.go b/app/plugin_api.go index ad50fc1360..ad33a4d4d9 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -140,7 +140,7 @@ func (api *PluginAPI) GetServerVersion() string { } func (api *PluginAPI) GetSystemInstallDate() (int64, *model.AppError) { - return api.app.Srv().getSystemInstallDate() + return api.app.Srv().Platform().GetSystemInstallDate() } func (api *PluginAPI) GetDiagnosticId() string { @@ -287,12 +287,12 @@ func (api *PluginAPI) CreateSession(session *model.Session) (*model.Session, *mo } func (api *PluginAPI) ExtendSessionExpiry(sessionID string, expiresAt int64) *model.AppError { - session, err := api.app.ch.srv.userService.GetSessionByID(sessionID) + session, err := api.app.ch.srv.platform.GetSessionByID(sessionID) if err != nil { return model.NewAppError("extendSessionExpiry", "app.session.get_sessions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := api.app.ch.srv.userService.ExtendSessionExpiry(session, expiresAt); err != nil { + if err := api.app.ch.srv.platform.ExtendSessionExpiry(session, expiresAt); err != nil { return model.NewAppError("extendSessionExpiry", "app.session.extend_session_expiry.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1091,7 +1091,7 @@ func (api *PluginAPI) ListCommands(teamID string) ([]*model.Command, error) { func (api *PluginAPI) ListCustomCommands(teamID string) ([]*model.Command, error) { // Plugins are allowed to bypass the a.Config().ServiceSettings.EnableCommands setting. - return api.app.Srv().Store.Command().GetByTeam(teamID) + return api.app.Srv().Store().Command().GetByTeam(teamID) } func (api *PluginAPI) ListPluginCommands(teamID string) ([]*model.Command, error) { @@ -1127,7 +1127,7 @@ func (api *PluginAPI) ListBuiltInCommands() ([]*model.Command, error) { } func (api *PluginAPI) GetCommand(commandID string) (*model.Command, error) { - return api.app.Srv().Store.Command().Get(commandID) + return api.app.Srv().Store().Command().Get(commandID) } func (api *PluginAPI) UpdateCommand(commandID string, updatedCmd *model.Command) (*model.Command, error) { @@ -1147,11 +1147,11 @@ func (api *PluginAPI) UpdateCommand(commandID string, updatedCmd *model.Command) updatedCmd.TeamId = oldCmd.TeamId } - return api.app.Srv().Store.Command().Update(updatedCmd) + return api.app.Srv().Store().Command().Update(updatedCmd) } func (api *PluginAPI) DeleteCommand(commandID string) error { - err := api.app.Srv().Store.Command().Delete(commandID, model.GetMillis()) + err := api.app.Srv().Store().Command().Delete(commandID, model.GetMillis()) if err != nil { return err } diff --git a/app/plugin_api_test.go b/app/plugin_api_test.go index 21a1d89af4..1068adaa64 100644 --- a/app/plugin_api_test.go +++ b/app/plugin_api_test.go @@ -570,7 +570,7 @@ func TestPluginAPIGetFile(t *testing.T) { info, err := th.App.DoUploadFile(th.Context, uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info.Id) th.App.RemoveFile(info.Path) }() @@ -599,7 +599,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { ) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(fileInfo1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo1.Id) th.App.RemoveFile(fileInfo1.Path) }() @@ -613,7 +613,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { ) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(fileInfo2.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo2.Id) th.App.RemoveFile(fileInfo2.Path) }() @@ -627,7 +627,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) { ) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(fileInfo3.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo3.Id) th.App.RemoveFile(fileInfo3.Path) }() @@ -1135,7 +1135,7 @@ func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string, if settingsSchema != "" { schema = settingsSchema } - th.App.ch.srv.sqlStore = th.GetSqlStore() + th.App.ch.srv.platform.SetSqlStore(th.GetSqlStore()) // TODO: platform: check if necessary setupPluginAPITest(t, code, fmt.Sprintf(`{"id": "%v", "server": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema), id, th.App, th.Context) @@ -1360,7 +1360,7 @@ func TestPluginCreatePostWithUploadedFile(t *testing.T) { fileInfo, err := api.UploadFile(data, channelID, filename) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(fileInfo.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(fileInfo.Id) th.App.RemoveFile(fileInfo.Path) }() diff --git a/app/plugin_db_driver.go b/app/plugin_db_driver.go index 7962f8ede0..753bd0671c 100644 --- a/app/plugin_db_driver.go +++ b/app/plugin_db_driver.go @@ -40,9 +40,9 @@ func NewDriverImpl(s *Server) *DriverImpl { } func (d *DriverImpl) Conn(isMaster bool) (string, error) { - dbFunc := d.s.sqlStore.GetMasterX + dbFunc := d.s.Platform().Store.GetInternalMasterDB if !isMaster { - dbFunc = d.s.sqlStore.GetReplicaX + dbFunc = d.s.Platform().Store.GetInternalReplicaDB } conn, err := dbFunc().Conn(context.Background()) if err != nil { diff --git a/app/plugin_event.go b/app/plugin_event.go index b4b68be3b5..c30e2d1af5 100644 --- a/app/plugin_event.go +++ b/app/plugin_event.go @@ -11,8 +11,8 @@ import ( func (ch *Channels) notifyClusterPluginEvent(event model.ClusterEvent, data model.PluginEventData) { buf, _ := json.Marshal(data) - if ch.srv.Cluster != nil { - ch.srv.Cluster.SendClusterMessage(&model.ClusterMessage{ + if ch.srv.platform.Cluster() != nil { + ch.srv.platform.Cluster().SendClusterMessage(&model.ClusterMessage{ Event: event, SendType: model.ClusterSendReliable, WaitForAllToSend: true, diff --git a/app/plugin_hooks_test.go b/app/plugin_hooks_test.go index b6e26b562f..1b1673be93 100644 --- a/app/plugin_hooks_test.go +++ b/app/plugin_hooks_test.go @@ -182,7 +182,7 @@ func TestHookMessageWillBePosted(t *testing.T) { require.Nil(t, err) assert.Equal(t, "message", post.Message) - retrievedPost, errSingle := th.App.Srv().Store.Post().GetSingle(post.Id, false) + retrievedPost, errSingle := th.App.Srv().Store().Post().GetSingle(post.Id, false) require.NoError(t, errSingle) assert.Equal(t, "message", retrievedPost.Message) }) @@ -226,7 +226,7 @@ func TestHookMessageWillBePosted(t *testing.T) { require.Nil(t, err) assert.Equal(t, "message_fromplugin", post.Message) - retrievedPost, errSingle := th.App.Srv().Store.Post().GetSingle(post.Id, false) + retrievedPost, errSingle := th.App.Srv().Store().Post().GetSingle(post.Id, false) require.NoError(t, errSingle) assert.Equal(t, "message_fromplugin", retrievedPost.Message) }) diff --git a/app/plugin_key_value_store.go b/app/plugin_key_value_store.go index 961932ea30..c4fa86d639 100644 --- a/app/plugin_key_value_store.go +++ b/app/plugin_key_value_store.go @@ -10,23 +10,10 @@ import ( "net/http" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/product" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" ) -// Ensure KV store wrapper implements `product.KVStoreService` -var _ product.KVStoreService = (*kvStoreWrapper)(nil) - -// kvStoreWrapper provides an implementation of `product.KVStoreService` for use by products. -type kvStoreWrapper struct { - srv *Server -} - -func (k *kvStoreWrapper) SetPluginKeyWithOptions(pluginID string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) { - return k.srv.setPluginKeyWithOptions(pluginID, key, value, options) -} - func getKeyHash(key string) string { hash := sha256.New() hash.Write([]byte(key)) @@ -53,34 +40,8 @@ func (a *App) CompareAndSetPluginKey(pluginID string, key string, oldValue, newV return a.SetPluginKeyWithOptions(pluginID, key, newValue, options) } -func (s *Server) setPluginKeyWithOptions(pluginID string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) { - if err := options.IsValid(); err != nil { - mlog.Debug("Failed to set plugin key value with options", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) - return false, err - } - - updated, err := s.Store.Plugin().SetWithOptions(pluginID, key, value, options) - if err != nil { - mlog.Error("Failed to set plugin key value with options", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) - var appErr *model.AppError - switch { - case errors.As(err, &appErr): - return false, appErr - default: - return false, model.NewAppError("SetPluginKeyWithOptions", "app.plugin_store.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - } - - // Clean up a previous entry using the hashed key, if it exists. - if err := s.Store.Plugin().Delete(pluginID, getKeyHash(key)); err != nil { - mlog.Warn("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) - } - - return updated, nil -} - func (a *App) SetPluginKeyWithOptions(pluginID string, key string, value []byte, options model.PluginKVSetOptions) (bool, *model.AppError) { - return a.Srv().setPluginKeyWithOptions(pluginID, key, value, options) + return a.Srv().Platform().SetPluginKeyWithOptions(pluginID, key, value, options) } func (a *App) CompareAndDeletePluginKey(pluginID string, key string, oldValue []byte) (bool, *model.AppError) { @@ -89,7 +50,7 @@ func (a *App) CompareAndDeletePluginKey(pluginID string, key string, oldValue [] Key: key, } - deleted, err := a.Srv().Store.Plugin().CompareAndDelete(kv, oldValue) + deleted, err := a.Srv().Store().Plugin().CompareAndDelete(kv, oldValue) if err != nil { mlog.Error("Failed to compare and delete plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) var appErr *model.AppError @@ -102,15 +63,16 @@ func (a *App) CompareAndDeletePluginKey(pluginID string, key string, oldValue [] } // Clean up a previous entry using the hashed key, if it exists. - if err := a.Srv().Store.Plugin().Delete(pluginID, getKeyHash(key)); err != nil { + if err := a.Srv().Store().Plugin().Delete(pluginID, getKeyHash(key)); err != nil { mlog.Warn("Failed to clean up previously hashed plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) } return deleted, nil } +// TODO: platform: remove func (s *Server) getPluginKey(pluginID string, key string) ([]byte, *model.AppError) { - if kv, err := s.Store.Plugin().Get(pluginID, key); err == nil { + if kv, err := s.Store().Plugin().Get(pluginID, key); err == nil { return kv.Value, nil } else if nfErr := new(store.ErrNotFound); !errors.As(err, &nfErr) { mlog.Error("Failed to query plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) @@ -118,7 +80,7 @@ func (s *Server) getPluginKey(pluginID string, key string) ([]byte, *model.AppEr } // Lookup using the hashed version of the key for keys written prior to v5.6. - if kv, err := s.Store.Plugin().Get(pluginID, getKeyHash(key)); err == nil { + if kv, err := s.Store().Plugin().Get(pluginID, getKeyHash(key)); err == nil { return kv.Value, nil } else if nfErr := new(store.ErrNotFound); !errors.As(err, &nfErr) { mlog.Error("Failed to query plugin key value using hashed key", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) @@ -132,27 +94,12 @@ func (a *App) GetPluginKey(pluginID string, key string) ([]byte, *model.AppError return a.Srv().getPluginKey(pluginID, key) } -func (s *Server) deletePluginKey(pluginID string, key string) *model.AppError { - if err := s.Store.Plugin().Delete(pluginID, getKeyHash(key)); err != nil { - mlog.Error("Failed to delete plugin key value", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) - return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - // Also delete the key without hashing - if err := s.Store.Plugin().Delete(pluginID, key); err != nil { - mlog.Error("Failed to delete plugin key value using hashed key", mlog.String("plugin_id", pluginID), mlog.String("key", key), mlog.Err(err)) - return model.NewAppError("DeletePluginKey", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - return nil -} - func (a *App) DeletePluginKey(pluginID string, key string) *model.AppError { - return a.Srv().deletePluginKey(pluginID, key) + return a.Srv().Platform().DeletePluginKey(pluginID, key) } func (a *App) DeleteAllKeysForPlugin(pluginID string) *model.AppError { - if err := a.Srv().Store.Plugin().DeleteAllForPlugin(pluginID); err != nil { + if err := a.Srv().Store().Plugin().DeleteAllForPlugin(pluginID); err != nil { mlog.Error("Failed to delete all plugin key values", mlog.String("plugin_id", pluginID), mlog.Err(err)) return model.NewAppError("DeleteAllKeysForPlugin", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -165,7 +112,7 @@ func (a *App) DeleteAllExpiredPluginKeys() *model.AppError { return nil } - if err := a.Srv().Store.Plugin().DeleteAllExpired(); err != nil { + if err := a.Srv().Store().Plugin().DeleteAllExpired(); err != nil { mlog.Error("Failed to delete all expired plugin key values", mlog.Err(err)) return model.NewAppError("DeleteAllExpiredPluginKeys", "app.plugin_store.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -173,17 +120,6 @@ func (a *App) DeleteAllExpiredPluginKeys() *model.AppError { return nil } -func (s *Server) listPluginKeys(pluginID string, page, perPage int) ([]string, *model.AppError) { - data, err := s.Store.Plugin().List(pluginID, page*perPage, perPage) - - if err != nil { - mlog.Error("Failed to list plugin key values", mlog.Int("page", page), mlog.Int("perPage", perPage), mlog.Err(err)) - return nil, model.NewAppError("ListPluginKeys", "app.plugin_store.list.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - return data, nil -} - func (a *App) ListPluginKeys(pluginID string, page, perPage int) ([]string, *model.AppError) { - return a.Srv().listPluginKeys(pluginID, page, perPage) + return a.Srv().Platform().ListPluginKeys(pluginID, page, perPage) } diff --git a/app/plugin_requests.go b/app/plugin_requests.go index 5e75a10457..1ccc966822 100644 --- a/app/plugin_requests.go +++ b/app/plugin_requests.go @@ -149,7 +149,7 @@ func (ch *Channels) servePluginRequest(w http.ResponseWriter, r *http.Request, h r.Header.Del("Mattermost-User-Id") if token != "" { session, err := New(ServerConnector(ch)).GetSession(token) - defer ch.srv.userService.ReturnSessionToPool(session) + defer ch.srv.platform.ReturnSessionToPool(session) csrfCheckPassed := false diff --git a/app/plugin_signature_test.go b/app/plugin_signature_test.go index 20e50bc414..f57043e4e4 100644 --- a/app/plugin_signature_test.go +++ b/app/plugin_signature_test.go @@ -20,7 +20,7 @@ func TestPluginPublicKeys(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} diff --git a/app/plugin_statuses.go b/app/plugin_statuses.go index c183c6402d..399d58e5b2 100644 --- a/app/plugin_statuses.go +++ b/app/plugin_statuses.go @@ -24,8 +24,8 @@ func (ch *Channels) GetPluginStatus(id string) (*model.PluginStatus, *model.AppE for _, status := range pluginStatuses { if status.PluginId == id { // Add our cluster ID - if ch.srv.Cluster != nil { - status.ClusterId = ch.srv.Cluster.GetClusterId() + if ch.srv.platform.Cluster() != nil { + status.ClusterId = ch.srv.platform.Cluster().GetClusterId() } return status, nil @@ -54,8 +54,8 @@ func (ch *Channels) GetPluginStatuses() (model.PluginStatuses, *model.AppError) // Add our cluster ID for _, status := range pluginStatuses { - if ch.srv.Cluster != nil { - status.ClusterId = ch.srv.Cluster.GetClusterId() + if ch.srv.platform.Cluster() != nil { + status.ClusterId = ch.srv.platform.Cluster().GetClusterId() } else { status.ClusterId = "" } @@ -80,8 +80,8 @@ func (ch *Channels) getClusterPluginStatuses() (model.PluginStatuses, *model.App return nil, err } - if ch.srv.Cluster != nil && *ch.cfgSvc.Config().ClusterSettings.Enable { - clusterPluginStatuses, err := ch.srv.Cluster.GetPluginStatuses() + if ch.srv.platform.Cluster() != nil && *ch.cfgSvc.Config().ClusterSettings.Enable { + clusterPluginStatuses, err := ch.srv.platform.Cluster().GetPluginStatuses() if err != nil { return nil, model.NewAppError("GetClusterPluginStatuses", "app.plugin.get_cluster_plugin_statuses.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -102,7 +102,7 @@ func (ch *Channels) notifyPluginStatusesChanged() error { message := model.NewWebSocketEvent(model.WebsocketEventPluginStatusesChanged, "", "", "", nil, "") message.Add("plugin_statuses", pluginStatuses) message.GetBroadcast().ContainsSensitiveData = true - ch.srv.Publish(message) + ch.srv.platform.Publish(message) return nil } diff --git a/app/plugin_test.go b/app/plugin_test.go index 47f7a2a86a..fcc719c891 100644 --- a/app/plugin_test.go +++ b/app/plugin_test.go @@ -78,7 +78,7 @@ func TestPluginKeyValueStore(t *testing.T) { ExpireAt: 0, } - _, nErr := th.App.Srv().Store.Plugin().SaveOrUpdate(kv) + _, nErr := th.App.Srv().Store().Plugin().SaveOrUpdate(kv) assert.NoError(t, nErr) // Test fetch by keyname (this key does not exist but hashed key will be used for lookup) diff --git a/app/post.go b/app/post.go index 0a3cd3ba36..a204bc8119 100644 --- a/app/post.go +++ b/app/post.go @@ -48,7 +48,7 @@ func (s *postServiceWrapper) CreatePost(ctx *request.Context, post *model.Post) func (a *App) CreatePostAsUser(c request.CTX, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) { // Check that channel has not been deleted - channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true) + channel, errCh := a.Srv().Store().Channel().Get(post.ChannelId, true) if errCh != nil { err := model.NewAppError("CreatePostAsUser", "api.context.invalid_param.app_error", map[string]any{"Name": "post.channel_id"}, "", http.StatusBadRequest).Wrap(errCh) return nil, err @@ -96,7 +96,7 @@ func (a *App) CreatePostAsUser(c request.CTX, post *model.Post, currentSessionId } func (a *App) CreatePostMissingChannel(c request.CTX, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) { - channel, err := a.Srv().Store.Channel().Get(post.ChannelId, true) + channel, err := a.Srv().Store().Channel().Get(post.ChannelId, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -182,13 +182,13 @@ func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel if post.RootId != "" { pchan = make(chan store.StoreResult, 1) go func() { - r, pErr := a.Srv().Store.Post().Get(sqlstore.WithMaster(context.Background()), post.RootId, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) + r, pErr := a.Srv().Store().Post().Get(sqlstore.WithMaster(context.Background()), post.RootId, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) pchan <- store.StoreResult{Data: r, NErr: pErr} close(pchan) }() } - user, nErr := a.Srv().Store.User().Get(context.Background(), post.UserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), post.UserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -296,7 +296,7 @@ func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel post.AddProp(model.PostPropsPreviewedPost, previewPost.PostID) } - rpost, nErr := a.Srv().Store.Post().Save(post) + rpost, nErr := a.Srv().Store().Post().Save(post) if nErr != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -347,7 +347,7 @@ func (a *App) CreatePost(c request.CTX, post *model.Post, channel *model.Channel // Make sure poster is following the thread if *a.Config().ServiceSettings.ThreadAutoFollow && rpost.RootId != "" { - _, err := a.Srv().Store.Thread().MaintainMembership(user.Id, rpost.RootId, store.ThreadMembershipOpts{ + _, err := a.Srv().Store().Thread().MaintainMembership(user.Id, rpost.RootId, store.ThreadMembershipOpts{ Following: true, UpdateFollowing: true, }) @@ -378,7 +378,7 @@ func (a *App) addPostPreviewProp(post *model.Post) (*model.Post, error) { if previewPost != nil { updatedPost := post.Clone() updatedPost.AddProp(model.PostPropsPreviewedPost, previewPost.PostID) - updatedPost, err := a.Srv().Store.Post().Update(updatedPost, post) + updatedPost, err := a.Srv().Store().Post().Update(updatedPost, post) return updatedPost, err } return post, nil @@ -387,7 +387,7 @@ func (a *App) addPostPreviewProp(post *model.Post) (*model.Post, error) { func (a *App) attachFilesToPost(post *model.Post) *model.AppError { var attachedIds []string for _, fileID := range post.FileIds { - err := a.Srv().Store.FileInfo().AttachToPost(fileID, post.Id, post.UserId) + err := a.Srv().Store().FileInfo().AttachToPost(fileID, post.Id, post.UserId) if err != nil { mlog.Warn("Failed to attach file to post", mlog.String("file_id", fileID), mlog.String("post_id", post.Id), mlog.Err(err)) continue @@ -400,7 +400,7 @@ func (a *App) attachFilesToPost(post *model.Post) *model.AppError { // We couldn't attach all files to the post, so ensure that post.FileIds reflects what was actually attached post.FileIds = attachedIds - if _, err := a.Srv().Store.Post().Overwrite(post); err != nil { + if _, err := a.Srv().Store().Post().Overwrite(post); err != nil { return model.NewAppError("attachFilesToPost", "app.post.overwrite.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } } @@ -418,7 +418,7 @@ func (a *App) FillInPostProps(c request.CTX, post *model.Post, channel *model.Ch if len(channelMentions) > 0 { if channel == nil { - postChannel, err := a.Srv().Store.Channel().GetForPost(post.Id) + postChannel, err := a.Srv().Store().Channel().GetForPost(post.Id) if err != nil { return model.NewAppError("FillInPostProps", "api.context.invalid_param.app_error", map[string]any{"Name": "post.channel_id"}, "", http.StatusBadRequest).Wrap(err) } @@ -432,7 +432,7 @@ func (a *App) FillInPostProps(c request.CTX, post *model.Post, channel *model.Ch for _, mentioned := range mentionedChannels { if mentioned.Type == model.ChannelTypeOpen { - team, err := a.Srv().Store.Team().Get(mentioned.TeamId) + team, err := a.Srv().Store().Team().Get(mentioned.TeamId) if err != nil { mlog.Warn("Failed to get team of the channel mention", mlog.String("team_id", channel.TeamId), mlog.String("channel_id", channel.Id), mlog.Err(err)) continue @@ -462,7 +462,7 @@ func (a *App) FillInPostProps(c request.CTX, post *model.Post, channel *model.Ch func (a *App) handlePostEvents(c request.CTX, post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error { var team *model.Team if channel.TeamId != "" { - t, err := a.Srv().Store.Team().Get(channel.TeamId) + t, err := a.Srv().Store().Team().Get(channel.TeamId) if err != nil { return err } @@ -472,7 +472,7 @@ func (a *App) handlePostEvents(c request.CTX, post *model.Post, user *model.User team = &model.Team{} } - a.invalidateCacheForChannel(channel) + a.Srv().Platform().InvalidateCacheForChannel(channel) a.invalidateCacheForChannelPosts(channel.Id) if _, err := a.SendNotifications(c, post, team, channel, user, parentPostList, setOnline); err != nil { @@ -571,7 +571,7 @@ func (a *App) DeleteEphemeralPost(userID, postID string) { func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) { post.SanitizeProps() - postLists, nErr := a.Srv().Store.Post().Get(context.Background(), post.Id, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) + postLists, nErr := a.Srv().Store().Post().Get(context.Background(), post.Id, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions()) if nErr != nil { var nfErr *store.ErrNotFound var invErr *store.ErrInvalidInput @@ -659,7 +659,7 @@ func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) newPost.Metadata = oldPost.Metadata } - rpost, nErr := a.Srv().Store.Post().Update(newPost, oldPost) + rpost, nErr := a.Srv().Store().Post().Update(newPost, oldPost) if nErr != nil { var appErr *model.AppError switch { @@ -807,7 +807,7 @@ func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatc } func (a *App) GetPostsPage(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetPosts(options, false, a.Config().GetSanitizeOptions()) + postList, err := a.Srv().Store().Post().GetPosts(options, false, a.Config().GetSanitizeOptions()) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -827,7 +827,7 @@ func (a *App) GetPostsPage(options model.GetPostsOptions) (*model.PostList, *mod } func (a *App) GetPosts(channelID string, offset int, limit int) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetPosts(model.GetPostsOptions{ChannelId: channelID, Page: offset, PerPage: limit}, true, a.Config().GetSanitizeOptions()) + postList, err := a.Srv().Store().Post().GetPosts(model.GetPostsOptions{ChannelId: channelID, Page: offset, PerPage: limit}, true, a.Config().GetSanitizeOptions()) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -846,11 +846,11 @@ func (a *App) GetPosts(channelID string, offset int, limit int) (*model.PostList } func (a *App) GetPostsEtag(channelID string, collapsedThreads bool) string { - return a.Srv().Store.Post().GetEtag(channelID, true, collapsedThreads) + return a.Srv().Store().Post().GetEtag(channelID, true, collapsedThreads) } func (a *App) GetPostsSince(options model.GetPostsSinceOptions) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetPostsSince(options, true, a.Config().GetSanitizeOptions()) + postList, err := a.Srv().Store().Post().GetPostsSince(options, true, a.Config().GetSanitizeOptions()) if err != nil { return nil, model.NewAppError("GetPostsSince", "app.post.get_posts_since.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -863,7 +863,7 @@ func (a *App) GetPostsSince(options model.GetPostsSinceOptions) (*model.PostList } func (a *App) GetSinglePost(postID string, includeDeleted bool) (*model.Post, *model.AppError) { - post, err := a.Srv().Store.Post().GetSingle(postID, includeDeleted) + post, err := a.Srv().Store().Post().GetSingle(postID, includeDeleted) if err != nil { var nfErr *store.ErrNotFound switch { @@ -886,7 +886,7 @@ func (a *App) GetSinglePost(postID string, includeDeleted bool) (*model.Post, *m } func (a *App) GetPostThread(postID string, opts model.GetPostsOptions, userID string) (*model.PostList, *model.AppError) { - posts, err := a.Srv().Store.Post().Get(context.Background(), postID, opts, userID, a.Config().GetSanitizeOptions()) + posts, err := a.Srv().Store().Post().Get(context.Background(), postID, opts, userID, a.Config().GetSanitizeOptions()) if err != nil { var nfErr *store.ErrNotFound var invErr *store.ErrInvalidInput @@ -916,7 +916,7 @@ func (a *App) GetPostThread(postID string, opts model.GetPostsOptions, userID st } func (a *App) GetFlaggedPosts(userID string, offset int, limit int) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetFlaggedPosts(userID, offset, limit) + postList, err := a.Srv().Store().Post().GetFlaggedPosts(userID, offset, limit) if err != nil { return nil, model.NewAppError("GetFlaggedPosts", "app.post.get_flagged_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -929,7 +929,7 @@ func (a *App) GetFlaggedPosts(userID string, offset int, limit int) (*model.Post } func (a *App) GetFlaggedPostsForTeam(userID, teamID string, offset int, limit int) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetFlaggedPostsForTeam(userID, teamID, offset, limit) + postList, err := a.Srv().Store().Post().GetFlaggedPostsForTeam(userID, teamID, offset, limit) if err != nil { return nil, model.NewAppError("GetFlaggedPostsForTeam", "app.post.get_flagged_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -942,7 +942,7 @@ func (a *App) GetFlaggedPostsForTeam(userID, teamID string, offset int, limit in } func (a *App) GetFlaggedPostsForChannel(userID, channelID string, offset int, limit int) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetFlaggedPostsForChannel(userID, channelID, offset, limit) + postList, err := a.Srv().Store().Post().GetFlaggedPostsForChannel(userID, channelID, offset, limit) if err != nil { return nil, model.NewAppError("GetFlaggedPostsForChannel", "app.post.get_flagged_posts.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -955,7 +955,7 @@ func (a *App) GetFlaggedPostsForChannel(userID, channelID string, offset int, li } func (a *App) GetPermalinkPost(c request.CTX, postID string, userID string) (*model.PostList, *model.AppError) { - list, nErr := a.Srv().Store.Post().Get(context.Background(), postID, model.GetPostsOptions{}, userID, a.Config().GetSanitizeOptions()) + list, nErr := a.Srv().Store().Post().Get(context.Background(), postID, model.GetPostsOptions{}, userID, a.Config().GetSanitizeOptions()) if nErr != nil { var nfErr *store.ErrNotFound var invErr *store.ErrInvalidInput @@ -991,7 +991,7 @@ func (a *App) GetPermalinkPost(c request.CTX, postID string, userID string) (*mo } func (a *App) GetPostsBeforePost(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetPostsBefore(options, a.Config().GetSanitizeOptions()) + postList, err := a.Srv().Store().Post().GetPostsBefore(options, a.Config().GetSanitizeOptions()) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -1019,7 +1019,7 @@ func (a *App) GetPostsBeforePost(options model.GetPostsOptions) (*model.PostList } func (a *App) GetPostsAfterPost(options model.GetPostsOptions) (*model.PostList, *model.AppError) { - postList, err := a.Srv().Store.Post().GetPostsAfter(options, a.Config().GetSanitizeOptions()) + postList, err := a.Srv().Store().Post().GetPostsAfter(options, a.Config().GetSanitizeOptions()) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -1051,9 +1051,9 @@ func (a *App) GetPostsAroundPost(before bool, options model.GetPostsOptions) (*m var err error sanitize := a.Config().GetSanitizeOptions() if before { - postList, err = a.Srv().Store.Post().GetPostsBefore(options, sanitize) + postList, err = a.Srv().Store().Post().GetPostsBefore(options, sanitize) } else { - postList, err = a.Srv().Store.Post().GetPostsAfter(options, sanitize) + postList, err = a.Srv().Store().Post().GetPostsAfter(options, sanitize) } if err != nil { @@ -1083,7 +1083,7 @@ func (a *App) GetPostsAroundPost(before bool, options model.GetPostsOptions) (*m } func (a *App) GetPostAfterTime(channelID string, time int64, collapsedThreads bool) (*model.Post, *model.AppError) { - post, err := a.Srv().Store.Post().GetPostAfterTime(channelID, time, collapsedThreads) + post, err := a.Srv().Store().Post().GetPostAfterTime(channelID, time, collapsedThreads) if err != nil { return nil, model.NewAppError("GetPostAfterTime", "app.post.get_post_after_time.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1092,7 +1092,7 @@ func (a *App) GetPostAfterTime(channelID string, time int64, collapsedThreads bo } func (a *App) GetPostIdAfterTime(channelID string, time int64, collapsedThreads bool) (string, *model.AppError) { - postID, err := a.Srv().Store.Post().GetPostIdAfterTime(channelID, time, collapsedThreads) + postID, err := a.Srv().Store().Post().GetPostIdAfterTime(channelID, time, collapsedThreads) if err != nil { return "", model.NewAppError("GetPostIdAfterTime", "app.post.get_post_id_around.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1101,7 +1101,7 @@ func (a *App) GetPostIdAfterTime(channelID string, time int64, collapsedThreads } func (a *App) GetPostIdBeforeTime(channelID string, time int64, collapsedThreads bool) (string, *model.AppError) { - postID, err := a.Srv().Store.Post().GetPostIdBeforeTime(channelID, time, collapsedThreads) + postID, err := a.Srv().Store().Post().GetPostIdBeforeTime(channelID, time, collapsedThreads) if err != nil { return "", model.NewAppError("GetPostIdBeforeTime", "app.post.get_post_id_around.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1233,7 +1233,7 @@ func (a *App) GetPostsForChannelAroundLastUnread(c request.CTX, channelID, userI } func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, *model.AppError) { - post, err := a.Srv().Store.Post().GetSingle(postID, false) + post, err := a.Srv().Store().Post().GetSingle(postID, false) if err != nil { return nil, model.NewAppError("DeletePost", "app.post.get.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1248,7 +1248,7 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, return nil, appErr } - err = a.Srv().Store.Post().Delete(postID, model.GetMillis(), deleteByID) + err = a.Srv().Store().Post().Delete(postID, model.GetMillis(), deleteByID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1279,8 +1279,8 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, a.Srv().Go(func() { a.deletePostFiles(post.Id) }) - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(postID, true) - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(postID, false) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, true) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, false) } a.Srv().Go(func() { a.deleteFlaggedPosts(post.Id) @@ -1292,14 +1292,14 @@ func (a *App) DeletePost(c request.CTX, postID, deleteByID string) (*model.Post, } func (a *App) deleteFlaggedPosts(postID string) { - if err := a.Srv().Store.Preference().DeleteCategoryAndName(model.PreferenceCategoryFlaggedPost, postID); err != nil { + if err := a.Srv().Store().Preference().DeleteCategoryAndName(model.PreferenceCategoryFlaggedPost, postID); err != nil { a.Log().Warn("Unable to delete flagged post preference when deleting post.", mlog.Err(err)) return } } func (a *App) deletePostFiles(postID string) { - if _, err := a.Srv().Store.FileInfo().DeleteForPost(postID); err != nil { + if _, err := a.Srv().Store().FileInfo().DeleteForPost(postID); err != nil { a.Log().Warn("Encountered error when deleting files for post", mlog.String("post_id", postID), mlog.Err(err)) } } @@ -1356,7 +1356,7 @@ func (a *App) searchPostsInTeam(teamID string, userID string, paramsList []*mode go func(params *model.SearchParams) { defer wg.Done() - postList, err := a.Srv().Store.Post().Search(teamID, userID, params) + postList, err := a.Srv().Store().Post().Search(teamID, userID, params) pchan <- store.StoreResult{Data: postList, NErr: err} }(params) } @@ -1412,7 +1412,7 @@ func (a *App) GetLastAccessiblePostTime() (int64, *model.AppError) { return 0, nil } - system, err := a.Srv().Store.System().GetByName(model.SystemLastAccessiblePostTime) + system, err := a.Srv().Store().System().GetByName(model.SystemLastAccessiblePostTime) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1449,7 +1449,7 @@ func (a *App) ComputeLastAccessiblePostTime() error { } // Update Cache - err = a.Srv().Store.System().SaveOrUpdate(&model.System{ + err = a.Srv().Store().System().SaveOrUpdate(&model.System{ Name: model.SystemLastAccessiblePostTime, Value: strconv.FormatInt(createdAt, 10), }) @@ -1526,7 +1526,7 @@ func (a *App) SearchPostsForUser(c *request.Context, terms string, userID string return model.MakePostSearchResults(model.NewPostList(), nil), nil } - postSearchResults, err := a.Srv().Store.Post().SearchPostsForUser(finalParamsList, userID, teamID, page, perPage) + postSearchResults, err := a.Srv().Store().Post().SearchPostsForUser(finalParamsList, userID, teamID, page, perPage) if err != nil { var appErr *model.AppError switch { @@ -1545,7 +1545,7 @@ func (a *App) SearchPostsForUser(c *request.Context, terms string, userID string } func (a *App) GetRecentSearchesForUser(userID string) ([]*model.SearchParams, *model.AppError) { - searchParams, err := a.Srv().Store.Post().GetRecentSearchesForUser(userID) + searchParams, err := a.Srv().Store().Post().GetRecentSearchesForUser(userID) if err != nil { return nil, model.NewAppError("GetRecentSearchesForUser", "app.recent_searches.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1557,7 +1557,7 @@ func (a *App) GetFileInfosForPostWithMigration(postID string, includeDeleted boo pchan := make(chan store.StoreResult, 1) go func() { - post, err := a.Srv().Store.Post().GetSingle(postID, includeDeleted) + post, err := a.Srv().Store().Post().GetSingle(postID, includeDeleted) pchan <- store.StoreResult{Data: post, NErr: err} close(pchan) }() @@ -1582,8 +1582,8 @@ func (a *App) GetFileInfosForPostWithMigration(postID string, includeDeleted boo post := result.Data.(*model.Post) if len(post.Filenames) > 0 { - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(postID, false) - a.Srv().Store.FileInfo().InvalidateFileInfosForPostCache(postID, true) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, false) + a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(postID, true) // The post has Filenames that need to be replaced with FileInfos infos = a.MigrateFilenamesToFileInfos(post) } @@ -1594,7 +1594,7 @@ func (a *App) GetFileInfosForPostWithMigration(postID string, includeDeleted boo // GetFileInfosForPost also returns firstInaccessibleFileTime based on cloud plan's limit. func (a *App) GetFileInfosForPost(postID string, fromMaster bool, includeDeleted bool) ([]*model.FileInfo, int64, *model.AppError) { - fileInfos, err := a.Srv().Store.FileInfo().GetForPost(postID, fromMaster, includeDeleted, true) + fileInfos, err := a.Srv().Store().FileInfo().GetForPost(postID, fromMaster, includeDeleted, true) if err != nil { return nil, 0, model.NewAppError("GetFileInfosForPost", "app.file_info.get_for_post.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1610,7 +1610,7 @@ func (a *App) GetFileInfosForPost(postID string, fromMaster bool, includeDeleted } func (a *App) getFileInfosForPostIgnoreCloudLimit(postID string, fromMaster bool, includeDeleted bool) ([]*model.FileInfo, *model.AppError) { - fileInfos, err := a.Srv().Store.FileInfo().GetForPost(postID, fromMaster, includeDeleted, true) + fileInfos, err := a.Srv().Store().FileInfo().GetForPost(postID, fromMaster, includeDeleted, true) if err != nil { return nil, model.NewAppError("getFileInfosForPostIgnoreCloudLimit", "app.file_info.get_for_post.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1661,17 +1661,8 @@ func (a *App) ImageProxyRemover() (f func(string) string) { } } -func (s *Server) MaxPostSize() int { - maxPostSize := s.Store.Post().GetMaxPostSize() - if maxPostSize == 0 { - return model.PostMessageMaxRunesV1 - } - - return maxPostSize -} - func (a *App) MaxPostSize() int { - return a.Srv().MaxPostSize() + return a.Srv().Platform().MaxPostSize() } // countThreadMentions returns the number of times the user is mentioned in a specified thread after the timestamp. @@ -1689,7 +1680,7 @@ func (a *App) countThreadMentions(c request.CTX, user *model.User, post *model.P true, // Assume channel mentions are always allowed for simplicity ) - posts, nErr := a.Srv().Store.Thread().GetPosts(post.Id, timestamp) + posts, nErr := a.Srv().Store().Thread().GetPosts(post.Id, timestamp) if nErr != nil { return 0, model.NewAppError("countMentionsFromPost", "app.channel.count_posts_since.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1743,7 +1734,7 @@ func (a *App) countMentionsFromPost(c request.CTX, user *model.User, post *model if channel.Type == model.ChannelTypeDirect { // In a DM channel, every post made by the other user is a mention - count, countRoot, nErr := a.Srv().Store.Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id)) + count, countRoot, nErr := a.Srv().Store().Channel().CountPostsAfter(post.ChannelId, post.CreateAt-1, channel.GetOtherUserIdForDM(user.Id)) if nErr != nil { return 0, 0, model.NewAppError("countMentionsFromPost", "app.channel.count_posts_since.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -1880,7 +1871,7 @@ func isPostMention(user *model.User, post *model.Post, keywords map[string][]str } func (a *App) GetThreadMembershipsForUser(userID, teamID string) ([]*model.ThreadMembership, error) { - return a.Srv().Store.Thread().GetMembershipsForUser(userID, teamID) + return a.Srv().Store().Thread().GetMembershipsForUser(userID, teamID) } func (a *App) GetPostIfAuthorized(c request.CTX, postID string, session *model.Session, includeDeleted bool) (*model.Post, *model.AppError) { @@ -1909,7 +1900,7 @@ func (a *App) GetPostIfAuthorized(c request.CTX, postID string, session *model.S // GetPostsByIds response bool value indicates, if the post is inaccessible due to cloud plan's limit. func (a *App) GetPostsByIds(postIDs []string) ([]*model.Post, int64, *model.AppError) { - posts, err := a.Srv().Store.Post().GetPostsByIds(postIDs) + posts, err := a.Srv().Store().Post().GetPostsByIds(postIDs) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1933,7 +1924,7 @@ func (a *App) GetTopThreadsForTeamSince(c request.CTX, teamID, userID string, op return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topThreads, err := a.Srv().Store.Thread().GetTopThreadsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topThreads, err := a.Srv().Store().Thread().GetTopThreadsForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.post.get_top_threads_for_team_since.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1949,7 +1940,7 @@ func (a *App) GetTopThreadsForUserSince(c request.CTX, teamID, userID string, op return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topThreads, err := a.Srv().Store.Thread().GetTopThreadsForUserSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topThreads, err := a.Srv().Store().Thread().GetTopThreadsForUserSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopChannelsForTeamSince", "app.post.get_top_threads_for_team_since.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1964,7 +1955,7 @@ func (a *App) GetTopDMsForUserSince(userID string, opts *model.InsightsOpts) (*m if !a.Config().FeatureFlags.InsightsEnabled { return nil, model.NewAppError("GetTopDMsForUserSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topDMs, err := a.Srv().Store.Post().GetTopDMsForUserSince(userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topDMs, err := a.Srv().Store().Post().GetTopDMsForUserSince(userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopDMsForUserSince", "app.post.get_top_dms_for_user_since.app_error", nil, err.Error(), http.StatusInternalServerError) } @@ -1978,12 +1969,12 @@ func (a *App) SetPostReminder(postID, userID string, targetTime int64) *model.Ap UserId: userID, TargetTime: targetTime, } - err := a.Srv().Store.Post().SetPostReminder(reminder) + err := a.Srv().Store().Post().SetPostReminder(reminder) if err != nil { return model.NewAppError("SetPostReminder", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } - metadata, err := a.Srv().Store.Post().GetPostReminderMetadata(postID) + metadata, err := a.Srv().Store().Post().GetPostReminderMetadata(postID) if err != nil { return model.NewAppError("SetPostReminder", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2036,7 +2027,7 @@ func (a *App) CheckPostReminders() { // Alternatively, if we delete those reminders _after_ it has been sent, // then in case of any temporary failure, they would get sent in the next batch. // MM-45595. - reminders, err := a.Srv().Store.Post().GetPostReminders(time.Now().UTC().Unix()) + reminders, err := a.Srv().Store().Post().GetPostReminders(time.Now().UTC().Unix()) if err != nil { mlog.Error("Failed to get post reminders", mlog.Err(err)) return @@ -2061,7 +2052,7 @@ func (a *App) CheckPostReminders() { } for _, postID := range postIDs { - metadata, err := a.Srv().Store.Post().GetPostReminderMetadata(postID) + metadata, err := a.Srv().Store().Post().GetPostReminderMetadata(postID) if err != nil { mlog.Error("Failed to get post reminder metadata", mlog.Err(err)) continue diff --git a/app/post_helpers_test.go b/app/post_helpers_test.go index 34b17e9e34..19f513ee15 100644 --- a/app/post_helpers_test.go +++ b/app/post_helpers_test.go @@ -194,7 +194,7 @@ func TestGetTimeSortedPostAccessibleBounds(t *testing.T) { func TestFilterInaccessiblePosts(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessiblePostTime, Value: "2", }) @@ -322,7 +322,7 @@ func TestFilterInaccessiblePosts(t *testing.T) { func TestGetFilteredAccessiblePosts(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessiblePostTime, Value: "2", }) @@ -363,7 +363,7 @@ func TestGetFilteredAccessiblePosts(t *testing.T) { func TestIsInaccessiblePost(t *testing.T) { th := Setup(t) th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - th.App.Srv().Store.System().Save(&model.System{ + th.App.Srv().Store().System().Save(&model.System{ Name: model.SystemLastAccessiblePostTime, Value: "2", }) diff --git a/app/post_metadata.go b/app/post_metadata.go index b863ac21f4..676faca564 100644 --- a/app/post_metadata.go +++ b/app/post_metadata.go @@ -17,9 +17,9 @@ import ( "github.com/dyatlov/go-opengraph/opengraph" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/shared/markdown" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/utils/imgutils" @@ -31,14 +31,8 @@ type linkMetadataCache struct { Permalink *model.Permalink } -const LinkCacheSize = 10000 -const LinkCacheDuration = 1 * time.Hour const MaxMetadataImageSize = MaxOpenGraphResponseSize -var linkCache = cache.NewLRU(cache.LRUOptions{ - Size: LinkCacheSize, -}) - func (s *Server) initPostMetadata() { // Dump any cached links if the proxy settings have changed so image URLs can be updated s.platform.AddConfigListener(func(before, after *model.Config) { @@ -46,7 +40,7 @@ func (s *Server) initPostMetadata() { (before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) || (before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) || (before.ImageProxySettings.RemoteImageProxyOptions != after.ImageProxySettings.RemoteImageProxyOptions) { - linkCache.Purge() + platform.PurgeLinkCache() } }) } @@ -642,7 +636,7 @@ func resolveMetadataURL(requestURL string, siteURL string) string { func getLinkMetadataFromCache(requestURL string, timestamp int64) (*opengraph.OpenGraph, *model.PostImage, *model.Permalink, bool) { var cached linkMetadataCache - err := linkCache.Get(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), &cached) + err := platform.LinkCache().Get(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), &cached) if err != nil { return nil, nil, nil, false } @@ -651,7 +645,7 @@ func getLinkMetadataFromCache(requestURL string, timestamp int64) (*opengraph.Op } func (a *App) getLinkMetadataFromDatabase(requestURL string, timestamp int64) (*opengraph.OpenGraph, *model.PostImage, bool) { - linkMetadata, err := a.Srv().Store.LinkMetadata().Get(requestURL, timestamp) + linkMetadata, err := a.Srv().Store().LinkMetadata().Get(requestURL, timestamp) if err != nil { return nil, nil, false } @@ -684,7 +678,7 @@ func (a *App) saveLinkMetadataToDatabase(requestURL string, timestamp int64, og metadata.Type = model.LinkMetadataTypeNone } - _, err := a.Srv().Store.LinkMetadata().Save(metadata) + _, err := a.Srv().Store().LinkMetadata().Save(metadata) if err != nil { mlog.Warn("Failed to write link metadata", mlog.String("request_url", requestURL), mlog.Err(err)) } @@ -697,7 +691,7 @@ func cacheLinkMetadata(requestURL string, timestamp int64, og *opengraph.OpenGra Permalink: permalink, } - linkCache.SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, LinkCacheDuration) + platform.LinkCache().SetWithExpiry(strconv.FormatInt(model.GenerateLinkMetadataHash(requestURL, timestamp), 16), metadata, platform.LinkCacheDuration) } func (a *App) parseLinkMetadata(requestURL string, body io.Reader, contentType string) (*opengraph.OpenGraph, *model.PostImage, error) { diff --git a/app/post_metadata_test.go b/app/post_metadata_test.go index 396aaa350a..b1bf0b24f7 100644 --- a/app/post_metadata_test.go +++ b/app/post_metadata_test.go @@ -23,6 +23,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/httpservice" "github.com/mattermost/mattermost-server/v6/services/imageproxy" @@ -1900,7 +1901,7 @@ func TestGetLinkMetadata(t *testing.T) { *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "127.0.0.1" }) - linkCache.Purge() + platform.PurgeLinkCache() return th } @@ -2048,7 +2049,7 @@ func TestGetLinkMetadata(t *testing.T) { th.App.saveLinkMetadataToDatabase(requestURL, timestamp, &opengraph.OpenGraph{Title: title}, nil) t.Run("should use database if saved entry exists", func(t *testing.T) { - linkCache.Purge() + platform.PurgeLinkCache() _, _, _, ok := getLinkMetadataFromCache(requestURL, timestamp) require.False(t, ok, "data should not exist in in-memory cache") @@ -2065,7 +2066,7 @@ func TestGetLinkMetadata(t *testing.T) { }) t.Run("should use database if saved entry exists near time", func(t *testing.T) { - linkCache.Purge() + platform.PurgeLinkCache() _, _, _, ok := getLinkMetadataFromCache(requestURL, timestamp) require.False(t, ok, "data should not exist in in-memory cache") @@ -2082,7 +2083,7 @@ func TestGetLinkMetadata(t *testing.T) { }) t.Run("should not use database if URL is different", func(t *testing.T) { - linkCache.Purge() + platform.PurgeLinkCache() differentURL := requestURL + "/other" @@ -2100,7 +2101,7 @@ func TestGetLinkMetadata(t *testing.T) { }) t.Run("should not use database if timestamp is different", func(t *testing.T) { - linkCache.Purge() + platform.PurgeLinkCache() differentTimestamp := timestamp + 60*60*1000 @@ -2308,7 +2309,7 @@ func TestGetLinkMetadata(t *testing.T) { _, _, _, ok = getLinkMetadataFromCache(requestURL, timestamp) require.True(t, ok, "data should now exist in in-memory cache") - linkCache.Purge() + platform.PurgeLinkCache() _, _, _, ok = getLinkMetadataFromCache(requestURL, timestamp) require.False(t, ok, "data should no longer exist in in-memory cache") diff --git a/app/post_test.go b/app/post_test.go index c51eabb5db..3315ada6f9 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -16,6 +16,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v6/app/platform" eMocks "github.com/mattermost/mattermost-server/v6/einterfaces/mocks" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/plugin/plugintest/mock" @@ -201,13 +202,13 @@ func TestAttachFilesToPost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - info1, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + info1, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) require.NoError(t, err) - info2, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + info2, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) @@ -228,14 +229,14 @@ func TestAttachFilesToPost(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - info1, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + info1, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", PostId: model.NewId(), }) require.NoError(t, err) - info2, err := th.App.Srv().Store.FileInfo().Save(&model.FileInfo{ + info2, err := th.App.Srv().Store().FileInfo().Save(&model.FileInfo{ CreatorId: th.BasicUser.Id, Path: "path.txt", }) @@ -453,7 +454,7 @@ func TestImageProxy(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockUserStore := storemocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := storemocks.PostStore{} @@ -608,7 +609,9 @@ func TestMaxPostSize(t *testing.T) { app := App{ ch: &Channels{ srv: &Server{ - Store: mockStore, + platform: &platform.PlatformService{ + Store: mockStore, + }, }, }, } @@ -632,7 +635,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) { info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data) require.Nil(t, err) defer func() { - th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id) + th.App.Srv().Store().FileInfo().PermanentDelete(info1.Id) th.App.RemoveFile(info1.Path) }() @@ -1041,14 +1044,14 @@ func TestCreatePostAsUser(t *testing.T) { UserId: th.BasicUser.Id, } - channelMemberBefore, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberBefore, err := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, err) time.Sleep(1 * time.Millisecond) _, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) - channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberAfter, err := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, err) require.Greater(t, channelMemberAfter.LastViewedAt, channelMemberBefore.LastViewedAt) @@ -1065,14 +1068,14 @@ func TestCreatePostAsUser(t *testing.T) { } post.AddProp("from_webhook", "true") - channelMemberBefore, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberBefore, err := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, err) time.Sleep(1 * time.Millisecond) _, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) - channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberAfter, err := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, err) require.Equal(t, channelMemberAfter.LastViewedAt, channelMemberBefore.LastViewedAt) @@ -1096,14 +1099,14 @@ func TestCreatePostAsUser(t *testing.T) { UserId: bot.UserId, } - channelMemberBefore, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberBefore, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) time.Sleep(1 * time.Millisecond) _, appErr = th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) - channelMemberAfter, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberAfter, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) require.Equal(t, channelMemberAfter.LastViewedAt, channelMemberBefore.LastViewedAt) @@ -1170,7 +1173,7 @@ func TestCreatePostAsUser(t *testing.T) { rootPost, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) - channelMemberBefore, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberBefore, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) time.Sleep(1 * time.Millisecond) @@ -1183,7 +1186,7 @@ func TestCreatePostAsUser(t *testing.T) { _, appErr = th.App.CreatePostAsUser(th.Context, replyPost, "", true) require.Nil(t, appErr) - channelMemberAfter, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberAfter, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) require.NotEqual(t, channelMemberAfter.LastViewedAt, channelMemberBefore.LastViewedAt) @@ -1206,7 +1209,7 @@ func TestCreatePostAsUser(t *testing.T) { rootPost, appErr := th.App.CreatePostAsUser(th.Context, post, "", true) require.Nil(t, appErr) - channelMemberBefore, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberBefore, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) time.Sleep(1 * time.Millisecond) @@ -1219,7 +1222,7 @@ func TestCreatePostAsUser(t *testing.T) { _, appErr = th.App.CreatePostAsUser(th.Context, replyPost, "", true) require.Nil(t, appErr) - channelMemberAfter, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) + channelMemberAfter, nErr := th.App.Srv().Store().Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id) require.NoError(t, nErr) require.Equal(t, channelMemberAfter.LastViewedAt, channelMemberBefore.LastViewedAt) @@ -1469,9 +1472,9 @@ func TestSearchPostsForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchPostsForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierMessages) @@ -1496,9 +1499,9 @@ func TestSearchPostsForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchPostsForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierMessages) @@ -1520,9 +1523,9 @@ func TestSearchPostsForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchPostsForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierMessages) @@ -1552,9 +1555,9 @@ func TestSearchPostsForUser(t *testing.T) { es.On("Start").Return(nil).Maybe() es.On("IsActive").Return(true) es.On("IsSearchEnabled").Return(true) - th.App.Srv().SearchEngine.ElasticsearchEngine = es + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = es defer func() { - th.App.Srv().SearchEngine.ElasticsearchEngine = nil + th.App.Srv().Platform().SearchEngine.ElasticsearchEngine = nil }() results, err := th.App.SearchPostsForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage, model.ModifierMessages) @@ -2445,7 +2448,7 @@ func TestCollapsedThreadFetch(t *testing.T) { Message: fmt.Sprintf("@%s", user2.Username), }, channel, false, true) require.Nil(t, err) - thread, nErr := th.App.Srv().Store.Thread().Get(postRoot.Id) + thread, nErr := th.App.Srv().Store().Thread().Get(postRoot.Id) require.NoError(t, nErr) require.Len(t, thread.Participants, 1) th.App.MarkChannelAsUnreadFromPost(th.Context, postRoot.Id, user1.Id, true) @@ -2488,7 +2491,7 @@ func TestCollapsedThreadFetch(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - th.Server.Store.Post().PermanentDeleteByUser(user1.Id) + th.Server.Store().Post().PermanentDeleteByUser(user1.Id) }() require.NotPanics(t, func() { @@ -2535,7 +2538,7 @@ func TestCollapsedThreadFetch(t *testing.T) { Message: "reply", }, channel, false, true) require.Nil(t, err) - thread, nErr := th.App.Srv().Store.Thread().Get(postRoot.Id) + thread, nErr := th.App.Srv().Store().Thread().Get(postRoot.Id) require.NoError(t, nErr) require.Len(t, thread.Participants, 1) @@ -2622,9 +2625,9 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { defer th.TearDown() remoteClusterService := NewMockSharedChannelService(nil) - th.App.ch.srv.sharedChannelService = remoteClusterService + th.Server.SetSharedChannelSyncService(remoteClusterService) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) user := th.BasicUser @@ -2637,7 +2640,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { }, channel, false, true) require.Nil(t, err, "Creating a post should not error") - assert.Len(t, remoteClusterService.channelNotifications, 1) + require.Len(t, remoteClusterService.channelNotifications, 1) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[0]) }) @@ -2646,9 +2649,9 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { defer th.TearDown() remoteClusterService := NewMockSharedChannelService(nil) - th.App.ch.srv.sharedChannelService = remoteClusterService + th.Server.SetSharedChannelSyncService(remoteClusterService) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) user := th.BasicUser @@ -2664,7 +2667,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { _, err = th.App.UpdatePost(th.Context, post, true) require.Nil(t, err, "Updating a post should not error") - assert.Len(t, remoteClusterService.channelNotifications, 2) + require.Len(t, remoteClusterService.channelNotifications, 2) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[0]) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[1]) }) @@ -2674,9 +2677,9 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { defer th.TearDown() remoteClusterService := NewMockSharedChannelService(nil) - th.App.ch.srv.sharedChannelService = remoteClusterService + th.Server.SetSharedChannelSyncService(remoteClusterService) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) user := th.BasicUser @@ -2693,7 +2696,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) { require.Nil(t, err, "Deleting a post should not error") // one creation and two deletes - assert.Len(t, remoteClusterService.channelNotifications, 3) + require.Len(t, remoteClusterService.channelNotifications, 3) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[0]) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[1]) assert.Equal(t, channel.Id, remoteClusterService.channelNotifications[2]) @@ -2726,7 +2729,7 @@ func TestAutofollowOnPostingAfterUnfollow(t *testing.T) { require.Nil(t, err) // unfollow thread - m, nErr := th.App.Srv().Store.Thread().MaintainMembership(user.Id, p1.Id, store.ThreadMembershipOpts{ + m, nErr := th.App.Srv().Store().Thread().MaintainMembership(user.Id, p1.Id, store.ThreadMembershipOpts{ Following: false, UpdateFollowing: true, }) @@ -2793,7 +2796,7 @@ func TestShouldNotRefollowOnOthersReply(t *testing.T) { require.Nil(t, err) // User2 unfollows thread - m, nErr := th.App.Srv().Store.Thread().MaintainMembership(user2.Id, p1.Id, store.ThreadMembershipOpts{ + m, nErr := th.App.Srv().Store().Thread().MaintainMembership(user2.Id, p1.Id, store.ThreadMembershipOpts{ Following: false, UpdateFollowing: true, }) @@ -2830,7 +2833,7 @@ func TestGetLastAccessiblePostTime(t *testing.T) { th.App.Srv().SetLicense(model.NewTestLicense("cloud")) - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockSystemStore := storemocks.SystemStore{} mockStore.On("System").Return(&mockSystemStore) @@ -2868,7 +2871,7 @@ func TestComputeLastAccessiblePostTime(t *testing.T) { }, }, nil) - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockPostStore := storemocks.PostStore{} mockPostStore.On("GetNthRecentPostTime", mock.Anything).Return(int64(1), nil) mockSystemStore := storemocks.SystemStore{} @@ -3052,7 +3055,7 @@ func TestGetTopThreadsForUserSince(t *testing.T) { _, appErr = th.App.DeletePost(th.Context, replyPostUser2InPrivate.Id, th.BasicUser2.Id) require.Nil(t, appErr) // unfollow thread - _, err := th.App.Srv().Store.Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ + _, err := th.App.Srv().Store().Thread().MaintainMembership(th.BasicUser2.Id, rootPostPrivateChannel.Id, store.ThreadMembershipOpts{ Following: false, UpdateFollowing: true, }) diff --git a/app/preference.go b/app/preference.go index 4cf8903740..f995eb9391 100644 --- a/app/preference.go +++ b/app/preference.go @@ -33,7 +33,7 @@ func (w *preferencesServiceWrapper) DeletePreferencesForUser(userID string, pref } func (a *App) GetPreferencesForUser(userID string) (model.Preferences, *model.AppError) { - preferences, err := a.Srv().Store.Preference().GetAll(userID) + preferences, err := a.Srv().Store().Preference().GetAll(userID) if err != nil { return nil, model.NewAppError("GetPreferencesForUser", "app.preference.get_all.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -41,7 +41,7 @@ func (a *App) GetPreferencesForUser(userID string) (model.Preferences, *model.Ap } func (a *App) GetPreferenceByCategoryForUser(userID string, category string) (model.Preferences, *model.AppError) { - preferences, err := a.Srv().Store.Preference().GetCategory(userID, category) + preferences, err := a.Srv().Store().Preference().GetCategory(userID, category) if err != nil { return nil, model.NewAppError("GetPreferenceByCategoryForUser", "app.preference.get_category.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -53,7 +53,7 @@ func (a *App) GetPreferenceByCategoryForUser(userID string, category string) (mo } func (a *App) GetPreferenceByCategoryAndNameForUser(userID string, category string, preferenceName string) (*model.Preference, *model.AppError) { - res, err := a.Srv().Store.Preference().Get(userID, category, preferenceName) + res, err := a.Srv().Store().Preference().Get(userID, category, preferenceName) if err != nil { return nil, model.NewAppError("GetPreferenceByCategoryAndNameForUser", "app.preference.get.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -68,7 +68,7 @@ func (a *App) UpdatePreferences(userID string, preferences model.Preferences) *m } } - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -78,7 +78,7 @@ func (a *App) UpdatePreferences(userID string, preferences model.Preferences) *m } } - if err := a.Srv().Store.Channel().UpdateSidebarChannelsByPreferences(preferences); err != nil { + if err := a.Srv().Store().Channel().UpdateSidebarChannelsByPreferences(preferences); err != nil { return model.NewAppError("UpdatePreferences", "api.preference.update_preferences.update_sidebar.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -107,12 +107,12 @@ func (a *App) DeletePreferences(userID string, preferences model.Preferences) *m } for _, preference := range preferences { - if err := a.Srv().Store.Preference().Delete(userID, preference.Category, preference.Name); err != nil { + if err := a.Srv().Store().Preference().Delete(userID, preference.Category, preference.Name); err != nil { return model.NewAppError("DeletePreferences", "app.preference.delete.app_error", nil, "", http.StatusBadRequest).Wrap(err) } } - if err := a.Srv().Store.Channel().DeleteSidebarChannelsByPreferences(preferences); err != nil { + if err := a.Srv().Store().Channel().DeleteSidebarChannelsByPreferences(preferences); err != nil { return model.NewAppError("DeletePreferences", "api.preference.delete_preferences.update_sidebar.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/product_notices.go b/app/product_notices.go index 0b387897ac..673f78e4f6 100644 --- a/app/product_notices.go +++ b/app/product_notices.go @@ -244,7 +244,7 @@ func (a *App) GetProductNotices(c *request.Context, userID, teamID string, clien return []model.NoticeMessage{}, nil } - views, err := a.Srv().Store.ProductNotices().GetViews(userID) + views, err := a.Srv().Store().ProductNotices().GetViews(userID) if err != nil { return nil, model.NewAppError("GetProductNotices", "api.system.update_viewed_notices.failed", nil, "", http.StatusBadRequest).Wrap(err) } @@ -254,7 +254,7 @@ func (a *App) GetProductNotices(c *request.Context, userID, teamID string, clien dbName := *a.Config().SqlSettings.DriverName var searchEngineName, searchEngineVersion string - if engine := a.Srv().SearchEngine; engine != nil && engine.ElasticsearchEngine != nil { + if engine := a.Srv().Platform().SearchEngine; engine != nil && engine.ElasticsearchEngine != nil { searchEngineName = engine.ElasticsearchEngine.GetName() searchEngineVersion = engine.ElasticsearchEngine.GetFullVersion() } @@ -285,7 +285,7 @@ func (a *App) GetProductNotices(c *request.Context, userID, teamID string, clien } result, err := noticeMatchesConditions( a.Config(), - a.Srv().Store.Preference(), + a.Srv().Store().Preference(), userID, client, clientVersion, @@ -319,7 +319,7 @@ func (a *App) GetProductNotices(c *request.Context, userID, teamID string, clien // UpdateViewedProductNotices is called from the frontend to mark a set of notices as 'viewed' by user func (a *App) UpdateViewedProductNotices(userID string, noticeIds []string) *model.AppError { - if err := a.Srv().Store.ProductNotices().View(userID, noticeIds); err != nil { + if err := a.Srv().Store().ProductNotices().View(userID, noticeIds); err != nil { return model.NewAppError("UpdateViewedProductNotices", "api.system.update_viewed_notices.failed", nil, "", http.StatusBadRequest).Wrap(err) } return nil @@ -332,7 +332,7 @@ func (a *App) UpdateViewedProductNoticesForNewUser(userID string) { for _, notice := range a.ch.cachedNotices { noticeIds = append(noticeIds, notice.ID) } - if err := a.Srv().Store.ProductNotices().View(userID, noticeIds); err != nil { + if err := a.Srv().Store().ProductNotices().View(userID, noticeIds); err != nil { mlog.Error("Cannot update product notices viewed state for user", mlog.String("userId", userID)) } } @@ -343,17 +343,17 @@ func (a *App) UpdateProductNotices() *model.AppError { skip := *a.Config().AnnouncementSettings.NoticesSkipCache mlog.Debug("Will fetch notices from", mlog.String("url", url), mlog.Bool("skip_cache", skip)) var err error - a.ch.cachedPostCount, err = a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{}) + a.ch.cachedPostCount, err = a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{}) if err != nil { mlog.Warn("Failed to fetch post count", mlog.String("error", err.Error())) } - a.ch.cachedUserCount, err = a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) + a.ch.cachedUserCount, err = a.Srv().Store().User().Count(model.UserCountOptions{IncludeDeleted: true}) if err != nil { mlog.Warn("Failed to fetch user count", mlog.String("error", err.Error())) } - a.ch.cachedDBMSVersion, err = a.Srv().Store.GetDbVersion(false) + a.ch.cachedDBMSVersion, err = a.Srv().Store().GetDbVersion(false) if err != nil { mlog.Warn("Failed to get DBMS version", mlog.String("error", err.Error())) } @@ -369,7 +369,7 @@ func (a *App) UpdateProductNotices() *model.AppError { return model.NewAppError("UpdateProductNotices", "api.system.update_notices.parse_failed", nil, "", http.StatusBadRequest).Wrap(err) } - if err := a.Srv().Store.ProductNotices().ClearOldNotices(a.ch.cachedNotices); err != nil { + if err := a.Srv().Store().ProductNotices().ClearOldNotices(a.ch.cachedNotices); err != nil { return model.NewAppError("UpdateProductNotices", "api.system.update_notices.clear_failed", nil, "", http.StatusBadRequest).Wrap(err) } return nil diff --git a/app/product_notices_test.go b/app/product_notices_test.go index d6826b2f92..fa9774b7b7 100644 --- a/app/product_notices_test.go +++ b/app/product_notices_test.go @@ -20,7 +20,7 @@ import ( func TestNoticeValidation(t *testing.T) { th := SetupWithStoreMock(t) - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockRoleStore := mocks.RoleStore{} mockSystemStore := mocks.SystemStore{} mockUserStore := mocks.UserStore{} @@ -643,7 +643,7 @@ func TestNoticeValidation(t *testing.T) { } if ok, err := noticeMatchesConditions( th.App.Config(), - th.App.Srv().Store.Preference(), + th.App.Srv().Store().Preference(), "test", tt.args.client, clientVersion, @@ -733,7 +733,7 @@ func TestNoticeFetch(t *testing.T) { require.Len(t, messages, 0) // validate views table - views, err := th.App.Srv().Store.ProductNotices().GetViews(th.BasicUser.Id) + views, err := th.App.Srv().Store().ProductNotices().GetViews(th.BasicUser.Id) require.NoError(t, err) require.Len(t, views, 1) @@ -752,7 +752,7 @@ func TestNoticeFetch(t *testing.T) { require.Len(t, messages, 0) // even though UpdateViewedProductNotices was called previously, the table should be empty, since there's cleanup done during UpdateProductNotices - views, err = th.App.Srv().Store.ProductNotices().GetViews(th.BasicUser.Id) + views, err = th.App.Srv().Store().ProductNotices().GetViews(th.BasicUser.Id) require.NoError(t, err) require.Len(t, views, 0) } diff --git a/app/reaction.go b/app/reaction.go index b48c33536b..0163c98519 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -29,7 +29,7 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden) } - reaction, nErr := a.Srv().Store.Reaction().Save(reaction) + reaction, nErr := a.Srv().Store().Reaction().Save(reaction) if nErr != nil { var appErr *model.AppError switch { @@ -61,7 +61,7 @@ func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) } func (a *App) GetReactionsForPost(postID string) ([]*model.Reaction, *model.AppError) { - reactions, err := a.Srv().Store.Reaction().GetForPost(postID, true) + reactions, err := a.Srv().Store().Reaction().GetForPost(postID, true) if err != nil { return nil, model.NewAppError("GetReactionsForPost", "app.reaction.get_for_post.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -71,7 +71,7 @@ func (a *App) GetReactionsForPost(postID string) ([]*model.Reaction, *model.AppE func (a *App) GetBulkReactionsForPosts(postIDs []string) (map[string][]*model.Reaction, *model.AppError) { reactions := make(map[string][]*model.Reaction) - allReactions, err := a.Srv().Store.Reaction().BulkGetForPosts(postIDs) + allReactions, err := a.Srv().Store().Reaction().BulkGetForPosts(postIDs) if err != nil { return nil, model.NewAppError("GetBulkReactionsForPosts", "app.reaction.bulk_get_for_post_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -101,7 +101,7 @@ func (a *App) GetTopReactionsForTeamSince(teamID string, userID string, opts *mo return nil, model.NewAppError("GetTopReactionsForTeamSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topReactionList, err := a.Srv().Store.Reaction().GetTopForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topReactionList, err := a.Srv().Store().Reaction().GetTopForTeamSince(teamID, userID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopReactionsForTeamSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -113,7 +113,7 @@ func (a *App) GetTopReactionsForUserSince(userID string, teamID string, opts *mo return nil, model.NewAppError("GetTopReactionsForUserSince", "api.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - topReactionList, err := a.Srv().Store.Reaction().GetTopForUserSince(userID, teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + topReactionList, err := a.Srv().Store().Reaction().GetTopForUserSince(userID, teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, model.NewAppError("GetTopReactionsForUserSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -135,7 +135,7 @@ func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction return model.NewAppError("DeleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden) } - if _, err := a.Srv().Store.Reaction().Delete(reaction); err != nil { + if _, err := a.Srv().Store().Reaction().Delete(reaction); err != nil { return model.NewAppError("DeleteReactionForPost", "app.reaction.delete_all_with_emoji_name.get_reactions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/reaction_test.go b/app/reaction_test.go index 3e60208b84..d9670e4eeb 100644 --- a/app/reaction_test.go +++ b/app/reaction_test.go @@ -19,9 +19,9 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { th := Setup(t).InitBasic() sharedChannelService := NewMockSharedChannelService(nil) - th.App.ch.srv.sharedChannelService = sharedChannelService + th.Server.SetSharedChannelSyncService(sharedChannelService) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) user := th.BasicUser @@ -54,9 +54,9 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) { th := Setup(t).InitBasic() sharedChannelService := NewMockSharedChannelService(nil) - th.App.ch.srv.sharedChannelService = sharedChannelService + th.Server.SetSharedChannelSyncService(sharedChannelService) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) user := th.BasicUser @@ -217,7 +217,7 @@ func TestGetTopReactionsForTeamSince(t *testing.T) { } for _, userReaction := range userReactions { - _, err := th.App.Srv().Store.Reaction().Save(userReaction) + _, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) } @@ -388,7 +388,7 @@ func TestGetTopReactionsForUserSince(t *testing.T) { } for _, userReaction := range userReactions { - _, err := th.App.Srv().Store.Reaction().Save(userReaction) + _, err := th.App.Srv().Store().Reaction().Save(userReaction) require.NoError(t, err) } diff --git a/app/remote_cluster.go b/app/remote_cluster.go index c80388b1b7..5466ed1dfd 100644 --- a/app/remote_cluster.go +++ b/app/remote_cluster.go @@ -15,7 +15,7 @@ import ( ) func (a *App) AddRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) { - rc, err := a.Srv().Store.RemoteCluster().Save(rc) + rc, err := a.Srv().Store().RemoteCluster().Save(rc) if err != nil { if sqlstore.IsUniqueConstraintError(errors.Cause(err), []string{sqlstore.RemoteClusterSiteURLUniqueIndex}) { return nil, model.NewAppError("AddRemoteCluster", "api.remote_cluster.save_not_unique.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -27,7 +27,7 @@ func (a *App) AddRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, * } func (a *App) UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError) { - rc, err := a.Srv().Store.RemoteCluster().Update(rc) + rc, err := a.Srv().Store().RemoteCluster().Update(rc) if err != nil { if sqlstore.IsUniqueConstraintError(errors.Cause(err), []string{sqlstore.RemoteClusterSiteURLUniqueIndex}) { return nil, model.NewAppError("UpdateRemoteCluster", "api.remote_cluster.update_not_unique.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -39,7 +39,7 @@ func (a *App) UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster } func (a *App) DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError) { - deleted, err := a.Srv().Store.RemoteCluster().Delete(remoteClusterId) + deleted, err := a.Srv().Store().RemoteCluster().Delete(remoteClusterId) if err != nil { return false, model.NewAppError("DeleteRemoteCluster", "api.remote_cluster.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -47,7 +47,7 @@ func (a *App) DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError } func (a *App) GetRemoteCluster(remoteClusterId string) (*model.RemoteCluster, *model.AppError) { - rc, err := a.Srv().Store.RemoteCluster().Get(remoteClusterId) + rc, err := a.Srv().Store().RemoteCluster().Get(remoteClusterId) if err != nil { return nil, model.NewAppError("GetRemoteCluster", "api.remote_cluster.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -55,7 +55,7 @@ func (a *App) GetRemoteCluster(remoteClusterId string) (*model.RemoteCluster, *m } func (a *App) GetAllRemoteClusters(filter model.RemoteClusterQueryFilter) ([]*model.RemoteCluster, *model.AppError) { - list, err := a.Srv().Store.RemoteCluster().GetAll(filter) + list, err := a.Srv().Store().RemoteCluster().GetAll(filter) if err != nil { return nil, model.NewAppError("GetAllRemoteClusters", "api.remote_cluster.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -63,7 +63,7 @@ func (a *App) GetAllRemoteClusters(filter model.RemoteClusterQueryFilter) ([]*mo } func (a *App) UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError) { - rc, err := a.Srv().Store.RemoteCluster().UpdateTopics(remoteClusterId, topics) + rc, err := a.Srv().Store().RemoteCluster().UpdateTopics(remoteClusterId, topics) if err != nil { return nil, model.NewAppError("UpdateRemoteClusterTopics", "api.remote_cluster.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -71,7 +71,7 @@ func (a *App) UpdateRemoteClusterTopics(remoteClusterId string, topics string) ( } func (a *App) SetRemoteClusterLastPingAt(remoteClusterId string) *model.AppError { - err := a.Srv().Store.RemoteCluster().SetLastPingAt(remoteClusterId) + err := a.Srv().Store().RemoteCluster().SetLastPingAt(remoteClusterId) if err != nil { return model.NewAppError("SetRemoteClusterLastPingAt", "api.remote_cluster.save.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/role.go b/app/role.go index 156ef32a49..6fd4863e16 100644 --- a/app/role.go +++ b/app/role.go @@ -17,7 +17,7 @@ import ( ) func (a *App) GetRole(id string) (*model.Role, *model.AppError) { - role, err := a.Srv().Store.Role().Get(id) + role, err := a.Srv().Store().Role().Get(id) if err != nil { var nfErr *store.ErrNotFound switch { @@ -37,7 +37,7 @@ func (a *App) GetRole(id string) (*model.Role, *model.AppError) { } func (a *App) GetAllRoles() ([]*model.Role, *model.AppError) { - roles, err := a.Srv().Store.Role().GetAll() + roles, err := a.Srv().Store().Role().GetAll() if err != nil { return nil, model.NewAppError("GetAllRoles", "app.role.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -51,7 +51,7 @@ func (a *App) GetAllRoles() ([]*model.Role, *model.AppError) { } func (s *Server) GetRoleByName(ctx context.Context, name string) (*model.Role, *model.AppError) { - role, nErr := s.Store.Role().GetByName(ctx, name) + role, nErr := s.Store().Role().GetByName(ctx, name) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -75,7 +75,7 @@ func (a *App) GetRoleByName(ctx context.Context, name string) (*model.Role, *mod } func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) { - roles, nErr := a.Srv().Store.Role().GetByNames(names) + roles, nErr := a.Srv().Store().Role().GetByNames(names) if nErr != nil { return nil, model.NewAppError("GetRolesByNames", "app.role.get_by_names.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -103,7 +103,7 @@ func (s *Server) mergeChannelHigherScopedPermissions(roles []*model.Role) *model return nil } - higherScopedPermissionsMap, err := s.Store.Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery) + higherScopedPermissionsMap, err := s.Store().Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery) if err != nil { return model.NewAppError("mergeChannelHigherScopedPermissions", "app.role.get_by_names.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -153,7 +153,7 @@ func (a *App) CreateRole(role *model.Role) (*model.Role, *model.AppError) { role.SchemeManaged = false var err error - role, err = a.Srv().Store.Role().Save(role) + role, err = a.Srv().Store().Role().Save(role) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -168,7 +168,7 @@ func (a *App) CreateRole(role *model.Role) (*model.Role, *model.AppError) { } func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) { - savedRole, err := a.Srv().Store.Role().Save(role) + savedRole, err := a.Srv().Store().Role().Save(role) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -195,7 +195,7 @@ func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) { if utils.StringInSlice(savedRole.Name, builtInChannelRoles) { roleRetrievalFunc = func() ([]*model.Role, *model.AppError) { - roles, nErr := a.Srv().Store.Role().AllChannelSchemeRoles() + roles, nErr := a.Srv().Store().Role().AllChannelSchemeRoles() if nErr != nil { return nil, model.NewAppError("UpdateRole", "app.role.get.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -204,7 +204,7 @@ func (a *App) UpdateRole(role *model.Role) (*model.Role, *model.AppError) { } } else { roleRetrievalFunc = func() ([]*model.Role, *model.AppError) { - roles, nErr := a.Srv().Store.Role().ChannelRolesUnderTeamRole(savedRole.Name) + roles, nErr := a.Srv().Store().Role().ChannelRolesUnderTeamRole(savedRole.Name) if nErr != nil { return nil, model.NewAppError("UpdateRole", "app.role.get.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } diff --git a/app/saml.go b/app/saml.go index 1d90d09030..7a995651c9 100644 --- a/app/saml.go +++ b/app/saml.go @@ -288,7 +288,7 @@ func (a *App) ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.not_available.app_error", nil, "", http.StatusNotImplemented) return } - numAffected, err := a.Srv().Store.User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun) + numAffected, err := a.Srv().Store().User().ResetAuthDataToEmailForUsers(model.UserAuthServiceSaml, userIDs, includeDeleted, dryRun) if err != nil { appErr = model.NewAppError("ResetAuthDataToEmail", "api.admin.saml.failure_reset_authdata_to_email.app_error", nil, "", http.StatusInternalServerError).Wrap(err) return diff --git a/app/scheme.go b/app/scheme.go index 8a9b5b031f..e8d0e293ec 100644 --- a/app/scheme.go +++ b/app/scheme.go @@ -16,7 +16,7 @@ func (a *App) GetScheme(id string) (*model.Scheme, *model.AppError) { return nil, appErr } - scheme, err := a.Srv().Store.Scheme().Get(id) + scheme, err := a.Srv().Store().Scheme().Get(id) if err != nil { var nfErr *store.ErrNotFound switch { @@ -34,7 +34,7 @@ func (a *App) GetSchemeByName(name string) (*model.Scheme, *model.AppError) { return nil, err } - scheme, err := a.Srv().Store.Scheme().GetByName(name) + scheme, err := a.Srv().Store().Scheme().GetByName(name) if err != nil { var nfErr *store.ErrNotFound switch { @@ -60,7 +60,7 @@ func (s *Server) GetSchemes(scope string, offset int, limit int) ([]*model.Schem return nil, err } - scheme, err := s.Store.Scheme().GetAllPage(scope, offset, limit) + scheme, err := s.Store().Scheme().GetAllPage(scope, offset, limit) if err != nil { return nil, model.NewAppError("GetSchemes", "app.scheme.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -91,7 +91,7 @@ func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError scheme.UpdateAt = 0 scheme.DeleteAt = 0 - scheme, err := a.Srv().Store.Scheme().Save(scheme) + scheme, err := a.Srv().Store().Scheme().Save(scheme) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -126,7 +126,7 @@ func (a *App) UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError return nil, err } - scheme, err := a.Srv().Store.Scheme().Save(scheme) + scheme, err := a.Srv().Store().Scheme().Save(scheme) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -147,7 +147,7 @@ func (a *App) DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) { return nil, err } - scheme, err := a.Srv().Store.Scheme().Delete(schemeId) + scheme, err := a.Srv().Store().Scheme().Delete(schemeId) if err != nil { var nfErr *store.ErrNotFound switch { @@ -173,7 +173,7 @@ func (a *App) GetTeamsForScheme(scheme *model.Scheme, offset int, limit int) ([] return nil, err } - teams, err := a.Srv().Store.Team().GetTeamsByScheme(scheme.Id, offset, limit) + teams, err := a.Srv().Store().Team().GetTeamsByScheme(scheme.Id, offset, limit) if err != nil { return nil, model.NewAppError("GetTeamsForScheme", "app.team.get_by_scheme.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -193,7 +193,7 @@ func (a *App) GetChannelsForScheme(scheme *model.Scheme, offset int, limit int) return nil, err } - channelList, nErr := a.Srv().Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit) + channelList, nErr := a.Srv().Store().Channel().GetChannelsByScheme(scheme.Id, offset, limit) if nErr != nil { return nil, model.NewAppError("GetChannelsForScheme", "app.channel.get_by_scheme.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -206,7 +206,7 @@ func (s *Server) IsPhase2MigrationCompleted() *model.AppError { return nil } - if _, err := s.Store.System().GetByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { + if _, err := s.Store().System().GetByName(model.MigrationKeyAdvancedPermissionsPhase2); err != nil { return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, "", http.StatusNotImplemented).Wrap(err) } @@ -222,7 +222,7 @@ func (a *App) IsPhase2MigrationCompleted() *model.AppError { func (a *App) SchemesIterator(scope string, batchSize int) func() []*model.Scheme { offset := 0 return func() []*model.Scheme { - schemes, err := a.Srv().Store.Scheme().GetAllPage(scope, offset, batchSize) + schemes, err := a.Srv().Store().Scheme().GetAllPage(scope, offset, batchSize) if err != nil { return []*model.Scheme{} } diff --git a/app/searchengine.go b/app/searchengine.go index b8c107c5e6..69becd6e47 100644 --- a/app/searchengine.go +++ b/app/searchengine.go @@ -32,7 +32,7 @@ func (a *App) TestElasticsearch(cfg *model.Config) *model.AppError { } func (a *App) SetSearchEngine(se *searchengine.Broker) { - a.ch.srv.SearchEngine = se + a.ch.srv.platform.SearchEngine = se } func (a *App) PurgeElasticsearchIndexes() *model.AppError { diff --git a/app/security_update_check.go b/app/security_update_check.go index ecbf2f03d0..b20d9268e9 100644 --- a/app/security_update_check.go +++ b/app/security_update_check.go @@ -37,7 +37,7 @@ func (s *Server) DoSecurityUpdateCheck() { return } - props, err := s.Store.System().Get() + props, err := s.Store().System().Get() if err != nil { return } @@ -64,20 +64,20 @@ func (s *Server) DoSecurityUpdateCheck() { systemSecurityLastTime := &model.System{Name: model.SystemLastSecurityTime, Value: strconv.FormatInt(currentTime, 10)} if lastSecurityTime == 0 { - s.Store.System().Save(systemSecurityLastTime) + s.Store().System().Save(systemSecurityLastTime) } else { - s.Store.System().Update(systemSecurityLastTime) + s.Store().System().Update(systemSecurityLastTime) } - if count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { + if count, err := s.Store().User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { v.Set(PropSecurityUserCount, strconv.FormatInt(count, 10)) } - if ucr, err := s.Store.Status().GetTotalActiveUsersCount(); err == nil { + if ucr, err := s.Store().Status().GetTotalActiveUsersCount(); err == nil { v.Set(PropSecurityActiveUserCount, strconv.FormatInt(ucr, 10)) } - if teamCount, err := s.Store.Team().AnalyticsTeamCount(nil); err == nil { + if teamCount, err := s.Store().Team().AnalyticsTeamCount(nil); err == nil { v.Set(PropSecurityTeamCount, strconv.FormatInt(teamCount, 10)) } @@ -98,7 +98,7 @@ func (s *Server) DoSecurityUpdateCheck() { for _, bulletin := range bulletins { if bulletin.AppliesToVersion == model.CurrentVersion { if props["SecurityBulletin_"+bulletin.Id] == "" { - users, userErr := s.Store.User().GetSystemAdminProfiles() + users, userErr := s.Store().User().GetSystemAdminProfiles() if userErr != nil { mlog.Error("Failed to get system admins for security update information from Mattermost.") return @@ -125,7 +125,7 @@ func (s *Server) DoSecurityUpdateCheck() { } bulletinSeen := &model.System{Name: "SecurityBulletin_" + bulletin.Id, Value: bulletin.Id} - s.Store.System().Save(bulletinSeen) + s.Store().System().Save(bulletinSeen) } } } diff --git a/app/server.go b/app/server.go index 997c5a3f64..cddce3da40 100644 --- a/app/server.go +++ b/app/server.go @@ -8,18 +8,15 @@ import ( "context" "crypto/tls" "fmt" - "hash/maphash" "net" "net/http" "net/url" "os" "os/exec" "path" - "runtime" "strconv" "strings" "sync" - "sync/atomic" "syscall" "time" @@ -59,7 +56,6 @@ import ( "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/services/httpservice" "github.com/mattermost/mattermost-server/v6/services/remotecluster" - "github.com/mattermost/mattermost-server/v6/services/searchengine" "github.com/mattermost/mattermost-server/v6/services/searchengine/bleveengine" "github.com/mattermost/mattermost-server/v6/services/searchengine/bleveengine/indexer" "github.com/mattermost/mattermost-server/v6/services/sharedchannel" @@ -73,11 +69,6 @@ import ( "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/shared/templates" "github.com/mattermost/mattermost-server/v6/store" - "github.com/mattermost/mattermost-server/v6/store/localcachelayer" - "github.com/mattermost/mattermost-server/v6/store/retrylayer" - "github.com/mattermost/mattermost-server/v6/store/searchlayer" - "github.com/mattermost/mattermost-server/v6/store/sqlstore" - "github.com/mattermost/mattermost-server/v6/store/timerlayer" "github.com/mattermost/mattermost-server/v6/utils" ) @@ -109,10 +100,6 @@ const ( ) type Server struct { - sqlStore *sqlstore.SqlStore - Store store.Store - WebSocketRouter *WebSocketRouter - // RootRouter is the starting point for all HTTP requests to the server. RootRouter *mux.Router @@ -127,21 +114,13 @@ type Server struct { Server *http.Server ListenAddr *net.TCPAddr RateLimiter *RateLimiter - Busy *Busy localModeServer *http.Server didFinishListen chan struct{} - goroutineCount int32 - goroutineExitSignal chan struct{} - goroutineBuffered chan struct{} - EmailService email.ServiceInterface - hubs []*Hub - hashSeed maphash.Seed - httpService httpservice.HTTPService PushNotificationsHub PushNotificationsHub pushNotificationClient *http.Client // TODO: move this to it's own package @@ -149,77 +128,65 @@ type Server struct { runEssentialJobs bool Jobs *jobs.JobServer - clusterLeaderListeners sync.Map - clusterWrapper *clusterWrapper - - licenseValue atomic.Value - clientLicenseValue atomic.Value - licenseListeners map[string]func(*model.License, *model.License) - licenseWrapper *licenseWrapper + licenseWrapper *licenseWrapper timezones *timezones.Timezones - newStore func() (store.Store, error) - htmlTemplateWatcher *templates.Container seenPendingPostIdsCache cache.Cache - statusCache cache.Cache openGraphDataCache cache.Cache - configListenerId string - licenseListenerId string clusterLeaderListenerId string - searchConfigListenerId string - searchLicenseListenerId string loggerLicenseListenerId string filestore filestore.FileBackend platform *platform.PlatformService + platformOptions []platform.Option telemetryService *telemetry.TelemetryService userService *users.UserService teamService *teams.TeamService serviceMux sync.RWMutex remoteClusterService remotecluster.RemoteClusterServiceIFace - sharedChannelService SharedChannelServiceIFace + sharedChannelService SharedChannelServiceIFace // TODO: platform: move to platform package phase2PermissionsMigrationComplete bool Audit *audit.Audit - joinCluster bool - startMetrics bool - startSearchEngine bool - skipPostInit bool + joinCluster bool + // startSearchEngine bool + skipPostInit bool - SearchEngine *searchengine.Broker - - Cluster einterfaces.ClusterInterface - Cloud einterfaces.CloudInterface - LicenseManager einterfaces.LicenseInterface - - CacheProvider cache.Provider + Cloud einterfaces.CloudInterface tracer *tracing.Tracer products map[string]Product } +func (s *Server) Store() store.Store { + if s.platform != nil { + return s.platform.Store + } + + return nil +} + +func (s *Server) SetStore(st store.Store) { + if s.platform != nil { + s.platform.Store = st + } +} + func NewServer(options ...Option) (*Server, error) { rootRouter := mux.NewRouter() localRouter := mux.NewRouter() s := &Server{ - goroutineExitSignal: make(chan struct{}, 1), - goroutineBuffered: make(chan struct{}, runtime.NumCPU()), - RootRouter: rootRouter, - LocalRouter: localRouter, - WebSocketRouter: &WebSocketRouter{ - handlers: make(map[string]webSocketHandler), - }, - licenseListeners: map[string]func(*model.License, *model.License){}, - hashSeed: maphash.MakeSeed(), - timezones: timezones.New(), - products: make(map[string]Product), + RootRouter: rootRouter, + LocalRouter: localRouter, + timezones: timezones.New(), + products: make(map[string]Product), } for _, option := range options { @@ -232,7 +199,7 @@ func NewServer(options ...Option) (*Server, error) { // performed during server bootup. They are sensitive to order // and has dependency requirements with the previous step. // - // Step 1: Config. + // Step 1: Platform. if s.platform == nil { innerStore, err := config.NewFileStore("config.json", true) if err != nil { @@ -244,23 +211,14 @@ func NewServer(options ...Option) (*Server, error) { } platformCfg := platform.ServiceConfig{ - ConfigStore: configStore, - StartMetrics: s.startMetrics, - Cluster: s.Cluster, - } - if metricsInterface != nil { - platformCfg.Metrics = metricsInterface(s, *configStore.Get().SqlSettings.DriverName, *configStore.Get().SqlSettings.DataSource) + ConfigStore: configStore, } - ps, sErr := platform.New(platformCfg) + ps, sErr := platform.New(platformCfg, s.platformOptions...) if sErr != nil { return nil, errors.Wrap(sErr, "failed to initialize platform") } s.platform = ps - - if s.licenseValue.Load() != nil { - ps.SetLicense(s.licenseValue.Load().(*model.License)) // in case license is set in server options - } } subpath, err := utils.GetSubpathFromConfig(s.platform.Config()) @@ -269,99 +227,26 @@ func NewServer(options ...Option) (*Server, error) { } s.Router = s.RootRouter.PathPrefix(subpath).Subrouter() - // This is called after initLogging() to avoid a race condition. - mlog.Info("Server is initializing...", mlog.String("go_version", runtime.Version())) - s.httpService = httpservice.MakeHTTPService(s.platform) - // Step 3: Search Engine - // Depends on Step 1 (config). - searchEngine := searchengine.NewBroker(s.platform.Config()) - bleveEngine := bleveengine.NewBleveEngine(s.platform.Config()) - if err := bleveEngine.Start(); err != nil { - return nil, err - } - searchEngine.RegisterBleveEngine(bleveEngine) - s.SearchEngine = searchEngine - - // Step 4: Init Enterprise - // Depends on step 3 (s.SearchEngine must be non-nil) + // Step 2: Init Enterprise + // Depends on step 1 (s.Platform must be non-nil) s.initEnterprise() - // Step 5: Cache provider. - // At the moment we only have this implementation - // in the future the cache provider will be built based on the loaded config - s.CacheProvider = cache.NewProvider() - if err2 := s.CacheProvider.Connect(); err2 != nil { - return nil, errors.Wrapf(err2, "Unable to connect to cache provider") - } - - // Step 6: Store. - // Depends on Step 1 (config), 4 (metrics, cluster) and 5 (cacheProvider). - if s.newStore == nil { - s.newStore = func() (store.Store, error) { - s.sqlStore = sqlstore.New(s.platform.Config().SqlSettings, s.GetMetrics()) - - lcl, err2 := localcachelayer.NewLocalCacheLayer( - retrylayer.New(s.sqlStore), - s.GetMetrics(), - s.Cluster, - s.CacheProvider, - ) - if err2 != nil { - return nil, errors.Wrap(err2, "cannot create local cache layer") - } - - searchStore := searchlayer.NewSearchLayer( - lcl, - s.SearchEngine, - s.platform.Config(), - ) - - s.platform.AddConfigListener(func(prevCfg, cfg *model.Config) { - searchStore.UpdateConfig(cfg) - }) - - s.sqlStore.UpdateLicense(s.License()) - s.AddLicenseListener(func(oldLicense, newLicense *model.License) { - s.sqlStore.UpdateLicense(newLicense) - }) - - return timerlayer.New( - searchStore, - s.GetMetrics(), - ), nil - } - } - - s.Store, err = s.newStore() - if err != nil { - return nil, errors.Wrap(err, "cannot create store") - } - // Needed to run before loading license. s.userService, err = users.New(users.ServiceConfig{ - UserStore: s.Store.User(), - SessionStore: s.Store.Session(), - OAuthStore: s.Store.OAuth(), + UserStore: s.Store().User(), + SessionStore: s.Store().Session(), + OAuthStore: s.Store().OAuth(), ConfigFn: s.platform.Config, Metrics: s.GetMetrics(), - Cluster: s.Cluster, + Cluster: s.platform.Cluster(), LicenseFn: s.License, }) if err != nil { return nil, errors.Wrapf(err, "unable to create users service") } - // Needed before loading license - if s.statusCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{ - Size: model.StatusCacheSize, - Striped: true, - StripedBuckets: maxInt(runtime.NumCPU()-1, 1), - }); err != nil { - return nil, errors.Wrap(err, "Unable to create status cache") - } - if model.BuildEnterpriseReady == "true" { // Dependent on user service s.LoadLicense() @@ -369,7 +254,7 @@ func NewServer(options ...Option) (*Server, error) { license := s.License() insecure := s.platform.Config().ServiceSettings.EnableInsecureOutgoingConnections - // Step 7: Initialize filestore + // Step 3: Initialize filestore backend, err := filestore.NewFileBackend(s.platform.Config().FileSettings.ToFileBackendSettings(license != nil && *license.Features.Compliance, insecure != nil && *insecure)) if err != nil { return nil, errors.Wrap(err, "failed to initialize filebackend") @@ -380,16 +265,12 @@ func NewServer(options ...Option) (*Server, error) { srv: s, } - s.clusterWrapper = &clusterWrapper{ - srv: s, - } - s.teamService, err = teams.New(teams.ServiceConfig{ - TeamStore: s.Store.Team(), - ChannelStore: s.Store.Channel(), - GroupStore: s.Store.Group(), + TeamStore: s.Store().Team(), + ChannelStore: s.Store().Channel(), + GroupStore: s.Store().Group(), Users: s.userService, - WebHub: s, + WebHub: s.platform, ConfigFn: s.platform.Config, LicenseFn: s.License, }) @@ -406,16 +287,16 @@ func NewServer(options ...Option) (*Server, error) { LicenseKey: s.licenseWrapper, FilestoreKey: s.filestore, FileInfoStoreKey: &fileInfoWrapper{srv: s}, - ClusterKey: s.clusterWrapper, + ClusterKey: s.platform, UserKey: New(ServerConnector(s.Channels())), - LogKey: s.Log(), + LogKey: s.platform.Log(), CloudKey: &cloudWrapper{cloud: s.Cloud}, - KVStoreKey: &kvStoreWrapper{srv: s}, - StoreKey: store.NewStoreServiceAdapter(s.Store), + KVStoreKey: s.platform, + StoreKey: store.NewStoreServiceAdapter(s.Store()), SystemKey: &systemServiceAdapter{server: s}, } - // Step 8: Initialize products. + // Step 4: Initialize products. // Depends on s.httpService. err = s.initializeProducts(products, serviceMap) if err != nil { @@ -424,8 +305,8 @@ func NewServer(options ...Option) (*Server, error) { // It is important to initialize the hub only after the global logger is set // to avoid race conditions while logging from inside the hub. - // Step 9: Hub depends on s.Channels() (step 8) - s.HubStart() + // Step 5: Hub depends on s.Channels() (step 8) + s.platform.HubStart(New(ServerConnector(s.Channels()))) // ------------------------------------------------------------------------- // Everything below this is not order sensitive and safe to be moved around. @@ -475,12 +356,12 @@ func NewServer(options ...Option) (*Server, error) { } model.AppErrorInit(i18n.T) - if s.seenPendingPostIdsCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{ + if s.seenPendingPostIdsCache, err = s.platform.CacheProvider().NewCache(&cache.CacheOptions{ Size: PendingPostIDsCacheSize, }); err != nil { return nil, errors.Wrap(err, "Unable to create pending post ids cache") } - if s.openGraphDataCache, err = s.CacheProvider.NewCache(&cache.CacheOptions{ + if s.openGraphDataCache, err = s.platform.CacheProvider().NewCache(&cache.CacheOptions{ Size: openGraphMetadataCacheSize, }); err != nil { return nil, errors.Wrap(err, "Unable to create opengraphdata cache") @@ -507,35 +388,7 @@ func NewServer(options ...Option) (*Server, error) { }) s.htmlTemplateWatcher = htmlTemplateWatcher - s.configListenerId = s.platform.AddConfigListener(func(_, _ *model.Config) { - ch := s.Channels() - ch.regenerateClientConfig() - - message := model.NewWebSocketEvent(model.WebsocketEventConfigChanged, "", "", "", nil, "") - - appInstance := New(ServerConnector(ch)) - message.Add("config", appInstance.ClientConfigWithComputed()) - s.Go(func() { - s.Publish(message) - }) - - if err = s.platform.ReconfigureLogger(); err != nil { - mlog.Error("Error re-configuring logging after config change", mlog.Err(err)) - return - } - }) - s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { - s.Channels().regenerateClientConfig() - - message := model.NewWebSocketEvent(model.WebsocketEventLicenseChanged, "", "", "", nil, "") - message.Add("license", s.GetSanitizedClientLicense()) - s.Go(func() { - s.Publish(message) - }) - - }) - - s.telemetryService = telemetry.New(New(ServerConnector(s.Channels())), s.Store, s.SearchEngine, s.Log()) + s.telemetryService = telemetry.New(New(ServerConnector(s.Channels())), s.Store(), s.platform.SearchEngine, s.Log()) s.platform.SetTelemetryId(s.TelemetryId()) // TODO: move this into platform once telemetry service moved to platform. emailService, err := email.NewService(email.ServiceConfig{ @@ -617,36 +470,6 @@ func NewServer(options ...Option) (*Server, error) { s.platform.EnableLoggingMetrics() }) - // Enable developer settings if this is a "dev" build - if model.BuildNumber == "dev" { - s.platform.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableDeveloper = true }) - } - - if s.startMetrics { - if err := s.platform.RestartMetrics(); err != nil { - return nil, errors.Wrap(err, "failed to start metrics") - } - } - - s.AddLicenseListener(func(oldLicense, newLicense *model.License) { - if (oldLicense == nil && newLicense == nil) || !s.startMetrics { - return - } - - if oldLicense != nil && newLicense != nil && *oldLicense.Features.Metrics == *newLicense.Features.Metrics { - return - } - - if err := s.platform.RestartMetrics(); err != nil { - s.Log().Error("Failed to reset metrics server", mlog.Err(err)) - } - }) - - s.SearchEngine.UpdateConfig(s.platform.Config()) - searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine() - s.searchConfigListenerId = searchConfigListenerId - s.searchLicenseListenerId = searchLicenseListenerId - // if enabled - perform initial product notices fetch if *s.platform.Config().AnnouncementSettings.AdminNoticesEnabled || *s.platform.Config().AnnouncementSettings.UserNoticesEnabled { go func() { @@ -708,13 +531,6 @@ func NewServer(options ...Option) (*Server, error) { return s, nil } -func maxInt(a, b int) int { - if a > b { - return a - } - return b -} - func (s *Server) runJobs() { s.Go(func() { runSecurityJob(s) @@ -778,7 +594,7 @@ func (s *Server) Channels() *Channels { // Return Database type (postgres or mysql) and current version of the schema func (s *Server) DatabaseTypeAndSchemaVersion() (string, string) { - schemaVersion, _ := s.Store.GetDBSchemaVersion() + schemaVersion, _ := s.Store().GetDBSchemaVersion() return *s.platform.Config().SqlSettings.DriverName, strconv.Itoa(schemaVersion) } @@ -836,6 +652,7 @@ func (s *Server) startInterClusterServices(license *model.License) error { if err != nil { return err } + s.platform.SetSharedChannelService(scs) if err = scs.Start(); err != nil { return err @@ -877,8 +694,6 @@ func (s *Server) Shutdown() { defer sentry.Flush(2 * time.Second) - s.HubStop() - s.RemoveLicenseListener(s.licenseListenerId) s.RemoveLicenseListener(s.loggerLicenseListenerId) s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId) @@ -915,8 +730,7 @@ func (s *Server) Shutdown() { s.WaitForGoroutines() - s.platform.RemoveConfigListener(s.configListenerId) - s.stopSearchEngine() + s.platform.StopSearchEngine() s.Audit.Shutdown() @@ -926,8 +740,8 @@ func (s *Server) Shutdown() { s.Log().Warn("Failed to shut down config store", mlog.Err(err)) } - if s.Cluster != nil { - s.Cluster.StopInterNodeCommunication() + if s.platform.Cluster() != nil { + s.platform.Cluster().StopInterNodeCommunication() } if err = s.platform.ShutdownMetrics(); err != nil { @@ -956,14 +770,8 @@ func (s *Server) Shutdown() { } } - if s.Store != nil { - s.Store.Close() - } - - if s.CacheProvider != nil { - if err = s.CacheProvider.Close(); err != nil { - s.Log().Warn("Unable to cleanly shutdown cache", mlog.Err(err)) - } + if err = s.platform.Shutdown(); err != nil { + s.Log().Warn("Failed to stop platform", mlog.Err(err)) } s.Log().Info("Server stopped") @@ -999,14 +807,6 @@ func (s *Server) Restart() error { return syscall.Exec(argv0, os.Args, os.Environ()) } -func (s *Server) isUpgradedFromTE() bool { - val, err := s.Store.System().GetByName(model.SystemUpgradedFromTeId) - if err != nil { - return false - } - return val.Value == "true" -} - func (s *Server) CanIUpgradeToE0() error { return upgrader.CanIUpgradeToE0() } @@ -1016,7 +816,7 @@ func (s *Server) UpgradeToE0() error { return err } upgradedFromTE := &model.System{Name: model.SystemUpgradedFromTeId, Value: "true"} - s.Store.System().Save(upgradedFromTE) + s.Store().System().Save(upgradedFromTE) return nil } @@ -1027,44 +827,18 @@ func (s *Server) UpgradeToE0Status() (int64, error) { // Go creates a goroutine, but maintains a record of it to ensure that execution completes before // the server is shutdown. func (s *Server) Go(f func()) { - atomic.AddInt32(&s.goroutineCount, 1) - - go func() { - f() - - atomic.AddInt32(&s.goroutineCount, -1) - select { - case s.goroutineExitSignal <- struct{}{}: - default: - } - }() + s.platform.Go(f) } // GoBuffered acts like a semaphore which creates a goroutine, but maintains a record of it // to ensure that execution completes before the server is shutdown. func (s *Server) GoBuffered(f func()) { - s.goroutineBuffered <- struct{}{} - - atomic.AddInt32(&s.goroutineCount, 1) - - go func() { - f() - - atomic.AddInt32(&s.goroutineCount, -1) - select { - case s.goroutineExitSignal <- struct{}{}: - default: - } - - <-s.goroutineBuffered - }() + s.platform.GoBuffered(f) } // WaitForGoroutines blocks until all goroutines created by App.Go exit. func (s *Server) WaitForGoroutines() { - for atomic.LoadInt32(&s.goroutineCount) != 0 { - <-s.goroutineExitSignal - } + s.platform.WaitForGoroutines() } var corsAllowedMethods = []string{ @@ -1112,9 +886,9 @@ func (s *Server) Start() error { } } - if s.joinCluster && s.Cluster != nil { + if s.joinCluster && s.platform.Cluster() != nil { s.registerClusterHandlers() - s.Cluster.StartInterNodeCommunication() + s.platform.Cluster().StartInterNodeCommunication() } if err := s.ensureInstallationDate(); err != nil { @@ -1125,7 +899,7 @@ func (s *Server) Start() error { return errors.Wrapf(err, "unable to ensure first run timestamp") } - if err := s.Store.Status().ResetAll(); err != nil { + if err := s.Store().Status().ResetAll(); err != nil { mlog.Error("Error to reset the server status.", mlog.Err(err)) } @@ -1193,7 +967,6 @@ func (s *Server) Start() error { s.RateLimiter = rateLimiter handler = rateLimiter.RateLimitHandler(handler) } - s.Busy = NewBusy(s.Cluster) // Creating a logger for logging errors from http.Server at error level errStdLog := s.Log().With(mlog.String("source", "httpserver")).StdLogger(mlog.LvlError) @@ -1471,7 +1244,7 @@ func runReportToAWSMeterJob(s *Server) { } func doReportUsageToAWSMeteringService(s *Server) { - awsMeter := awsmeter.New(s.Store, s.platform.Config()) + awsMeter := awsmeter.New(s.Store(), s.platform.Config()) if awsMeter == nil { mlog.Error("Cannot obtain instance of AWS Metering Service.") return @@ -1491,11 +1264,11 @@ func doTokenCleanup(s *Server) { mlog.Debug("Cleaning up token store.") - s.Store.Token().Cleanup(expiry) + s.Store().Token().Cleanup(expiry) } func doCommandWebhookCleanup(s *Server) { - s.Store.CommandWebhook().Cleanup() + s.Store().CommandWebhook().Cleanup() } const ( @@ -1505,7 +1278,7 @@ const ( func doSessionCleanup(s *Server) { mlog.Debug("Cleaning up session store.") - err := s.Store.Session().Cleanup(model.GetMillis(), sessionsCleanupBatchSize) + err := s.Store().Session().Cleanup(model.GetMillis(), sessionsCleanupBatchSize) if err != nil { mlog.Warn("Error while cleaning up sessions", mlog.Err(err)) } @@ -1519,7 +1292,7 @@ func doJobsCleanup(s *Server) { dur := time.Duration(*s.platform.Config().JobSettings.CleanupJobsThresholdDays) * time.Hour * 24 expiry := model.GetMillisForTime(time.Now().Add(-dur)) - err := s.Store.Job().Cleanup(expiry, jobsCleanupBatchSize) + err := s.Store().Job().Cleanup(expiry, jobsCleanupBatchSize) if err != nil { mlog.Warn("Error while cleaning up jobs", mlog.Err(err)) } @@ -1542,7 +1315,7 @@ func (s *Server) HandleMetrics(route string, h http.Handler) { func (s *Server) sendLicenseUpForRenewalEmail(users map[string]*model.User, license *model.License) *model.AppError { key := model.LicenseUpForRenewalEmailSent + license.Id - if _, err := s.Store.System().GetByName(key); err == nil { + if _, err := s.Store().System().GetByName(key); err == nil { // return early because the key already exists and that means we already executed the code below to send email successfully return nil } @@ -1578,7 +1351,7 @@ func (s *Server) sendLicenseUpForRenewalEmail(users map[string]*model.User, lice Value: "true", } - if err := s.Store.System().Save(&system); err != nil { + if err := s.Store().System().Save(&system); err != nil { mlog.Debug("Failed to mark license up for renewal email sending as completed.", mlog.Err(err)) } @@ -1608,7 +1381,7 @@ func (s *Server) doLicenseExpirationCheck() { return } - users, err := s.Store.User().GetSystemAdminProfiles() + users, err := s.Store().User().GetSystemAdminProfiles() if err != nil { mlog.Error("Failed to get system admins for license expired message from Mattermost.") return @@ -1664,109 +1437,24 @@ func (s *Server) SendRemoveExpiredLicenseEmail(email string, renewalLink, locale return nil } -func (s *Server) StartSearchEngine() (string, string) { - if s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { - s.Go(func() { - if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { - s.Log().Error(err.Error()) - } - }) - } - - configListenerId := s.platform.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { - if s.SearchEngine == nil { - return - } - s.SearchEngine.UpdateConfig(newConfig) - - if s.SearchEngine.ElasticsearchEngine != nil && !*oldConfig.ElasticsearchSettings.EnableIndexing && *newConfig.ElasticsearchSettings.EnableIndexing { - s.Go(func() { - if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { - mlog.Error(err.Error()) - } - }) - } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.EnableIndexing && !*newConfig.ElasticsearchSettings.EnableIndexing { - s.Go(func() { - if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { - mlog.Error(err.Error()) - } - }) - } else if s.SearchEngine.ElasticsearchEngine != nil && *oldConfig.ElasticsearchSettings.Password != *newConfig.ElasticsearchSettings.Password || *oldConfig.ElasticsearchSettings.Username != *newConfig.ElasticsearchSettings.Username || *oldConfig.ElasticsearchSettings.ConnectionURL != *newConfig.ElasticsearchSettings.ConnectionURL || *oldConfig.ElasticsearchSettings.Sniff != *newConfig.ElasticsearchSettings.Sniff { - s.Go(func() { - if *oldConfig.ElasticsearchSettings.EnableIndexing { - if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { - mlog.Error(err.Error()) - } - if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { - mlog.Error(err.Error()) - } - } - }) - } - }) - - licenseListenerId := s.AddLicenseListener(func(oldLicense, newLicense *model.License) { - if s.SearchEngine == nil { - return - } - if oldLicense == nil && newLicense != nil { - if s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { - s.Go(func() { - if err := s.SearchEngine.ElasticsearchEngine.Start(); err != nil { - mlog.Error(err.Error()) - } - }) - } - } else if oldLicense != nil && newLicense == nil { - if s.SearchEngine.ElasticsearchEngine != nil { - s.Go(func() { - if err := s.SearchEngine.ElasticsearchEngine.Stop(); err != nil { - mlog.Error(err.Error()) - } - }) - } - } - }) - - return configListenerId, licenseListenerId -} - -func (s *Server) stopSearchEngine() { - s.platform.RemoveConfigListener(s.searchConfigListenerId) - s.RemoveLicenseListener(s.searchLicenseListenerId) - if s.SearchEngine != nil && s.SearchEngine.ElasticsearchEngine != nil && s.SearchEngine.ElasticsearchEngine.IsActive() { - s.SearchEngine.ElasticsearchEngine.Stop() - } - if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && s.SearchEngine.BleveEngine.IsActive() { - s.SearchEngine.BleveEngine.Stop() - } -} - func (s *Server) FileBackend() filestore.FileBackend { return s.filestore } func (s *Server) TotalWebsocketConnections() int { - // This method is only called after the hub is initialized. - // Therefore, no mutex is needed to protect s.hubs. - count := int64(0) - for _, hub := range s.hubs { - count = count + atomic.LoadInt64(&hub.connectionCount) - } - - return int(count) + return s.Platform().TotalWebsocketConnections() } func (s *Server) ClusterHealthScore() int { - return s.Cluster.HealthScore() + return s.platform.Cluster().HealthScore() } func (ch *Channels) ClientConfigHash() string { - return ch.clientConfigHash.Load().(string) + return ch.srv.Platform().ClientConfigHash() } func (s *Server) initJobs() { - s.Jobs = jobs.NewJobServer(s.platform, s.Store, s.GetMetrics()) + s.Jobs = jobs.NewJobServer(s.platform, s.Store(), s.GetMetrics()) if jobsDataRetentionJobInterface != nil { builder := jobsDataRetentionJobInterface(s) @@ -1795,14 +1483,14 @@ func (s *Server) initJobs() { s.Jobs.RegisterJobType( model.JobTypeBlevePostIndexing, - indexer.MakeWorker(s.Jobs, s.SearchEngine.BleveEngine.(*bleveengine.BleveEngine)), + indexer.MakeWorker(s.Jobs, s.platform.SearchEngine.BleveEngine.(*bleveengine.BleveEngine)), nil, ) s.Jobs.RegisterJobType( model.JobTypeMigrations, - migrations.MakeWorker(s.Jobs, s.Store), - migrations.MakeScheduler(s.Jobs, s.Store), + migrations.MakeWorker(s.Jobs, s.Store()), + migrations.MakeScheduler(s.Jobs, s.Store()), ) s.Jobs.RegisterJobType( @@ -1831,7 +1519,7 @@ func (s *Server) initJobs() { s.Jobs.RegisterJobType( model.JobTypeImportDelete, - import_delete.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store), + import_delete.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store()), import_delete.MakeScheduler(s.Jobs), ) @@ -1849,19 +1537,19 @@ func (s *Server) initJobs() { s.Jobs.RegisterJobType( model.JobTypeActiveUsers, - active_users.MakeWorker(s.Jobs, s.Store, func() einterfaces.MetricsInterface { return s.GetMetrics() }), + active_users.MakeWorker(s.Jobs, s.Store(), func() einterfaces.MetricsInterface { return s.GetMetrics() }), active_users.MakeScheduler(s.Jobs), ) s.Jobs.RegisterJobType( model.JobTypeResendInvitationEmail, - resend_invitation_email.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store, s.telemetryService), + resend_invitation_email.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store(), s.telemetryService), nil, ) s.Jobs.RegisterJobType( model.JobTypeExtractContent, - extract_content.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store), + extract_content.MakeWorker(s.Jobs, New(ServerConnector(s.Channels())), s.Store()), nil, ) @@ -1888,6 +1576,8 @@ func (s *Server) initJobs() { notify_admin.MakeTrialNotifyWorker(s.Jobs, s.License(), New(ServerConnector(s.Channels()))), notify_admin.MakeScheduler(s.Jobs, s.License(), model.JobTypeTrialNotifyAdmin), ) + + s.platform.Jobs = s.Jobs } func (s *Server) TelemetryId() string { @@ -1904,7 +1594,7 @@ func (s *Server) HTTPService() httpservice.HTTPService { // GetStore returns the server's Store. Exposing via a method // allows interfaces to be created with subsets of server APIs. func (s *Server) GetStore() store.Store { - return s.Store + return s.Store() } // GetRemoteClusterService returns the `RemoteClusterService` instantiated by the server. @@ -1946,6 +1636,7 @@ func (s *Server) SetSharedChannelSyncService(sharedChannelService SharedChannelS s.serviceMux.Lock() defer s.serviceMux.Unlock() s.sharedChannelService = sharedChannelService + s.platform.SetSharedChannelService(sharedChannelService) } func (s *Server) GetProfileImage(user *model.User) ([]byte, bool, *model.AppError) { @@ -2053,7 +1744,7 @@ func runPostReminderJob(a *App) { } func (a *App) GetAppliedSchemaMigrations() ([]model.AppliedMigration, *model.AppError) { - table, err := a.Srv().Store.GetAppliedMigrations() + table, err := a.Srv().Store().GetAppliedMigrations() if err != nil { return nil, model.NewAppError("GetDBSchemaTable", "api.file.read_file.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/server_inactivity.go b/app/server_inactivity.go index 4c5b0b7a01..350afb9090 100644 --- a/app/server_inactivity.go +++ b/app/server_inactivity.go @@ -32,7 +32,7 @@ func (s *Server) doInactivityCheck() { return } - _, sysValErr := s.Store.System().GetByName(inactivityEmailSent) + _, sysValErr := s.Store().System().GetByName(inactivityEmailSent) // if there is no error which may include *store.ErrNotFound, it means this check was already flagged as done if sysValErr == nil { return @@ -48,7 +48,7 @@ func (s *Server) doInactivityCheck() { // The first time this job runs. We check if the user has not made any posts in last inactivityDurationHours // and remind them to use the workspace. If no posts have been made. We check the last time // they logged in (session) for the last inactivityDurationHours and send a reminder. - lastPostAt, _ := s.Store.Post().GetLastPostRowCreateAt() + lastPostAt, _ := s.Store().Post().GetLastPostRowCreateAt() if lastPostAt != 0 { posT := time.Unix(lastPostAt/1000, 0) timeForLastPost := time.Since(posT).Hours() @@ -58,7 +58,7 @@ func (s *Server) doInactivityCheck() { return } - lastSessionAt, _ := s.Store.Session().GetLastSessionRowCreateAt() + lastSessionAt, _ := s.Store().Session().GetLastSessionRowCreateAt() if lastSessionAt != 0 { sesT := time.Unix(lastSessionAt/1000, 0) timeForLastSession := time.Since(sesT).Hours() @@ -79,7 +79,7 @@ func (s *Server) takeInactivityAction() { "SiteURL": siteURL, } s.GetTelemetryService().SendTelemetry("inactive_server", properties) - users, err := s.Store.User().GetSystemAdminProfiles() + users, err := s.Store().User().GetSystemAdminProfiles() if err != nil { mlog.Error("Failed to get system admins for inactivity check from Mattermost.") return @@ -110,7 +110,7 @@ func (s *Server) takeInactivityAction() { // Mark that we sent emails. sysVar := &model.System{Name: inactivityEmailSent, Value: "true"} - if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { + if err := s.Store().System().SaveOrUpdate(sysVar); err != nil { mlog.Error("Unable to save INACTIVITY", mlog.Err(err)) } diff --git a/app/server_test.go b/app/server_test.go index e7d5aa1cab..f8135d0461 100644 --- a/app/server_test.go +++ b/app/server_test.go @@ -29,7 +29,6 @@ import ( "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/filestore" "github.com/mattermost/mattermost-server/v6/shared/mlog" - "github.com/mattermost/mattermost-server/v6/store/storetest" "github.com/mattermost/mattermost-server/v6/utils/fileutils" ) @@ -61,97 +60,6 @@ func TestStartServerSuccess(t *testing.T) { require.NoError(t, serverErr) } -func TestReadReplicaDisabledBasedOnLicense(t *testing.T) { - cfg := model.Config{} - cfg.SetDefaults() - driverName := os.Getenv("MM_SQLSETTINGS_DRIVERNAME") - if driverName == "" { - driverName = model.DatabaseDriverPostgres - } - dsn := "" - if driverName == model.DatabaseDriverPostgres { - dsn = os.Getenv("TEST_DATABASE_POSTGRESQL_DSN") - } else { - dsn = os.Getenv("TEST_DATABASE_MYSQL_DSN") - } - cfg.SqlSettings = *storetest.MakeSqlSettings(driverName, false) - if dsn != "" { - cfg.SqlSettings.DataSource = &dsn - } - cfg.SqlSettings.DataSourceReplicas = []string{*cfg.SqlSettings.DataSource} - cfg.SqlSettings.DataSourceSearchReplicas = []string{*cfg.SqlSettings.DataSource} - - t.Run("Read Replicas with no License", func(t *testing.T) { - s, err := NewServer(func(server *Server) error { - configStore := config.NewTestMemoryStore() - configStore.Set(&cfg) - var err error - server.platform, err = platform.New(platform.ServiceConfig{ - ConfigStore: configStore, - }) - require.NoError(t, err) - return nil - }) - require.NoError(t, err) - defer s.Shutdown() - require.Same(t, s.sqlStore.GetMasterX(), s.sqlStore.GetReplicaX()) - require.Len(t, s.platform.Config().SqlSettings.DataSourceReplicas, 1) - }) - - t.Run("Read Replicas With License", func(t *testing.T) { - s, err := NewServer(func(server *Server) error { - configStore := config.NewTestMemoryStore() - configStore.Set(&cfg) - var err error - server.platform, err = platform.New(platform.ServiceConfig{ - ConfigStore: configStore, - }) - require.NoError(t, err) - server.licenseValue.Store(model.NewTestLicense()) - return nil - }) - require.NoError(t, err) - defer s.Shutdown() - require.NotSame(t, s.sqlStore.GetMasterX(), s.sqlStore.GetReplicaX()) - require.Len(t, s.platform.Config().SqlSettings.DataSourceReplicas, 1) - }) - - t.Run("Search Replicas with no License", func(t *testing.T) { - s, err := NewServer(func(server *Server) error { - configStore := config.NewTestMemoryStore() - configStore.Set(&cfg) - var err error - server.platform, err = platform.New(platform.ServiceConfig{ - ConfigStore: configStore, - }) - require.NoError(t, err) - return nil - }) - require.NoError(t, err) - defer s.Shutdown() - require.Same(t, s.sqlStore.GetMasterX(), s.sqlStore.GetSearchReplicaX()) - require.Len(t, s.platform.Config().SqlSettings.DataSourceSearchReplicas, 1) - }) - - t.Run("Search Replicas With License", func(t *testing.T) { - s, err := NewServer(func(server *Server) error { - configStore := config.NewTestMemoryStore() - configStore.Set(&cfg) - var err error - server.platform, err = platform.New(platform.ServiceConfig{ - ConfigStore: configStore, - }) - require.NoError(t, err) - server.licenseValue.Store(model.NewTestLicense()) - return nil - }) - require.NoError(t, err) - defer s.Shutdown() - require.NotSame(t, s.sqlStore.GetMasterX(), s.sqlStore.GetSearchReplicaX()) - require.Len(t, s.platform.Config().SqlSettings.DataSourceSearchReplicas, 1) - }) -} - func TestStartServerPortUnavailable(t *testing.T) { s, err := NewServer() require.NoError(t, err) diff --git a/app/session.go b/app/session.go index 4e32670b75..86ed75166b 100644 --- a/app/session.go +++ b/app/session.go @@ -10,6 +10,7 @@ import ( "net/http" "os" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/app/users" "github.com/mattermost/mattermost-server/v6/audit" "github.com/mattermost/mattermost-server/v6/model" @@ -18,7 +19,7 @@ import ( ) func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) { - session, err := a.ch.srv.userService.CreateSession(session) + session, err := a.ch.srv.platform.CreateSession(session) if err != nil { var invErr *store.ErrInvalidInput switch { @@ -66,13 +67,13 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { var session *model.Session // We intentionally skip the error check here, we only want to check if the token is valid. // If we don't have the session we are going to create one with the token eventually. - if session, _ = a.ch.srv.userService.GetSession(token); session != nil { + if session, _ = a.ch.srv.platform.GetSession(token); session != nil { if session.Token != token { return nil, model.NewAppError("GetSession", "api.context.invalid_token.error", map[string]any{"Token": token, "Error": ""}, "session token is different from the one in DB", http.StatusUnauthorized) } if !session.IsExpired() { - a.ch.srv.userService.AddSessionToCache(session) + a.ch.srv.platform.AddSessionToCache(session) } } @@ -124,7 +125,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { } func (a *App) GetSessions(userID string) ([]*model.Session, *model.AppError) { - sessions, err := a.ch.srv.userService.GetSessions(userID) + sessions, err := a.ch.srv.platform.GetSessions(userID) if err != nil { return nil, model.NewAppError("GetSessions", "app.session.get_sessions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -133,11 +134,11 @@ func (a *App) GetSessions(userID string) ([]*model.Session, *model.AppError) { } func (a *App) RevokeAllSessions(userID string) *model.AppError { - if err := a.ch.srv.userService.RevokeAllSessions(userID); err != nil { + if err := a.ch.srv.platform.RevokeAllSessions(userID); err != nil { switch { - case errors.Is(err, users.GetSessionError): + case errors.Is(err, platform.GetSessionError): return model.NewAppError("RevokeAllSessions", "app.session.get_sessions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - case errors.Is(err, users.DeleteSessionError): + case errors.Is(err, platform.DeleteSessionError): return model.NewAppError("RevokeAllSessions", "app.session.remove.app_error", nil, "", http.StatusInternalServerError).Wrap(err) default: return model.NewAppError("RevokeAllSessions", "app.session.remove.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -148,13 +149,13 @@ func (a *App) RevokeAllSessions(userID string) *model.AppError { } func (a *App) AddSessionToCache(session *model.Session) { - a.ch.srv.userService.AddSessionToCache(session) + a.ch.srv.platform.AddSessionToCache(session) } // RevokeSessionsFromAllUsers will go through all the sessions active // in the server and revoke them func (a *App) RevokeSessionsFromAllUsers() *model.AppError { - if err := a.ch.srv.userService.RevokeSessionsFromAllUsers(); err != nil { + if err := a.ch.srv.platform.RevokeSessionsFromAllUsers(); err != nil { switch { case errors.Is(err, users.DeleteAllAccessDataError): return model.NewAppError("RevokeSessionsFromAllUsers", "app.oauth.remove_access_data.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -167,27 +168,27 @@ func (a *App) RevokeSessionsFromAllUsers() *model.AppError { } func (a *App) ReturnSessionToPool(session *model.Session) { - a.ch.srv.userService.ReturnSessionToPool(session) + a.ch.srv.platform.ReturnSessionToPool(session) } func (a *App) ClearSessionCacheForUser(userID string) { - a.ch.srv.userService.ClearUserSessionCache(userID) + a.ch.srv.platform.ClearUserSessionCache(userID) } func (a *App) ClearSessionCacheForAllUsers() { - a.ch.srv.userService.ClearAllUsersSessionCache() + a.ch.srv.platform.ClearAllUsersSessionCache() } func (a *App) ClearSessionCacheForUserSkipClusterSend(userID string) { - a.Srv().clearSessionCacheForUserSkipClusterSend(userID) + a.Srv().Platform().ClearSessionCacheForUserSkipClusterSend(userID) } func (a *App) ClearSessionCacheForAllUsersSkipClusterSend() { - a.Srv().clearSessionCacheForAllUsersSkipClusterSend() + a.Srv().Platform().ClearSessionCacheForAllUsersSkipClusterSend() } func (a *App) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) *model.AppError { - if err := a.ch.srv.userService.RevokeSessionsForDeviceId(userID, deviceID, currentSessionId); err != nil { + if err := a.ch.srv.platform.RevokeSessionsForDeviceId(userID, deviceID, currentSessionId); err != nil { return model.NewAppError("RevokeSessionsForDeviceId", "app.session.get_sessions.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -195,7 +196,7 @@ func (a *App) RevokeSessionsForDeviceId(userID string, deviceID string, currentS } func (a *App) GetSessionById(sessionID string) (*model.Session, *model.AppError) { - session, err := a.ch.srv.userService.GetSessionByID(sessionID) + session, err := a.ch.srv.platform.GetSessionByID(sessionID) if err != nil { return nil, model.NewAppError("GetSessionById", "app.session.get.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -213,9 +214,9 @@ func (a *App) RevokeSessionById(sessionID string) *model.AppError { } func (a *App) RevokeSession(session *model.Session) *model.AppError { - if err := a.ch.srv.userService.RevokeSession(session); err != nil { + if err := a.ch.srv.platform.RevokeSession(session); err != nil { switch { - case errors.Is(err, users.DeleteSessionError): + case errors.Is(err, platform.DeleteSessionError): return model.NewAppError("RevokeSession", "app.session.remove.app_error", nil, "", http.StatusInternalServerError).Wrap(err) default: return model.NewAppError("RevokeSession", "app.session.remove.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -226,7 +227,7 @@ func (a *App) RevokeSession(session *model.Session) *model.AppError { } func (a *App) AttachDeviceId(sessionID string, deviceID string, expiresAt int64) *model.AppError { - _, err := a.Srv().Store.Session().UpdateDeviceId(sessionID, deviceID, expiresAt) + _, err := a.Srv().Store().Session().UpdateDeviceId(sessionID, deviceID, expiresAt) if err != nil { return model.NewAppError("AttachDeviceId", "app.session.update_device_id.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -243,12 +244,12 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { return } - if err := a.Srv().Store.Session().UpdateLastActivityAt(session.Id, now); err != nil { + if err := a.Srv().Store().Session().UpdateLastActivityAt(session.Id, now); err != nil { mlog.Warn("Failed to update LastActivityAt", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Err(err)) } session.LastActivityAt = now - a.ch.srv.userService.AddSessionToCache(&session) + a.ch.srv.platform.AddSessionToCache(&session) } // ExtendSessionExpiryIfNeeded extends Session.ExpiresAt based on session lengths in config. @@ -286,7 +287,7 @@ func (a *App) ExtendSessionExpiryIfNeeded(session *model.Session) bool { auditRec.AddMeta("session", session) newExpiry := now + sessionLength - if err := a.ch.srv.userService.ExtendSessionExpiry(session, newExpiry); err != nil { + if err := a.ch.srv.platform.ExtendSessionExpiry(session, newExpiry); err != nil { mlog.Error("Failed to update ExpiresAt", mlog.String("user_id", session.UserId), mlog.String("session_id", session.Id), mlog.Err(err)) auditRec.AddMeta("err", err.Error()) return false @@ -322,7 +323,7 @@ func (a *App) GetSessionLengthInMillis(session *model.Session) int64 { // relative to either the session creation date or the current time, depending // on the `ExtendSessionOnActivity` config setting. func (a *App) SetSessionExpireInHours(session *model.Session, hours int) { - a.ch.srv.userService.SetSessionExpireInHours(session, hours) + a.ch.srv.platform.SetSessionExpireInHours(session, hours) } func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { @@ -343,7 +344,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc token.Token = model.NewId() - token, nErr = a.Srv().Store.UserAccessToken().Save(token) + token, nErr = a.Srv().Store().UserAccessToken().Save(token) if nErr != nil { var appErr *model.AppError switch { @@ -366,7 +367,7 @@ func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAc } func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Session, *model.AppError) { - token, nErr := a.Srv().Store.UserAccessToken().GetByToken(tokenString) + token, nErr := a.Srv().Store().UserAccessToken().GetByToken(tokenString) if nErr != nil { return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "", http.StatusUnauthorized).Wrap(nErr) } @@ -375,7 +376,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio return nil, model.NewAppError("createSessionForUserAccessToken", "app.user_access_token.invalid_or_missing", nil, "inactive_token", http.StatusUnauthorized) } - user, nErr := a.Srv().Store.User().Get(context.Background(), token.UserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), token.UserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -411,9 +412,9 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio } else { session.AddProp(model.SessionPropIsGuest, "false") } - a.ch.srv.userService.SetSessionExpireInHours(session, model.SessionUserAccessTokenExpiryHours) + a.ch.srv.platform.SetSessionExpireInHours(session, model.SessionUserAccessTokenExpiryHours) - session, nErr = a.Srv().Store.Session().Save(session) + session, nErr = a.Srv().Store().Session().Save(session) if nErr != nil { var invErr *store.ErrInvalidInput switch { @@ -424,7 +425,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio } } - a.ch.srv.userService.AddSessionToCache(session) + a.ch.srv.platform.AddSessionToCache(session) return session, nil @@ -432,9 +433,9 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token) + session, _ = a.ch.srv.platform.GetSessionContext(context.Background(), token.Token) - if err := a.Srv().Store.UserAccessToken().Delete(token.Id); err != nil { + if err := a.Srv().Store().UserAccessToken().Delete(token.Id); err != nil { return model.NewAppError("RevokeUserAccessToken", "app.user_access_token.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -447,9 +448,9 @@ func (a *App) RevokeUserAccessToken(token *model.UserAccessToken) *model.AppErro func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token) + session, _ = a.ch.srv.platform.GetSessionContext(context.Background(), token.Token) - if err := a.Srv().Store.UserAccessToken().UpdateTokenDisable(token.Id); err != nil { + if err := a.Srv().Store().UserAccessToken().UpdateTokenDisable(token.Id); err != nil { return model.NewAppError("DisableUserAccessToken", "app.user_access_token.update_token_disable.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -462,9 +463,9 @@ func (a *App) DisableUserAccessToken(token *model.UserAccessToken) *model.AppErr func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppError { var session *model.Session - session, _ = a.ch.srv.userService.GetSessionContext(context.Background(), token.Token) + session, _ = a.ch.srv.platform.GetSessionContext(context.Background(), token.Token) - err := a.Srv().Store.UserAccessToken().UpdateTokenEnable(token.Id) + err := a.Srv().Store().UserAccessToken().UpdateTokenEnable(token.Id) if err != nil { return model.NewAppError("EnableUserAccessToken", "app.user_access_token.update_token_enable.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -477,7 +478,7 @@ func (a *App) EnableUserAccessToken(token *model.UserAccessToken) *model.AppErro } func (a *App) GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv().Store.UserAccessToken().GetAll(page*perPage, perPage) + tokens, err := a.Srv().Store().UserAccessToken().GetAll(page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetUserAccessTokens", "app.user_access_token.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -490,7 +491,7 @@ func (a *App) GetUserAccessTokens(page, perPage int) ([]*model.UserAccessToken, } func (a *App) GetUserAccessTokensForUser(userID string, page, perPage int) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv().Store.UserAccessToken().GetByUser(userID, page*perPage, perPage) + tokens, err := a.Srv().Store().UserAccessToken().GetByUser(userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetUserAccessTokensForUser", "app.user_access_token.get_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -503,7 +504,7 @@ func (a *App) GetUserAccessTokensForUser(userID string, page, perPage int) ([]*m } func (a *App) GetUserAccessToken(tokenID string, sanitize bool) (*model.UserAccessToken, *model.AppError) { - token, err := a.Srv().Store.UserAccessToken().Get(tokenID) + token, err := a.Srv().Store().UserAccessToken().Get(tokenID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -521,7 +522,7 @@ func (a *App) GetUserAccessToken(tokenID string, sanitize bool) (*model.UserAcce } func (a *App) SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError) { - tokens, err := a.Srv().Store.UserAccessToken().Search(term) + tokens, err := a.Srv().Store().UserAccessToken().Search(term) if err != nil { return nil, model.NewAppError("SearchUserAccessTokens", "app.user_access_token.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/session_test.go b/app/session_test.go index ec51d43913..7760bed82a 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -35,7 +35,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { // Test regular session, should timeout time := session.LastActivityAt - (1000 * 60 * 6) - nErr := th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) + nErr := th.App.Srv().Store().Session().UpdateLastActivityAt(session.Id, time) require.NoError(t, nErr) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -53,7 +53,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - nErr = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) + nErr = th.App.Srv().Store().Session().UpdateLastActivityAt(session.Id, time) require.NoError(t, nErr) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -68,7 +68,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - nErr = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) + nErr = th.App.Srv().Store().Session().UpdateLastActivityAt(session.Id, time) require.NoError(t, nErr) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -86,7 +86,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) time = session.LastActivityAt - (1000 * 60 * 6) - nErr = th.App.Srv().Store.Session().UpdateLastActivityAt(session.Id, time) + nErr = th.App.Srv().Store().Session().UpdateLastActivityAt(session.Id, time) require.NoError(t, nErr) th.App.ClearSessionCacheForUserSkipClusterSend(session.UserId) @@ -317,12 +317,12 @@ func TestApp_ExtendExpiryIfNeeded(t *testing.T) { require.False(t, session.IsExpired()) // check cache was updated - cachedSession, errGet := th.App.ch.srv.userService.GetSession(session.Token) + cachedSession, errGet := th.App.ch.srv.platform.GetSession(session.Token) require.NoError(t, errGet) require.Equal(t, session.ExpiresAt, cachedSession.ExpiresAt) // check database was updated. - storedSession, nErr := th.App.Srv().Store.Session().Get(context.Background(), session.Token) + storedSession, nErr := th.App.Srv().Store().Session().Get(context.Background(), session.Token) require.NoError(t, nErr) require.Equal(t, session.ExpiresAt, storedSession.ExpiresAt) }) diff --git a/app/shared_channel.go b/app/shared_channel.go index 9ce513be17..d1634859e4 100644 --- a/app/shared_channel.go +++ b/app/shared_channel.go @@ -63,19 +63,19 @@ func (a *App) SaveSharedChannel(c request.CTX, sc *model.SharedChannel) (*model. if err := a.checkChannelNotShared(c, sc.ChannelId); err != nil { return nil, err } - return a.Srv().Store.SharedChannel().Save(sc) + return a.Srv().Store().SharedChannel().Save(sc) } func (a *App) GetSharedChannel(channelID string) (*model.SharedChannel, error) { - return a.Srv().Store.SharedChannel().Get(channelID) + return a.Srv().Store().SharedChannel().Get(channelID) } func (a *App) HasSharedChannel(channelID string) (bool, error) { - return a.Srv().Store.SharedChannel().HasChannel(channelID) + return a.Srv().Store().SharedChannel().HasChannel(channelID) } func (a *App) GetSharedChannels(page int, perPage int, opts model.SharedChannelFilterOpts) ([]*model.SharedChannel, *model.AppError) { - channels, err := a.Srv().Store.SharedChannel().GetAll(page*perPage, perPage, opts) + channels, err := a.Srv().Store().SharedChannel().GetAll(page*perPage, perPage, opts) if err != nil { return nil, model.NewAppError("GetSharedChannels", "app.channel.get_channels.not_found.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -83,15 +83,15 @@ func (a *App) GetSharedChannels(page int, perPage int, opts model.SharedChannelF } func (a *App) GetSharedChannelsCount(opts model.SharedChannelFilterOpts) (int64, error) { - return a.Srv().Store.SharedChannel().GetAllCount(opts) + return a.Srv().Store().SharedChannel().GetAllCount(opts) } func (a *App) UpdateSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error) { - return a.Srv().Store.SharedChannel().Update(sc) + return a.Srv().Store().SharedChannel().Update(sc) } func (a *App) DeleteSharedChannel(channelID string) (bool, error) { - return a.Srv().Store.SharedChannel().Delete(channelID) + return a.Srv().Store().SharedChannel().Delete(channelID) } // SharedChannelRemotes @@ -100,28 +100,28 @@ func (a *App) SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model if err := a.checkChannelIsShared(remote.ChannelId); err != nil { return nil, err } - return a.Srv().Store.SharedChannel().SaveRemote(remote) + return a.Srv().Store().SharedChannel().SaveRemote(remote) } func (a *App) GetSharedChannelRemote(id string) (*model.SharedChannelRemote, error) { - return a.Srv().Store.SharedChannel().GetRemote(id) + return a.Srv().Store().SharedChannel().GetRemote(id) } func (a *App) GetSharedChannelRemoteByIds(channelID string, remoteID string) (*model.SharedChannelRemote, error) { - return a.Srv().Store.SharedChannel().GetRemoteByIds(channelID, remoteID) + return a.Srv().Store().SharedChannel().GetRemoteByIds(channelID, remoteID) } func (a *App) GetSharedChannelRemotes(opts model.SharedChannelRemoteFilterOpts) ([]*model.SharedChannelRemote, error) { - return a.Srv().Store.SharedChannel().GetRemotes(opts) + return a.Srv().Store().SharedChannel().GetRemotes(opts) } // HasRemote returns whether a given channelID is present in the channel remotes or not. func (a *App) HasRemote(channelID string, remoteID string) (bool, error) { - return a.Srv().Store.SharedChannel().HasRemote(channelID, remoteID) + return a.Srv().Store().SharedChannel().HasRemote(channelID, remoteID) } func (a *App) GetRemoteClusterForUser(remoteID string, userID string) (*model.RemoteCluster, *model.AppError) { - rc, err := a.Srv().Store.SharedChannel().GetRemoteForUser(remoteID, userID) + rc, err := a.Srv().Store().SharedChannel().GetRemoteForUser(remoteID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -135,18 +135,18 @@ func (a *App) GetRemoteClusterForUser(remoteID string, userID string) (*model.Re } func (a *App) UpdateSharedChannelRemoteCursor(id string, cursor model.GetPostsSinceForSyncCursor) error { - return a.Srv().Store.SharedChannel().UpdateRemoteCursor(id, cursor) + return a.Srv().Store().SharedChannel().UpdateRemoteCursor(id, cursor) } func (a *App) DeleteSharedChannelRemote(id string) (bool, error) { - return a.Srv().Store.SharedChannel().DeleteRemote(id) + return a.Srv().Store().SharedChannel().DeleteRemote(id) } func (a *App) GetSharedChannelRemotesStatus(channelID string) ([]*model.SharedChannelRemoteStatus, error) { if err := a.checkChannelIsShared(channelID); err != nil { return nil, err } - return a.Srv().Store.SharedChannel().GetRemotesStatus(channelID) + return a.Srv().Store().SharedChannel().GetRemotesStatus(channelID) } // SharedChannelUsers diff --git a/app/shared_channel_service_iface.go b/app/shared_channel_service_iface.go index 4df47fce08..6cd410a77d 100644 --- a/app/shared_channel_service_iface.go +++ b/app/shared_channel_service_iface.go @@ -3,6 +3,7 @@ package app +// TODO: platform: remove this and use from platform package import ( "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/services/sharedchannel" diff --git a/app/slack.go b/app/slack.go index 0661850f5e..f7baeb53bc 100644 --- a/app/slack.go +++ b/app/slack.go @@ -39,7 +39,7 @@ func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize GenerateThumbnailImage: a.generateThumbnailImage, GeneratePreviewImage: a.generatePreviewImage, InvalidateAllCaches: func() { a.ch.srv.InvalidateAllCaches() }, - MaxPostSize: func() int { return a.ch.srv.MaxPostSize() }, + MaxPostSize: func() int { return a.ch.srv.platform.MaxPostSize() }, PrepareImage: func(fileData []byte) (image.Image, func(), error) { img, release, err := prepareImage(a.ch.imgDecoder, bytes.NewReader(fileData)) if err != nil { @@ -49,13 +49,13 @@ func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize }, } - importer := slackimport.New(a.ch.srv.Store, actions, a.Config()) + importer := slackimport.New(a.Srv().Store(), actions, a.Config()) return importer.SlackImport(c, fileData, fileSize, teamID) } func (a *App) ProcessSlackText(text string) string { text = expandAnnouncement(text) - text = replaceUserIds(a.Srv().Store.User(), text) + text = replaceUserIds(a.Srv().Store().User(), text) return text } diff --git a/app/slashcommands/auto_users.go b/app/slashcommands/auto_users.go index 56f0855845..0fe51f5e28 100644 --- a/app/slashcommands/auto_users.go +++ b/app/slashcommands/auto_users.go @@ -55,11 +55,11 @@ func CreateBasicUser(a *app.App, client *model.Client4) error { if err != nil { return err } - _, err = a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err = a.Srv().Store().User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return model.NewAppError("CreateBasicUser", "app.user.verify_email.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if _, nErr := a.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id, CreateAt: model.GetMillis()}, *a.Config().TeamSettings.MaxUsersPerTeam); nErr != nil { + if _, nErr := a.Srv().Store().Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id, CreateAt: model.GetMillis()}, *a.Config().TeamSettings.MaxUsersPerTeam); nErr != nil { var appErr *model.AppError var conflictErr *store.ErrConflict var limitExceededErr *store.ErrLimitExceeded @@ -100,12 +100,12 @@ func (cfg *AutoUserCreator) createRandomUser(c request.CTX) (*model.User, error) } status := &model.Status{UserId: ruser.Id, Status: model.StatusOnline, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""} - if err := cfg.app.Srv().Store.Status().SaveOrUpdate(status); err != nil { + if err := cfg.app.Srv().Store().Status().SaveOrUpdate(status); err != nil { return nil, err } // We need to cheat to verify the user's email - _, err := cfg.app.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email) + _, err := cfg.app.Srv().Store().User().VerifyEmail(ruser.Id, ruser.Email) if err != nil { return nil, err } diff --git a/app/slashcommands/command_expand_collapse.go b/app/slashcommands/command_expand_collapse.go index 7dfada3d36..87e52ebc1f 100644 --- a/app/slashcommands/command_expand_collapse.go +++ b/app/slashcommands/command_expand_collapse.go @@ -71,7 +71,7 @@ func setCollapsePreference(a *app.App, args *model.CommandArgs, isCollapse bool) Value: strconv.FormatBool(isCollapse), } - if err := a.Srv().Store.Preference().Save(model.Preferences{pref}); err != nil { + if err := a.Srv().Store().Preference().Save(model.Preferences{pref}); err != nil { return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error") + err.Error(), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_groupmsg.go b/app/slashcommands/command_groupmsg.go index 2d57b9bf3b..bb33ccd114 100644 --- a/app/slashcommands/command_groupmsg.go +++ b/app/slashcommands/command_groupmsg.go @@ -49,7 +49,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, c request.CTX, args *model.Comman for _, username := range users { username = strings.TrimSpace(username) username = strings.TrimPrefix(username, "@") - targetUser, nErr := a.Srv().Store.User().GetByUsername(username) + targetUser, nErr := a.Srv().Store().User().GetByUsername(username) if nErr != nil { invalidUsernames = append(invalidUsernames, username) continue diff --git a/app/slashcommands/command_invite.go b/app/slashcommands/command_invite.go index 24c569c8a3..3bf4931324 100644 --- a/app/slashcommands/command_invite.go +++ b/app/slashcommands/command_invite.go @@ -50,7 +50,7 @@ func (*InviteProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandA targetUsername := splitMessage[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, nErr := a.Srv().Store.User().GetByUsername(targetUsername) + userProfile, nErr := a.Srv().Store().User().GetByUsername(targetUsername) if nErr != nil { mlog.Error(nErr.Error()) return &model.CommandResponse{ diff --git a/app/slashcommands/command_join.go b/app/slashcommands/command_join.go index 504d631630..8df9083a8e 100644 --- a/app/slashcommands/command_join.go +++ b/app/slashcommands/command_join.go @@ -44,7 +44,7 @@ func (*JoinProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArg channelName = message[1:] } - channel, err := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true) + channel, err := a.Srv().Store().Channel().GetByName(args.TeamId, channelName, true) if err != nil { return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.CommandResponseTypeEphemeral} } diff --git a/app/slashcommands/command_loadtest.go b/app/slashcommands/command_loadtest.go index 4ca6718446..abe6a36129 100644 --- a/app/slashcommands/command_loadtest.go +++ b/app/slashcommands/command_loadtest.go @@ -248,7 +248,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c request.CTX, args *model.Com c.Logger().Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + UserPassword) } } else { - team, err := a.Srv().Store.Team().Get(args.TeamId) + team, err := a.Srv().Store().Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err } @@ -299,7 +299,7 @@ func (*LoadTestProvider) UsersCommand(a *app.App, c request.CTX, args *model.Com usersr = utils.Range{Begin: 2, End: 5} } - team, err := a.Srv().Store.Team().Get(args.TeamId) + team, err := a.Srv().Store().Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to add users", ResponseType: model.CommandResponseTypeEphemeral}, err } @@ -328,7 +328,7 @@ func (*LoadTestProvider) ChannelsCommand(a *app.App, c request.CTX, args *model. channelsr = utils.Range{Begin: 2, End: 5} } - team, err := a.Srv().Store.Team().Get(args.TeamId) + team, err := a.Srv().Store().Team().Get(args.TeamId) if err != nil { return &model.CommandResponse{Text: "Failed to add channels", ResponseType: model.CommandResponseTypeEphemeral}, err } @@ -361,7 +361,7 @@ func (*LoadTestProvider) DMsCommand(a *app.App, c request.CTX, args *model.Comma func (*LoadTestProvider) ThreadedPostCommand(a *app.App, c request.CTX, args *model.CommandArgs, message string) (*model.CommandResponse, error) { var usernames []string options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000} - if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil { + if profileUsers, err := a.Srv().Store().User().GetProfiles(options); err == nil { usernames = make([]string, len(profileUsers)) i := 0 for _, userprof := range profileUsers { @@ -408,7 +408,7 @@ func (*LoadTestProvider) PostsCommand(a *app.App, c request.CTX, args *model.Com var usernames []string options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000} - if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil { + if profileUsers, err := a.Srv().Store().User().GetProfiles(options); err == nil { usernames = make([]string, len(profileUsers)) i := 0 for _, userprof := range profileUsers { diff --git a/app/slashcommands/command_msg.go b/app/slashcommands/command_msg.go index b801c4a34c..4f4f2c7799 100644 --- a/app/slashcommands/command_msg.go +++ b/app/slashcommands/command_msg.go @@ -52,7 +52,7 @@ func (*msgProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArgs targetUsername = strings.SplitN(message, " ", 2)[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, nErr := a.Srv().Store.User().GetByUsername(targetUsername) + userProfile, nErr := a.Srv().Store().User().GetByUsername(targetUsername) if nErr != nil { mlog.Error(nErr.Error()) return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.CommandResponseTypeEphemeral} @@ -75,7 +75,7 @@ func (*msgProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArgs channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id) targetChannelId := "" - if channel, channelErr := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil { + if channel, channelErr := a.Srv().Store().Channel().GetByName(args.TeamId, channelName, true); channelErr != nil { var nfErr *store.ErrNotFound if errors.As(channelErr, &nfErr) { if !a.HasPermissionTo(args.UserId, model.PermissionCreateDirectChannel) { diff --git a/app/slashcommands/command_mute.go b/app/slashcommands/command_mute.go index 747f86d1e7..0b60c8ff95 100644 --- a/app/slashcommands/command_mute.go +++ b/app/slashcommands/command_mute.go @@ -55,7 +55,7 @@ func (*MuteProvider) DoCommand(a *app.App, c request.CTX, args *model.CommandArg } if channelName != "" && message != "" { - channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true) + channel, _ = a.Srv().Store().Channel().GetByName(channel.TeamId, channelName, true) if channel == nil { return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]any{"Channel": channelName}), ResponseType: model.CommandResponseTypeEphemeral} diff --git a/app/slashcommands/command_remove.go b/app/slashcommands/command_remove.go index 935136f8fe..843eb1ad45 100644 --- a/app/slashcommands/command_remove.go +++ b/app/slashcommands/command_remove.go @@ -108,7 +108,7 @@ func doCommand(a *app.App, c request.CTX, args *model.CommandArgs, message strin targetUsername = strings.SplitN(message, " ", 2)[0] targetUsername = strings.TrimPrefix(targetUsername, "@") - userProfile, nErr := a.Srv().Store.User().GetByUsername(targetUsername) + userProfile, nErr := a.Srv().Store().User().GetByUsername(targetUsername) if nErr != nil { mlog.Error(nErr.Error()) return &model.CommandResponse{ diff --git a/app/slashcommands/command_share_test.go b/app/slashcommands/command_share_test.go index 8a58e44df0..850aba62cf 100644 --- a/app/slashcommands/command_share_test.go +++ b/app/slashcommands/command_share_test.go @@ -33,7 +33,7 @@ func TestShareProviderDoCommand(t *testing.T) { th.Server.SetRemoteClusterService(mockRemoteCluster) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) commandProvider := ShareProvider{} channel := th.CreateChannel(th.BasicTeam, WithShared(false)) @@ -69,7 +69,7 @@ func TestShareProviderDoCommand(t *testing.T) { th.Server.SetRemoteClusterService(mockRemoteCluster) testCluster := &testlib.FakeClusterInterface{} - th.Server.Cluster = testCluster + th.Server.Platform().SetCluster(testCluster) commandProvider := ShareProvider{} channel := th.CreateChannel(th.BasicTeam, WithShared(true)) diff --git a/app/slashcommands/helper_test.go b/app/slashcommands/helper_test.go index ff145921c7..23edc369bd 100644 --- a/app/slashcommands/helper_test.go +++ b/app/slashcommands/helper_test.go @@ -19,7 +19,6 @@ import ( "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mlog" "github.com/mattermost/mattermost-server/v6/store" - "github.com/mattermost/mattermost-server/v6/store/localcachelayer" ) type TestHelper struct { @@ -63,13 +62,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo var options []app.Option options = append(options, app.ConfigStore(memoryStore)) if includeCacheLayer { - options = append(options, app.StoreOverride(func(s *app.Server) store.Store { - lcl, err2 := localcachelayer.NewLocalCacheLayer(dbStore, s.GetMetrics(), s.Cluster, s.CacheProvider) - if err2 != nil { - panic(err2) - } - return lcl - })) + options = append(options, app.StoreOverrideWithCache(dbStore)) } else { options = append(options, app.StoreOverride(dbStore)) } @@ -108,9 +101,9 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) - th.App.Srv().SearchEngine = mainHelper.SearchEngine + th.App.Srv().Platform().SearchEngine = mainHelper.SearchEngine - th.App.Srv().Store.MarkSystemRanUnitTests() + th.App.Srv().Store().MarkSystemRanUnitTests() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) diff --git a/app/status.go b/app/status.go index 21c47ca760..cdbd0759de 100644 --- a/app/status.go +++ b/app/status.go @@ -5,157 +5,16 @@ package app import ( "encoding/json" - "errors" "net/http" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/mlog" - "github.com/mattermost/mattermost-server/v6/store" ) -func (a *App) AddStatusCacheSkipClusterSend(status *model.Status) { - a.Srv().statusCache.Set(status.UserId, status) -} - -func (a *App) AddStatusCache(status *model.Status) { - a.AddStatusCacheSkipClusterSend(status) - - if a.Cluster() != nil { - statusJSON, err := json.Marshal(status) - if err != nil { - a.Log().Warn("Failed to encode status to JSON", mlog.Err(err)) - } - msg := &model.ClusterMessage{ - Event: model.ClusterEventUpdateStatus, - SendType: model.ClusterSendBestEffort, - Data: statusJSON, - } - a.Cluster().SendClusterMessage(msg) - } -} - -func (a *App) GetAllStatuses() map[string]*model.Status { - if !*a.Config().ServiceSettings.EnableUserStatuses { - return map[string]*model.Status{} - } - - statusMap := map[string]*model.Status{} - if userIDs, err := a.Srv().statusCache.Keys(); err == nil { - for _, userID := range userIDs { - status := a.GetStatusFromCache(userID) - if status != nil { - statusMap[userID] = status - } - } - } - return statusMap -} - -func (a *App) GetStatusesByIds(userIDs []string) (map[string]any, *model.AppError) { - if !*a.Config().ServiceSettings.EnableUserStatuses { - return map[string]any{}, nil - } - - statusMap := map[string]any{} - metrics := a.Metrics() - - missingUserIds := []string{} - for _, userID := range userIDs { - var status *model.Status - if err := a.Srv().statusCache.Get(userID, &status); err == nil { - statusMap[userID] = status.Status - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Status") - } - } else { - missingUserIds = append(missingUserIds, userID) - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Status") - } - } - } - - if len(missingUserIds) > 0 { - statuses, err := a.Srv().Store.Status().GetByIds(missingUserIds) - if err != nil { - return nil, model.NewAppError("GetStatusesByIds", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - for _, s := range statuses { - a.AddStatusCacheSkipClusterSend(s) - statusMap[s.UserId] = s.Status - } - - } - - // For the case where the user does not have a row in the Status table and cache - for _, userID := range missingUserIds { - if _, ok := statusMap[userID]; !ok { - statusMap[userID] = model.StatusOffline - } - } - - return statusMap, nil -} - // GetUserStatusesByIds used by apiV4 func (a *App) GetUserStatusesByIds(userIDs []string) ([]*model.Status, *model.AppError) { - if !*a.Config().ServiceSettings.EnableUserStatuses { - return []*model.Status{}, nil - } - - var statusMap []*model.Status - metrics := a.Metrics() - - missingUserIds := []string{} - for _, userID := range userIDs { - var status *model.Status - if err := a.Srv().statusCache.Get(userID, &status); err == nil { - statusMap = append(statusMap, status) - if metrics != nil { - metrics.IncrementMemCacheHitCounter("Status") - } - } else { - missingUserIds = append(missingUserIds, userID) - if metrics != nil { - metrics.IncrementMemCacheMissCounter("Status") - } - } - } - - if len(missingUserIds) > 0 { - statuses, err := a.Srv().Store.Status().GetByIds(missingUserIds) - if err != nil { - return nil, model.NewAppError("GetUserStatusesByIds", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - - for _, s := range statuses { - a.AddStatusCacheSkipClusterSend(s) - } - - statusMap = append(statusMap, statuses...) - - } - - // For the case where the user does not have a row in the Status table and cache - // remove the existing ids from missingUserIds and then create a offline state for the missing ones - // This also return the status offline for the non-existing Ids in the system - for i := 0; i < len(missingUserIds); i++ { - missingUserId := missingUserIds[i] - for _, userMap := range statusMap { - if missingUserId == userMap.UserId { - missingUserIds = append(missingUserIds[:i], missingUserIds[i+1:]...) - i-- - break - } - } - } - for _, userID := range missingUserIds { - statusMap = append(statusMap, &model.Status{UserId: userID, Status: "offline"}) - } - - return statusMap, nil + return a.Srv().Platform().GetUserStatusesByIds(userIDs) } // SetStatusLastActivityAt sets the last activity at for a user on the local app server and updates @@ -170,7 +29,7 @@ func (a *App) SetStatusLastActivityAt(userID string, activityAt int64) { status.LastActivityAt = activityAt - a.AddStatusCacheSkipClusterSend(status) + a.Srv().Platform().AddStatusCacheSkipClusterSend(status) a.SetStatusAwayIfNeeded(userID, false) } @@ -208,38 +67,27 @@ func (a *App) SetStatusOnline(userID string, manual bool) { status.LastActivityAt = model.GetMillis() } - a.AddStatusCache(status) + a.Srv().Platform().AddStatusCache(status) // Only update the database if the status has changed, the status has been manually set, // or enough time has passed since the previous action if status.Status != oldStatus || status.Manual != oldManual || status.LastActivityAt-oldTime > model.StatusMinUpdateTime { if broadcast { - if err := a.Srv().Store.Status().SaveOrUpdate(status); err != nil { + if err := a.Srv().Store().Status().SaveOrUpdate(status); err != nil { mlog.Warn("Failed to save status", mlog.String("user_id", userID), mlog.Err(err), mlog.String("user_id", userID)) } } else { - if err := a.Srv().Store.Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt); err != nil { + if err := a.Srv().Store().Status().UpdateLastActivityAt(status.UserId, status.LastActivityAt); err != nil { mlog.Error("Failed to save status", mlog.String("user_id", userID), mlog.Err(err), mlog.String("user_id", userID)) } } } if broadcast { - a.BroadcastStatus(status) + a.Srv().Platform().BroadcastStatus(status) } } -func (a *App) BroadcastStatus(status *model.Status) { - if a.Srv().Busy.IsBusy() { - // this is considered a non-critical service and will be disabled when server busy. - return - } - event := model.NewWebSocketEvent(model.WebsocketEventStatusChange, "", "", status.UserId, nil, "") - event.Add("status", status.Status) - event.Add("user_id", status.UserId) - a.Publish(event) -} - func (a *App) SetStatusOffline(userID string, manual bool) { if !*a.Config().ServiceSettings.EnableUserStatuses { return @@ -252,7 +100,7 @@ func (a *App) SetStatusOffline(userID string, manual bool) { status = &model.Status{UserId: userID, Status: model.StatusOffline, Manual: manual, LastActivityAt: model.GetMillis(), ActiveChannel: ""} - a.SaveAndBroadcastStatus(status) + a.Srv().Platform().SaveAndBroadcastStatus(status) } func (a *App) SetStatusAwayIfNeeded(userID string, manual bool) { @@ -284,7 +132,7 @@ func (a *App) SetStatusAwayIfNeeded(userID string, manual bool) { status.Manual = manual status.ActiveChannel = "" - a.SaveAndBroadcastStatus(status) + a.Srv().Platform().SaveAndBroadcastStatus(status) } // SetStatusDoNotDisturbTimed takes endtime in unix epoch format in UTC @@ -306,7 +154,7 @@ func (a *App) SetStatusDoNotDisturbTimed(userId string, endtime int64) { status.DNDEndTime = endtime - a.SaveAndBroadcastStatus(status) + a.Srv().Platform().SaveAndBroadcastStatus(status) } func (a *App) SetStatusDoNotDisturb(userID string) { @@ -323,17 +171,7 @@ func (a *App) SetStatusDoNotDisturb(userID string) { status.Status = model.StatusDnd status.Manual = true - a.SaveAndBroadcastStatus(status) -} - -func (a *App) SaveAndBroadcastStatus(status *model.Status) { - a.AddStatusCache(status) - - if err := a.Srv().Store.Status().SaveOrUpdate(status); err != nil { - mlog.Warn("Failed to save status", mlog.String("user_id", status.UserId), mlog.Err(err)) - } - - a.BroadcastStatus(status) + a.Srv().Platform().SaveAndBroadcastStatus(status) } func (a *App) SetStatusOutOfOffice(userID string) { @@ -350,42 +188,15 @@ func (a *App) SetStatusOutOfOffice(userID string) { status.Status = model.StatusOutOfOffice status.Manual = true - a.SaveAndBroadcastStatus(status) + a.Srv().Platform().SaveAndBroadcastStatus(status) } func (a *App) GetStatusFromCache(userID string) *model.Status { - var status *model.Status - if err := a.Srv().statusCache.Get(userID, &status); err == nil { - statusCopy := &model.Status{} - *statusCopy = *status - return statusCopy - } - - return nil + return a.Srv().Platform().GetStatusFromCache(userID) } func (a *App) GetStatus(userID string) (*model.Status, *model.AppError) { - if !*a.Config().ServiceSettings.EnableUserStatuses { - return &model.Status{}, nil - } - - status := a.GetStatusFromCache(userID) - if status != nil { - return status, nil - } - - status, err := a.Srv().Store.Status().Get(userID) - if err != nil { - var nfErr *store.ErrNotFound - switch { - case errors.As(err, &nfErr): - return nil, model.NewAppError("GetStatus", "app.status.get.missing.app_error", nil, "", http.StatusNotFound).Wrap(err) - default: - return nil, model.NewAppError("GetStatus", "app.status.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) - } - } - - return status, nil + return a.Srv().Platform().GetStatus(userID) } func (a *App) IsUserAway(lastActivityAt int64) bool { @@ -401,8 +212,8 @@ func (a *App) UpdateDNDStatusOfUsers() { return } for i := range statuses { - a.AddStatusCache(statuses[i]) - a.BroadcastStatus(statuses[i]) + a.Srv().Platform().AddStatusCache(statuses[i]) + a.Srv().Platform().BroadcastStatus(statuses[i]) } } diff --git a/app/status_test.go b/app/status_test.go index 81ef4cebc4..42d97ea3e6 100644 --- a/app/status_test.go +++ b/app/status_test.go @@ -15,33 +15,6 @@ import ( "github.com/mattermost/mattermost-server/v6/store/storetest/mocks" ) -func TestSaveStatus(t *testing.T) { - th := Setup(t).InitBasic() - defer th.TearDown() - - user := th.BasicUser - - for _, statusString := range []string{ - model.StatusOnline, - model.StatusAway, - model.StatusDnd, - model.StatusOffline, - } { - t.Run(statusString, func(t *testing.T) { - status := &model.Status{ - UserId: user.Id, - Status: statusString, - } - - th.App.SaveAndBroadcastStatus(status) - - after, err := th.App.GetStatus(user.Id) - require.Nil(t, err, "failed to get status after save: %v", err) - require.Equal(t, statusString, after.Status, "failed to save status, got %v, expected %v", after.Status, statusString) - }) - } -} - func TestCustomStatus(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() diff --git a/app/support_packet.go b/app/support_packet.go index 9b91471f02..84236c7daf 100644 --- a/app/support_packet.go +++ b/app/support_packet.go @@ -58,9 +58,9 @@ func (a *App) generateSupportPacketYaml() (*model.FileData, string) { // Here we are getting information regarding Elastic Search var elasticServerVersion string var elasticServerPlugins []string - if a.Srv().SearchEngine.ElasticsearchEngine != nil { - elasticServerVersion = a.Srv().SearchEngine.ElasticsearchEngine.GetFullVersion() - elasticServerPlugins = a.Srv().SearchEngine.ElasticsearchEngine.GetPlugins() + if a.Srv().Platform().SearchEngine.ElasticsearchEngine != nil { + elasticServerVersion = a.Srv().Platform().SearchEngine.ElasticsearchEngine.GetFullVersion() + elasticServerPlugins = a.Srv().Platform().SearchEngine.ElasticsearchEngine.GetPlugins() } // Here we are getting information regarding LDAP @@ -73,7 +73,7 @@ func (a *App) generateSupportPacketYaml() (*model.FileData, string) { // Here we are getting information regarding the database (mysql/postgres + current schema version) databaseType, databaseVersion := a.Srv().DatabaseTypeAndSchemaVersion() - uniqueUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) + uniqueUserCount, err := a.Srv().Store().User().Count(model.UserCountOptions{}) if err != nil { return nil, errors.Wrap(err, "error while getting user count").Error() } diff --git a/app/syncables.go b/app/syncables.go index ed8806f7cd..cc87edc8ee 100644 --- a/app/syncables.go +++ b/app/syncables.go @@ -202,7 +202,7 @@ func (a *App) deleteGroupConstrainedChannelMemberships(c request.CTX, channelID // the member's group memberships and the configuration of those groups to the syncable. This method should only // be invoked on group-synced (aka group-constrained) syncables. func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSyncableType) *model.AppError { - permittedAdmins, err := a.Srv().Store.Group().PermittedSyncableAdmins(syncableID, syncableType) + permittedAdmins, err := a.Srv().Store().Group().PermittedSyncableAdmins(syncableID, syncableType) if err != nil { return model.NewAppError("SyncSyncableRoles", "app.select_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -215,13 +215,13 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca switch syncableType { case model.GroupSyncableTypeTeam: - nErr := a.Srv().Store.Team().UpdateMembersRole(syncableID, permittedAdmins) + nErr := a.Srv().Store().Team().UpdateMembersRole(syncableID, permittedAdmins) if nErr != nil { return model.NewAppError("App.SyncSyncableRoles", "app.update_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } return nil case model.GroupSyncableTypeChannel: - nErr := a.Srv().Store.Channel().UpdateMembersRole(syncableID, permittedAdmins) + nErr := a.Srv().Store().Channel().UpdateMembersRole(syncableID, permittedAdmins) if nErr != nil { return model.NewAppError("App.SyncSyncableRoles", "app.update_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -236,7 +236,7 @@ func (a *App) SyncSyncableRoles(syncableID string, syncableType model.GroupSynca func (a *App) SyncRolesAndMembership(c request.CTX, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool) { a.SyncSyncableRoles(syncableID, syncableType) - lastJob, _ := a.Srv().Store.Job().GetNewestJobByStatusAndType(model.JobStatusSuccess, model.JobTypeLdapSync) + lastJob, _ := a.Srv().Store().Job().GetNewestJobByStatusAndType(model.JobStatusSuccess, model.JobTypeLdapSync) var since int64 if lastJob != nil { since = lastJob.StartAt diff --git a/app/syncables_test.go b/app/syncables_test.go index 6947af7342..d78d46f1d2 100644 --- a/app/syncables_test.go +++ b/app/syncables_test.go @@ -298,7 +298,7 @@ func TestCreateDefaultMemberships(t *testing.T) { timeAfterLeaving := model.GetMillis() + 1 // Purging channelmemberhistory doesn't re-add user to channel - deletedCount, _, nErr := th.App.Srv().Store.ChannelMemberHistory().PermanentDeleteBatchForRetentionPolicies( + deletedCount, _, nErr := th.App.Srv().Store().ChannelMemberHistory().PermanentDeleteBatchForRetentionPolicies( 0, timeBeforeLeaving, 1000, model.RetentionPolicyCursor{}) if nErr != nil { t.Errorf("error permanently deleting channelmemberhistory: %s", nErr.Error()) @@ -316,7 +316,7 @@ func TestCreateDefaultMemberships(t *testing.T) { } // Purging channelmemberhistory doesn't re-add user to channel - deletedCount, _, nErr = th.App.Srv().Store.ChannelMemberHistory().PermanentDeleteBatchForRetentionPolicies( + deletedCount, _, nErr = th.App.Srv().Store().ChannelMemberHistory().PermanentDeleteBatchForRetentionPolicies( 0, timeAfterLeaving, 1000, model.RetentionPolicyCursor{}) if nErr != nil { t.Errorf("error permanently deleting channelmemberhistory: %s", nErr.Error()) diff --git a/app/team.go b/app/team.go index 25f7ae9664..fc69fbb652 100644 --- a/app/team.go +++ b/app/team.go @@ -289,7 +289,7 @@ func (a *App) UpdateTeamScheme(team *model.Team) (*model.Team, *model.AppError) oldTeam.SchemeId = team.SchemeId - oldTeam, nErr := a.Srv().Store.Team().Update(oldTeam) + oldTeam, nErr := a.Srv().Store().Team().Update(oldTeam) if nErr != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -329,7 +329,7 @@ func (a *App) UpdateTeamPrivacy(teamID string, teamType string, allowOpenInvite oldTeam.Type = teamType oldTeam.AllowOpenInvite = allowOpenInvite - oldTeam, nErr := a.Srv().Store.Team().Update(oldTeam) + oldTeam, nErr := a.Srv().Store().Team().Update(oldTeam) if nErr != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -386,7 +386,7 @@ func (a *App) RegenerateTeamInviteId(teamID string) (*model.Team, *model.AppErro team.InviteId = model.NewId() - updatedTeam, nErr := a.Srv().Store.Team().Update(team) + updatedTeam, nErr := a.Srv().Store().Team().Update(team) if nErr != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -445,7 +445,7 @@ func (a *App) GetSchemeRolesForTeam(teamID string) (string, string, string, *mod } func (a *App) UpdateTeamMemberRoles(teamID string, userID string, newRoles string) (*model.TeamMember, *model.AppError) { - member, nErr := a.Srv().Store.Team().GetMember(context.Background(), teamID, userID) + member, nErr := a.Srv().Store().Team().GetMember(context.Background(), teamID, userID) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -508,7 +508,7 @@ func (a *App) UpdateTeamMemberRoles(teamID string, userID string, newRoles strin member.ExplicitRoles = strings.Join(newExplicitRoles, " ") - member, nErr = a.Srv().Store.Team().UpdateMember(member) + member, nErr = a.Srv().Store().Team().UpdateMember(member) if nErr != nil { var appErr *model.AppError switch { @@ -547,7 +547,7 @@ func (a *App) UpdateTeamMemberSchemeRoles(teamID string, userID string, isScheme member.ExplicitRoles = RemoveRoles([]string{model.TeamGuestRoleId, model.TeamUserRoleId, model.TeamAdminRoleId}, member.ExplicitRoles) } - member, nErr := a.Srv().Store.Team().UpdateMember(member) + member, nErr := a.Srv().Store().Team().UpdateMember(member) if nErr != nil { var appErr *model.AppError switch { @@ -581,14 +581,14 @@ func (a *App) sendUpdatedMemberRoleEvent(userID string, member *model.TeamMember func (a *App) AddUserToTeam(c request.CTX, teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(teamID) + team, err := a.Srv().Store().Team().Get(teamID) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -626,7 +626,7 @@ func (a *App) AddUserToTeam(c request.CTX, teamID string, userID string, userReq } func (a *App) AddUserToTeamByTeamId(c *request.Context, teamID string, user *model.User) *model.AppError { - team, err := a.Srv().Store.Team().Get(teamID) + team, err := a.Srv().Store().Team().Get(teamID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -644,7 +644,7 @@ func (a *App) AddUserToTeamByTeamId(c *request.Context, teamID string, user *mod } func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError) { - token, err := a.Srv().Store.Token().GetByToken(tokenID) + token, err := a.Srv().Store().Token().GetByToken(tokenID) if err != nil { return nil, nil, model.NewAppError("AddUserToTeamByToken", "api.user.create_user.signup_link_invalid.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -662,14 +662,14 @@ func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID st tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(tokenData["teamId"]) + team, err := a.Srv().Store().Team().Get(tokenData["teamId"]) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -715,7 +715,7 @@ func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID st } if token.Type == TokenTypeGuestInvitation { - channels, err := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false) + channels, err := a.Srv().Store().Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false) if err != nil { return nil, nil, model.NewAppError("AddUserToTeamByToken", "app.channel.get_channels_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -738,14 +738,14 @@ func (a *App) AddUserToTeamByToken(c *request.Context, userID string, tokenID st func (a *App) AddUserToTeamByInviteId(c *request.Context, inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store().Team().GetByInviteId(inviteId) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -809,7 +809,7 @@ func (a *App) JoinUserToTeam(c request.CTX, team *model.Team, user *model.User, return teamMember, nil } - if _, err := a.Srv().Store.User().UpdateUpdateAt(user.Id); err != nil { + if _, err := a.Srv().Store().User().UpdateUpdateAt(user.Id); err != nil { return nil, model.NewAppError("JoinUserToTeam", "app.user.update_update.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -898,7 +898,7 @@ func (a *App) GetTeams(teamIDs []string) ([]*model.Team, *model.AppError) { } func (a *App) GetTeamByName(name string) (*model.Team, *model.AppError) { - team, err := a.Srv().Store.Team().GetByName(name) + team, err := a.Srv().Store().Team().GetByName(name) if err != nil { var nfErr *store.ErrNotFound switch { @@ -913,7 +913,7 @@ func (a *App) GetTeamByName(name string) (*model.Team, *model.AppError) { } func (a *App) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) { - team, err := a.Srv().Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store().Team().GetByInviteId(inviteId) if err != nil { var nfErr *store.ErrNotFound switch { @@ -928,7 +928,7 @@ func (a *App) GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError) } func (a *App) GetAllTeams() ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().GetAll() + teams, err := a.Srv().Store().Team().GetAll() if err != nil { return nil, model.NewAppError("GetAllTeams", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -937,7 +937,7 @@ func (a *App) GetAllTeams() ([]*model.Team, *model.AppError) { } func (a *App) GetAllTeamsPage(offset int, limit int, opts *model.TeamSearch) ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().GetAllPage(offset, limit, opts) + teams, err := a.Srv().Store().Team().GetAllPage(offset, limit, opts) if err != nil { return nil, model.NewAppError("GetAllTeamsPage", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -946,11 +946,11 @@ func (a *App) GetAllTeamsPage(offset int, limit int, opts *model.TeamSearch) ([] } func (a *App) GetAllTeamsPageWithCount(offset int, limit int, opts *model.TeamSearch) (*model.TeamsWithCount, *model.AppError) { - totalCount, err := a.Srv().Store.Team().AnalyticsTeamCount(opts) + totalCount, err := a.Srv().Store().Team().AnalyticsTeamCount(opts) if err != nil { return nil, model.NewAppError("GetAllTeamsPageWithCount", "app.team.analytics_team_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - teams, err := a.Srv().Store.Team().GetAllPage(offset, limit, opts) + teams, err := a.Srv().Store().Team().GetAllPage(offset, limit, opts) if err != nil { return nil, model.NewAppError("GetAllTeamsPageWithCount", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -958,7 +958,7 @@ func (a *App) GetAllTeamsPageWithCount(offset int, limit int, opts *model.TeamSe } func (a *App) GetAllPrivateTeams() ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().GetAllPrivateTeamListing() + teams, err := a.Srv().Store().Team().GetAllPrivateTeamListing() if err != nil { return nil, model.NewAppError("GetAllPrivateTeams", "app.team.get_all_private_team_listing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -967,7 +967,7 @@ func (a *App) GetAllPrivateTeams() ([]*model.Team, *model.AppError) { } func (a *App) GetAllPublicTeams() ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().GetAllTeamListing() + teams, err := a.Srv().Store().Team().GetAllTeamListing() if err != nil { return nil, model.NewAppError("GetAllPublicTeams", "app.team.get_all_team_listing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -978,14 +978,14 @@ func (a *App) GetAllPublicTeams() ([]*model.Team, *model.AppError) { // SearchAllTeams returns a team list and the total count of the results func (a *App) SearchAllTeams(searchOpts *model.TeamSearch) ([]*model.Team, int64, *model.AppError) { if searchOpts.IsPaginated() { - teams, count, err := a.Srv().Store.Team().SearchAllPaged(searchOpts) + teams, count, err := a.Srv().Store().Team().SearchAllPaged(searchOpts) if err != nil { return nil, 0, model.NewAppError("SearchAllTeams", "app.team.search_all_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } return teams, count, nil } - results, err := a.Srv().Store.Team().SearchAll(searchOpts) + results, err := a.Srv().Store().Team().SearchAll(searchOpts) if err != nil { return nil, 0, model.NewAppError("SearchAllTeams", "app.team.search_all_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -993,7 +993,7 @@ func (a *App) SearchAllTeams(searchOpts *model.TeamSearch) ([]*model.Team, int64 } func (a *App) SearchPublicTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().SearchOpen(searchOpts) + teams, err := a.Srv().Store().Team().SearchOpen(searchOpts) if err != nil { return nil, model.NewAppError("SearchPublicTeams", "app.team.search_open_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1002,7 +1002,7 @@ func (a *App) SearchPublicTeams(searchOpts *model.TeamSearch) ([]*model.Team, *m } func (a *App) SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().SearchPrivate(searchOpts) + teams, err := a.Srv().Store().Team().SearchPrivate(searchOpts) if err != nil { return nil, model.NewAppError("SearchPrivateTeams", "app.team.search_private_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1011,7 +1011,7 @@ func (a *App) SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, * } func (a *App) GetTeamsForUser(userID string) ([]*model.Team, *model.AppError) { - teams, err := a.Srv().Store.Team().GetTeamsByUserId(userID) + teams, err := a.Srv().Store().Team().GetTeamsByUserId(userID) if err != nil { return nil, model.NewAppError("GetTeamsForUser", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1020,7 +1020,7 @@ func (a *App) GetTeamsForUser(userID string) ([]*model.Team, *model.AppError) { } func (a *App) GetTeamMember(teamID, userID string) (*model.TeamMember, *model.AppError) { - teamMember, err := a.Srv().Store.Team().GetMember(sqlstore.WithMaster(context.Background()), teamID, userID) + teamMember, err := a.Srv().Store().Team().GetMember(sqlstore.WithMaster(context.Background()), teamID, userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -1035,7 +1035,7 @@ func (a *App) GetTeamMember(teamID, userID string) (*model.TeamMember, *model.Ap } func (a *App) GetTeamMembersForUser(userID string, excludeTeamID string, includeDeleted bool) ([]*model.TeamMember, *model.AppError) { - teamMembers, err := a.Srv().Store.Team().GetTeamsForUser(context.Background(), userID, excludeTeamID, includeDeleted) + teamMembers, err := a.Srv().Store().Team().GetTeamsForUser(context.Background(), userID, excludeTeamID, includeDeleted) if err != nil { return nil, model.NewAppError("GetTeamMembersForUser", "app.team.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1044,7 +1044,7 @@ func (a *App) GetTeamMembersForUser(userID string, excludeTeamID string, include } func (a *App) GetTeamMembersForUserWithPagination(userID string, page, perPage int) ([]*model.TeamMember, *model.AppError) { - teamMembers, err := a.Srv().Store.Team().GetTeamsForUserWithPagination(userID, page, perPage) + teamMembers, err := a.Srv().Store().Team().GetTeamsForUserWithPagination(userID, page, perPage) if err != nil { return nil, model.NewAppError("GetTeamMembersForUserWithPagination", "app.team.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1053,7 +1053,7 @@ func (a *App) GetTeamMembersForUserWithPagination(userID string, page, perPage i } func (a *App) GetTeamMembers(teamID string, offset int, limit int, teamMembersGetOptions *model.TeamMembersGetOptions) ([]*model.TeamMember, *model.AppError) { - teamMembers, err := a.Srv().Store.Team().GetMembers(teamID, offset, limit, teamMembersGetOptions) + teamMembers, err := a.Srv().Store().Team().GetMembers(teamID, offset, limit, teamMembersGetOptions) if err != nil { return nil, model.NewAppError("GetTeamMembers", "app.team.get_members.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1062,7 +1062,7 @@ func (a *App) GetTeamMembers(teamID string, offset int, limit int, teamMembersGe } func (a *App) GetTeamMembersByIds(teamID string, userIDs []string, restrictions *model.ViewUsersRestrictions) ([]*model.TeamMember, *model.AppError) { - teamMembers, err := a.Srv().Store.Team().GetMembersByIds(teamID, userIDs, restrictions) + teamMembers, err := a.Srv().Store().Team().GetMembersByIds(teamID, userIDs, restrictions) if err != nil { return nil, model.NewAppError("GetTeamMembersByIds", "app.team.get_members_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1071,7 +1071,7 @@ func (a *App) GetTeamMembersByIds(teamID string, userIDs []string, restrictions } func (a *App) GetCommonTeamIDsForTwoUsers(userID, otherUserID string) ([]string, *model.AppError) { - teamIDs, err := a.Srv().Store.Team().GetCommonTeamIDsForTwoUsers(userID, otherUserID) + teamIDs, err := a.Srv().Store().Team().GetCommonTeamIDsForTwoUsers(userID, otherUserID) if err != nil { return nil, model.NewAppError("GetCommonTeamIDsForUsers", "app.team.get_common_team_ids_for_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1145,7 +1145,7 @@ func (a *App) AddTeamMemberByInviteId(c *request.Context, inviteId, userID strin } func (a *App) GetTeamUnread(teamID, userID string) (*model.TeamUnread, *model.AppError) { - channelUnreads, err := a.Srv().Store.Team().GetChannelUnreadsForTeam(teamID, userID) + channelUnreads, err := a.Srv().Store().Team().GetChannelUnreadsForTeam(teamID, userID) if err != nil { return nil, model.NewAppError("GetTeamUnread", "app.team.get_unread.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -1174,14 +1174,14 @@ func (a *App) GetTeamUnread(teamID, userID string) (*model.TeamUnread, *model.Ap func (a *App) RemoveUserFromTeam(c request.CTX, teamID string, userID string, requestorId string) *model.AppError { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(teamID) + team, err := a.Srv().Store().Team().Get(teamID) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), userID) + user, err := a.Srv().Store().User().Get(context.Background(), userID) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -1233,7 +1233,7 @@ func (a *App) postProcessTeamMemberLeave(c request.CTX, teamMember *model.TeamMe }) } - user, nErr := a.Srv().Store.User().Get(context.Background(), teamMember.UserId) + user, nErr := a.Srv().Store().User().Get(context.Background(), teamMember.UserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -1244,16 +1244,16 @@ func (a *App) postProcessTeamMemberLeave(c request.CTX, teamMember *model.TeamMe } } - if _, err := a.Srv().Store.User().UpdateUpdateAt(user.Id); err != nil { + if _, err := a.Srv().Store().User().UpdateUpdateAt(user.Id); err != nil { return model.NewAppError("postProcessTeamMemberLeave", "app.user.update_update.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Channel().ClearSidebarOnTeamLeave(user.Id, teamMember.TeamId); err != nil { + if err := a.Srv().Store().Channel().ClearSidebarOnTeamLeave(user.Id, teamMember.TeamId); err != nil { return model.NewAppError("postProcessTeamMemberLeave", "app.channel.sidebar_categories.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } // delete the preferences that set the last channel used in the team and other team specific preferences - if err := a.Srv().Store.Preference().DeleteCategory(user.Id, teamMember.TeamId); err != nil { + if err := a.Srv().Store().Preference().DeleteCategory(user.Id, teamMember.TeamId); err != nil { return model.NewAppError("postProcessTeamMemberLeave", "app.preference.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1272,7 +1272,7 @@ func (a *App) LeaveTeam(c request.CTX, team *model.Team, user *model.User, reque var channelList model.ChannelList var nErr error - if channelList, nErr = a.Srv().Store.Channel().GetChannels(team.Id, user.Id, &model.ChannelSearchOpts{ + if channelList, nErr = a.Srv().Store().Channel().GetChannels(team.Id, user.Id, &model.ChannelSearchOpts{ IncludeDeleted: true, LastDeleteAt: 0, }); nErr != nil { @@ -1287,14 +1287,14 @@ func (a *App) LeaveTeam(c request.CTX, team *model.Team, user *model.User, reque for _, channel := range channelList { if !channel.IsGroupOrDirect() { a.invalidateCacheForChannelMembers(channel.Id) - if nErr = a.Srv().Store.Channel().RemoveMember(channel.Id, user.Id); nErr != nil { + if nErr = a.Srv().Store().Channel().RemoveMember(channel.Id, user.Id); nErr != nil { return model.NewAppError("LeaveTeam", "app.channel.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } } } if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages { - channel, cErr := a.Srv().Store.Channel().GetByName(team.Id, model.DefaultChannelName, false) + channel, cErr := a.Srv().Store().Channel().GetByName(team.Id, model.DefaultChannelName, false) if cErr != nil { var nfErr *store.ErrNotFound switch { @@ -1366,14 +1366,14 @@ func (a *App) postRemoveFromTeamMessage(c request.CTX, user *model.User, channel func (a *App) prepareInviteNewUsersToTeam(teamID, senderId string, channelIds []string) (*model.User, *model.Team, []*model.Channel, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(teamID) + team, err := a.Srv().Store().Team().Get(teamID) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), senderId) + user, err := a.Srv().Store().User().Get(context.Background(), senderId) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -1381,7 +1381,7 @@ func (a *App) prepareInviteNewUsersToTeam(teamID, senderId string, channelIds [] var channels []*model.Channel var err error if len(channelIds) > 0 { - channels, err = a.Srv().Store.Channel().GetChannelsByIds(channelIds, false) + channels, err = a.Srv().Store().Channel().GetChannelsByIds(channelIds, false) if err != nil { return nil, nil, nil, model.NewAppError("prepareInviteNewUsersToTeam", "app.channel.get_channels_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1501,19 +1501,19 @@ func (a *App) prepareInviteGuestsToChannels(teamID string, guestsInvite *model.G tchan := make(chan store.StoreResult, 1) go func() { - team, err := a.Srv().Store.Team().Get(teamID) + team, err := a.Srv().Store().Team().Get(teamID) tchan <- store.StoreResult{Data: team, NErr: err} close(tchan) }() cchan := make(chan store.StoreResult, 1) go func() { - channels, err := a.Srv().Store.Channel().GetChannelsByIds(guestsInvite.Channels, false) + channels, err := a.Srv().Store().Channel().GetChannelsByIds(guestsInvite.Channels, false) cchan <- store.StoreResult{Data: channels, NErr: err} close(cchan) }() uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), senderId) + user, err := a.Srv().Store().User().Get(context.Background(), senderId) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -1702,14 +1702,14 @@ func (a *App) InviteGuestsToChannels(teamID string, guestsInvite *model.GuestsIn } func (a *App) FindTeamByName(name string) bool { - if _, err := a.Srv().Store.Team().GetByName(name); err != nil { + if _, err := a.Srv().Store().Team().GetByName(name); err != nil { return false } return true } func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userID string, includeCollapsedThreads bool) ([]*model.TeamUnread, *model.AppError) { - data, err := a.Srv().Store.Team().GetChannelUnreadsForAllTeams(excludeTeamId, userID) + data, err := a.Srv().Store().Team().GetChannelUnreadsForAllTeams(excludeTeamId, userID) if err != nil { return nil, model.NewAppError("GetTeamsUnreadForUser", "app.team.get_unread.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1751,7 +1751,7 @@ func (a *App) GetTeamsUnreadForUser(excludeTeamId string, userID string, include includeCollapsedThreads = includeCollapsedThreads && *a.Config().ServiceSettings.CollapsedThreads != model.CollapsedThreadsDisabled if includeCollapsedThreads { - teamUnreads, err := a.Srv().Store.Thread().GetTeamsUnreadForUser(userID, teamIDs) + teamUnreads, err := a.Srv().Store().Thread().GetTeamsUnreadForUser(userID, teamIDs) if err != nil { return nil, model.NewAppError("GetTeamsUnreadForUser", "app.team.get_unread.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1780,7 +1780,7 @@ func (a *App) PermanentDeleteTeamId(c request.CTX, teamID string) *model.AppErro func (a *App) PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppError { team.DeleteAt = model.GetMillis() - if _, err := a.Srv().Store.Team().Update(team); err != nil { + if _, err := a.Srv().Store().Team().Update(team); err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError switch { @@ -1793,7 +1793,7 @@ func (a *App) PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppErr } } - if channels, err := a.Srv().Store.Channel().GetTeamChannels(team.Id); err != nil { + if channels, err := a.Srv().Store().Channel().GetTeamChannels(team.Id); err != nil { var nfErr *store.ErrNotFound if !errors.As(err, &nfErr) { return model.NewAppError("PermanentDeleteTeam", "app.channel.get_channels.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -1804,15 +1804,15 @@ func (a *App) PermanentDeleteTeam(c request.CTX, team *model.Team) *model.AppErr } } - if err := a.Srv().Store.Team().RemoveAllMembersByTeam(team.Id); err != nil { + if err := a.Srv().Store().Team().RemoveAllMembersByTeam(team.Id); err != nil { return model.NewAppError("PermanentDeleteTeam", "app.team.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Command().PermanentDeleteByTeam(team.Id); err != nil { + if err := a.Srv().Store().Command().PermanentDeleteByTeam(team.Id); err != nil { return model.NewAppError("PermanentDeleteTeam", "app.team.permanentdeleteteam.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Team().PermanentDelete(team.Id); err != nil { + if err := a.Srv().Store().Team().PermanentDelete(team.Id); err != nil { return model.NewAppError("PermanentDeleteTeam", "app.team.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1830,7 +1830,7 @@ func (a *App) SoftDeleteTeam(teamID string) *model.AppError { } team.DeleteAt = model.GetMillis() - team, nErr := a.Srv().Store.Team().Update(team) + team, nErr := a.Srv().Store().Team().Update(team) if nErr != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -1858,7 +1858,7 @@ func (a *App) RestoreTeam(teamID string) *model.AppError { } team.DeleteAt = 0 - team, nErr := a.Srv().Store.Team().Update(team) + team, nErr := a.Srv().Store().Team().Update(team) if nErr != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -1882,13 +1882,13 @@ func (a *App) RestoreTeam(teamID string) *model.AppError { func (a *App) GetTeamStats(teamID string, restrictions *model.ViewUsersRestrictions) (*model.TeamStats, *model.AppError) { tchan := make(chan store.StoreResult, 1) go func() { - totalMemberCount, err := a.Srv().Store.Team().GetTotalMemberCount(teamID, restrictions) + totalMemberCount, err := a.Srv().Store().Team().GetTotalMemberCount(teamID, restrictions) tchan <- store.StoreResult{Data: totalMemberCount, NErr: err} close(tchan) }() achan := make(chan store.StoreResult, 1) go func() { - memberCount, err := a.Srv().Store.Team().GetActiveMemberCount(teamID, restrictions) + memberCount, err := a.Srv().Store().Team().GetActiveMemberCount(teamID, restrictions) achan <- store.StoreResult{Data: memberCount, NErr: err} close(achan) }() @@ -1916,7 +1916,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { inviteId := query.Get("id") if tokenID != "" { - token, err := a.Srv().Store.Token().GetByToken(tokenID) + token, err := a.Srv().Store().Token().GetByToken(tokenID) if err != nil { return "", model.NewAppError("GetTeamIdFromQuery", "api.oauth.singup_with_oauth.invalid_link.app_error", nil, "", http.StatusBadRequest) } @@ -1935,7 +1935,7 @@ func (a *App) GetTeamIdFromQuery(query url.Values) (string, *model.AppError) { return tokenData["teamId"], nil } if inviteId != "" { - team, err := a.Srv().Store.Team().GetByInviteId(inviteId) + team, err := a.Srv().Store().Team().GetByInviteId(inviteId) if err == nil { return team.Id, nil } @@ -2041,7 +2041,7 @@ func (a *App) SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppEr curTime := model.GetMillis() - if err := a.Srv().Store.Team().UpdateLastTeamIconUpdate(team.Id, curTime); err != nil { + if err := a.Srv().Store().Team().UpdateLastTeamIconUpdate(team.Id, curTime); err != nil { return model.NewAppError("SetTeamIcon", "api.team.team_icon.update.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -2061,7 +2061,7 @@ func (a *App) RemoveTeamIcon(teamID string) *model.AppError { return model.NewAppError("RemoveTeamIcon", "api.team.remove_team_icon.get_team.app_error", nil, "", http.StatusBadRequest).Wrap(err) } - if err := a.Srv().Store.Team().UpdateLastTeamIconUpdate(teamID, 0); err != nil { + if err := a.Srv().Store().Team().UpdateLastTeamIconUpdate(teamID, 0); err != nil { return model.NewAppError("RemoveTeamIcon", "api.team.team_icon.update.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -2075,10 +2075,10 @@ func (a *App) RemoveTeamIcon(teamID string) *model.AppError { } func (a *App) InvalidateAllEmailInvites() *model.AppError { - if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeTeamInvitation); err != nil { + if err := a.Srv().Store().Token().RemoveAllTokensByType(TokenTypeTeamInvitation); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Token().RemoveAllTokensByType(TokenTypeGuestInvitation); err != nil { + if err := a.Srv().Store().Token().RemoveAllTokensByType(TokenTypeGuestInvitation); err != nil { return model.NewAppError("InvalidateAllEmailInvites", "api.team.invalidate_all_email_invites.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } if err := a.InvalidateAllResendInviteEmailJobs(); err != nil { @@ -2096,7 +2096,7 @@ func (a *App) InvalidateAllResendInviteEmailJobs() *model.AppError { for _, j := range jobs { a.Srv().Jobs.SetJobCanceled(j) // clean up any system values this job was using - a.Srv().Store.System().PermanentDeleteByName(j.Id) + a.Srv().Store().System().PermanentDeleteByName(j.Id) } return nil @@ -2107,7 +2107,7 @@ func (a *App) ClearTeamMembersCache(teamID string) error { page := 0 for { - teamMembers, err := a.Srv().Store.Team().GetMembers(teamID, page*perPage, perPage, nil) + teamMembers, err := a.Srv().Store().Team().GetMembers(teamID, page*perPage, perPage, nil) if err != nil { return fmt.Errorf("failed to get team members: %v", err) } @@ -2139,7 +2139,7 @@ func (a *App) GetNewTeamMembersSince(c request.CTX, teamID string, opts *model.I return nil, 0, model.NewAppError("GetNewTeamMembersSince", "app.insights.feature_disabled", nil, "", http.StatusNotImplemented) } - ntms, count, err := a.Srv().Store.Team().GetNewTeamMembersSince(teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) + ntms, count, err := a.Srv().Store().Team().GetNewTeamMembersSince(teamID, opts.StartUnixMilli, opts.Page*opts.PerPage, opts.PerPage) if err != nil { return nil, 0, model.NewAppError("GetNewTeamMembersSince", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/team_test.go b/app/team_test.go index 2d17d62673..14eb0273a7 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -213,7 +213,7 @@ func TestAddUserToTeamByToken(t *testing.T) { model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) @@ -227,7 +227,7 @@ func TestAddUserToTeamByToken(t *testing.T) { ) token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1 - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) @@ -239,7 +239,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": model.NewId()}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) @@ -251,7 +251,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, _, err := th.App.AddUserToTeamByToken(th.Context, model.NewId(), token.Token) @@ -263,11 +263,11 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.Nil(t, err, "Should add user to the team") - _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, ruser.Id) @@ -280,7 +280,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) assert.NotNil(t, err) }) @@ -290,7 +290,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) assert.NotNil(t, err) }) @@ -305,7 +305,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.NotNil(t, err) assert.Equal(t, "api.team.join_user_to_team.allowed_domains.app_error", err.Id) @@ -323,20 +323,20 @@ func TestAddUserToTeamByToken(t *testing.T) { ) guestEmail := rguest.Email rguest.Email = "test@restricted.com" - _, err := th.App.Srv().Store.User().Update(rguest, false) + _, err := th.App.Srv().Store().User().Update(rguest, false) th.App.InvalidateCacheForUser(rguest.Id) require.NoError(t, err) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, appErr) rguest.Email = guestEmail - _, err = th.App.Srv().Store.User().Update(rguest, false) + _, err = th.App.Srv().Store().User().Update(rguest, false) require.NoError(t, err) }) t.Run("add a guest user even though there are team and system domain restrictions", func(t *testing.T) { th.BasicTeam.AllowedDomains = "restricted-team.com" - _, err := th.Server.Store.Team().Update(th.BasicTeam) + _, err := th.Server.Store().Team().Update(th.BasicTeam) require.NoError(t, err) restrictedDomain := *th.App.Config().TeamSettings.RestrictCreationToDomains defer func() { @@ -347,13 +347,13 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - _, err = th.App.Srv().Store.User().Update(rguest, false) + _, err = th.App.Srv().Store().User().Update(rguest, false) require.NoError(t, err) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, appErr := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, appErr) th.BasicTeam.AllowedDomains = "" - _, err = th.Server.Store.Team().Update(th.BasicTeam) + _, err = th.Server.Store().Team().Update(th.BasicTeam) require.NoError(t, err) }) @@ -362,12 +362,12 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, rguest.Id, token.Token) require.Nil(t, err, "Should add user to the team") - _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, rguest.Id) @@ -385,7 +385,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err = th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should return an error when trying to join a group-constrained team.") @@ -409,7 +409,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err = th.App.AddUserToTeamByToken(th.Context, ruser.Id, token.Token) require.NotNil(t, err, "Should not add restricted user") @@ -424,7 +424,7 @@ func TestAddUserToTeamByToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": team.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, _, err := th.App.AddUserToTeamByToken(th.Context, user.Id, token.Token) require.Nil(t, err) @@ -1026,7 +1026,7 @@ func TestLeaveTeamPanic(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Get", context.Background(), "userID").Return(&model.User{Id: "userID"}, nil) mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) @@ -1087,7 +1087,7 @@ func TestLeaveTeamPanic(t *testing.T) { ChannelStore: &mockChannelStore, GroupStore: &mocks.GroupStore{}, Users: th.App.ch.srv.userService, - WebHub: th.App.ch.srv, + WebHub: th.App.ch.srv.platform, ConfigFn: th.App.ch.srv.platform.Config, LicenseFn: th.App.ch.srv.License, }) @@ -1355,17 +1355,17 @@ func TestInvalidateAllResendInviteEmailJobs(t *testing.T) { require.Nil(t, err) sysVar := &model.System{Name: job.Id, Value: "0"} - e := th.App.Srv().Store.System().SaveOrUpdate(sysVar) + e := th.App.Srv().Store().System().SaveOrUpdate(sysVar) require.NoError(t, e) appErr := th.App.InvalidateAllResendInviteEmailJobs() require.Nil(t, appErr) - j, e := th.App.Srv().Store.Job().Get(job.Id) + j, e := th.App.Srv().Store().Job().Get(job.Id) require.NoError(t, e) require.Equal(t, j.Status, model.JobStatusCanceled) - _, sysValErr := th.App.Srv().Store.System().GetByName(job.Id) + _, sysValErr := th.App.Srv().Store().System().GetByName(job.Id) var errNotFound *store.ErrNotFound require.ErrorAs(t, sysValErr, &errNotFound) } @@ -1380,7 +1380,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: TokenTypeGuestInvitation, Extra: "", } - err := th.App.Srv().Store.Token().Save(&t1) + err := th.App.Srv().Store().Token().Save(&t1) require.NoError(t, err) t2 := model.Token{ @@ -1389,7 +1389,7 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: TokenTypeTeamInvitation, Extra: "", } - err = th.App.Srv().Store.Token().Save(&t2) + err = th.App.Srv().Store().Token().Save(&t2) require.NoError(t, err) t3 := model.Token{ @@ -1398,19 +1398,19 @@ func TestInvalidateAllEmailInvites(t *testing.T) { Type: "other", Extra: "", } - err = th.App.Srv().Store.Token().Save(&t3) + err = th.App.Srv().Store().Token().Save(&t3) require.NoError(t, err) appErr := th.App.InvalidateAllEmailInvites() require.Nil(t, appErr) - _, err = th.App.Srv().Store.Token().GetByToken(t1.Token) + _, err = th.App.Srv().Store().Token().GetByToken(t1.Token) require.Error(t, err) - _, err = th.App.Srv().Store.Token().GetByToken(t2.Token) + _, err = th.App.Srv().Store().Token().GetByToken(t2.Token) require.Error(t, err) - _, err = th.App.Srv().Store.Token().GetByToken(t3.Token) + _, err = th.App.Srv().Store().Token().GetByToken(t3.Token) require.NoError(t, err) } @@ -1418,7 +1418,7 @@ func TestClearTeamMembersCache(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockTeamStore := mocks.TeamStore{} tms := []*model.TeamMember{} for i := 0; i < 200; i++ { @@ -1607,7 +1607,7 @@ func TestGetNewTeamMembersSince(t *testing.T) { var anotherUser *model.User t.Run("since time 0", func(t *testing.T) { - teamMembers, err := th.App.Srv().Store.Team().GetMembers(team.Id, 0, 1000, nil) + teamMembers, err := th.App.Srv().Store().Team().GetMembers(team.Id, 0, 1000, nil) require.NoError(t, err) originalExpectedCount = int64(len(teamMembers)) _, actualCount, appErr := th.App.GetNewTeamMembersSince(th.Context, team.Id, &model.InsightsOpts{StartUnixMilli: 0, Page: 0, PerPage: 1000}) @@ -1706,7 +1706,7 @@ func TestGetNewTeamMembersSince(t *testing.T) { t.Run("since time 0", func(t *testing.T) { var err error - originalExpectedMembers, err = th.App.Srv().Store.Team().GetMembers(th.BasicTeam.Id, 0, 1000, nil) + originalExpectedMembers, err = th.App.Srv().Store().Team().GetMembers(th.BasicTeam.Id, 0, 1000, nil) require.NoError(t, err) actualMembersList, _, appErr := th.App.GetNewTeamMembersSince(th.Context, th.BasicTeam.Id, &model.InsightsOpts{StartUnixMilli: 0, Page: 0, PerPage: 1000}) require.Nil(t, appErr) diff --git a/app/terms_of_service.go b/app/terms_of_service.go index 157dae592b..ba3736e7ed 100644 --- a/app/terms_of_service.go +++ b/app/terms_of_service.go @@ -22,7 +22,7 @@ func (a *App) CreateTermsOfService(text, userID string) (*model.TermsOfService, } var err error - if termsOfService, err = a.Srv().Store.TermsOfService().Save(termsOfService); err != nil { + if termsOfService, err = a.Srv().Store().TermsOfService().Save(termsOfService); err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError switch { @@ -39,7 +39,7 @@ func (a *App) CreateTermsOfService(text, userID string) (*model.TermsOfService, } func (a *App) GetLatestTermsOfService() (*model.TermsOfService, *model.AppError) { - termsOfService, err := a.Srv().Store.TermsOfService().GetLatest(true) + termsOfService, err := a.Srv().Store().TermsOfService().GetLatest(true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -53,7 +53,7 @@ func (a *App) GetLatestTermsOfService() (*model.TermsOfService, *model.AppError) } func (a *App) GetTermsOfService(id string) (*model.TermsOfService, *model.AppError) { - termsOfService, err := a.Srv().Store.TermsOfService().Get(id, true) + termsOfService, err := a.Srv().Store().TermsOfService().Get(id, true) if err != nil { var nfErr *store.ErrNotFound switch { diff --git a/app/upload.go b/app/upload.go index e2e8e2afc4..15ccfba51a 100644 --- a/app/upload.go +++ b/app/upload.go @@ -156,7 +156,7 @@ func (a *App) CreateUploadSession(c request.CTX, us *model.UploadSession) (*mode } } - us, storeErr := a.Srv().Store.UploadSession().Save(us) + us, storeErr := a.Srv().Store().UploadSession().Save(us) if storeErr != nil { return nil, model.NewAppError("CreateUploadSession", "app.upload.create.save.app_error", nil, "", http.StatusInternalServerError).Wrap(storeErr) } @@ -165,7 +165,7 @@ func (a *App) CreateUploadSession(c request.CTX, us *model.UploadSession) (*mode } func (a *App) GetUploadSession(uploadId string) (*model.UploadSession, *model.AppError) { - us, err := a.Srv().Store.UploadSession().Get(uploadId) + us, err := a.Srv().Store().UploadSession().Get(uploadId) if err != nil { var nfErr *store.ErrNotFound switch { @@ -181,7 +181,7 @@ func (a *App) GetUploadSession(uploadId string) (*model.UploadSession, *model.Ap } func (a *App) GetUploadSessionsForUser(userID string) ([]*model.UploadSession, *model.AppError) { - uss, err := a.Srv().Store.UploadSession().GetForUser(userID) + uss, err := a.Srv().Store().UploadSession().GetForUser(userID) if err != nil { return nil, model.NewAppError("GetUploadsForUser", "app.upload.get_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) @@ -252,7 +252,7 @@ func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Read } if written > 0 { us.FileOffset += written - if storeErr := a.Srv().Store.UploadSession().Update(us); storeErr != nil { + if storeErr := a.Srv().Store().UploadSession().Update(us); storeErr != nil { return nil, model.NewAppError("UploadData", "app.upload.upload_data.update.app_error", nil, "", http.StatusInternalServerError).Wrap(storeErr) } } @@ -314,7 +314,7 @@ func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Read } var storeErr error - if info, storeErr = a.Srv().Store.FileInfo().Save(info); storeErr != nil { + if info, storeErr = a.Srv().Store().FileInfo().Save(info); storeErr != nil { var appErr *model.AppError switch { case errors.As(storeErr, &appErr): @@ -335,7 +335,7 @@ func (a *App) UploadData(c *request.Context, us *model.UploadSession, rd io.Read } // delete upload session - if storeErr := a.Srv().Store.UploadSession().Delete(us.Id); storeErr != nil { + if storeErr := a.Srv().Store().UploadSession().Delete(us.Id); storeErr != nil { mlog.Warn("Failed to delete UploadSession", mlog.Err(storeErr)) } diff --git a/app/usage.go b/app/usage.go index 02a577712b..3abf9bdf64 100644 --- a/app/usage.go +++ b/app/usage.go @@ -44,7 +44,7 @@ func (ch *Channels) getIntegrationsUsage() (*model.IntegrationsUsage, *model.App // GetPostsUsage returns the total posts count rounded down to the most // significant digit func (a *App) GetPostsUsage() (int64, *model.AppError) { - count, err := a.Srv().Store.Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true, UsersPostsOnly: true, AllowFromCache: true}) + count, err := a.Srv().Store().Post().AnalyticsPostCount(&model.PostCountOptions{ExcludeDeleted: true, UsersPostsOnly: true, AllowFromCache: true}) if err != nil { return 0, model.NewAppError("GetPostsUsage", "app.post.analytics_posts_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -54,7 +54,7 @@ func (a *App) GetPostsUsage() (int64, *model.AppError) { // GetStorageUsage returns the sum of files' sizes stored on this instance func (a *App) GetStorageUsage() (int64, *model.AppError) { - usage, err := a.Srv().Store.FileInfo().GetStorageUsage(true, false) + usage, err := a.Srv().Store().FileInfo().GetStorageUsage(true, false) if err != nil { return 0, model.NewAppError("GetStorageUsage", "app.usage.get_storage_usage.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -64,7 +64,7 @@ func (a *App) GetStorageUsage() (int64, *model.AppError) { func (a *App) GetTeamsUsage() (*model.TeamsUsage, *model.AppError) { usage := &model.TeamsUsage{} includeDeleted := false - teamCount, err := a.Srv().Store.Team().AnalyticsTeamCount(&model.TeamSearch{IncludeDeleted: &includeDeleted}) + teamCount, err := a.Srv().Store().Team().AnalyticsTeamCount(&model.TeamSearch{IncludeDeleted: &includeDeleted}) if err != nil { return nil, model.NewAppError("GetTeamsUsage", "app.post.analytics_teams_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/usage_test.go b/app/usage_test.go index 54f8bd59b9..031429b8c4 100644 --- a/app/usage_test.go +++ b/app/usage_test.go @@ -20,7 +20,7 @@ func TestGetPostsUsage(t *testing.T) { errMsg := "Test posts count error" - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockPostStore := mocks.PostStore{} mockPostStore.On("AnalyticsPostCount", mock.Anything).Return(int64(0), errors.New(errMsg)) mockStore.On("Post").Return(&mockPostStore) @@ -37,7 +37,7 @@ func TestGetPostsUsage(t *testing.T) { var mockCount int64 = 4321 var expected int64 = 4000 - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockPostStore := mocks.PostStore{} mockPostStore.On("AnalyticsPostCount", mock.Anything).Return(mockCount, nil) mockStore.On("Post").Return(&mockPostStore) diff --git a/app/user.go b/app/user.go index a9fed62539..bdb9fc8841 100644 --- a/app/user.go +++ b/app/user.go @@ -59,7 +59,7 @@ func (a *App) CreateUserWithToken(c request.CTX, user *model.User, token *model. tokenData := model.MapFromJSON(strings.NewReader(token.Extra)) - team, nErr := a.Srv().Store.Team().Get(tokenData["teamId"]) + team, nErr := a.Srv().Store().Team().Get(tokenData["teamId"]) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -70,7 +70,7 @@ func (a *App) CreateUserWithToken(c request.CTX, user *model.User, token *model. } } - channels, nErr := a.Srv().Store.Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false) + channels, nErr := a.Srv().Store().Channel().GetChannelsByIds(strings.Split(tokenData["channels"], " "), false) if nErr != nil { return nil, model.NewAppError("CreateUserWithToken", "app.channel.get_channels_by_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -121,7 +121,7 @@ func (a *App) CreateUserWithInviteId(c request.CTX, user *model.User, inviteId, return nil, err } - team, nErr := a.Srv().Store.Team().GetByInviteId(inviteId) + team, nErr := a.Srv().Store().Team().GetByInviteId(inviteId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -206,7 +206,7 @@ func (a *App) IsUserSignUpAllowed() *model.AppError { } func (a *App) IsFirstUserAccount() bool { - return a.ch.srv.userService.IsFirstUserAccount() + return a.ch.srv.platform.IsFirstUserAccount() } // CreateUser creates a user and sets several fields of the returned User struct to @@ -284,7 +284,7 @@ func (a *App) createUserOrGuest(c request.CTX, user *model.User, guest bool) (*m preferences = append(preferences, model.Preference{UserId: ruser.Id, Category: model.PreferenceCategoryInsights, Name: model.PreferenceNameInsights, Value: "{\"insights_modal_viewed\":false}"}) } - if err := a.Srv().Store.Preference().Save(preferences); err != nil { + if err := a.Srv().Store().Preference().Save(preferences); err != nil { c.Logger().Warn("Encountered error saving user preferences", mlog.Err(err)) } @@ -345,7 +345,7 @@ func (a *App) CreateOAuthUser(c *request.Context, service string, userData io.Re return nil, model.NewAppError("CreateOAuthUser", "api.user.create_oauth_user.already_attached.app_error", map[string]any{"Service": service, "Auth": model.UserAuthServiceEmail}, "email="+user.Email, http.StatusBadRequest) } if provider.IsSameUser(userByEmail, user) { - if _, err := a.Srv().Store.User().UpdateAuthData(userByEmail.Id, user.AuthService, user.AuthData, "", false); err != nil { + if _, err := a.Srv().Store().User().UpdateAuthData(userByEmail.Id, user.AuthService, user.AuthData, "", false); err != nil { // if the user is not updated, write a warning to the log, but don't prevent user login c.Logger().Warn("Error attempting to update user AuthData", mlog.Err(err)) } @@ -513,7 +513,7 @@ func (a *App) GetUsersNotInTeamEtag(teamID string, restrictionsHash string) stri } func (a *App) GetUsersInChannel(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetProfilesInChannel(options) + users, err := a.Srv().Store().User().GetProfilesInChannel(options) if err != nil { return nil, model.NewAppError("GetUsersInChannel", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -522,7 +522,7 @@ func (a *App) GetUsersInChannel(options *model.UserGetOptions) ([]*model.User, * } func (a *App) GetUsersInChannelByStatus(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetProfilesInChannelByStatus(options) + users, err := a.Srv().Store().User().GetProfilesInChannelByStatus(options) if err != nil { return nil, model.NewAppError("GetUsersInChannelByStatus", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -531,7 +531,7 @@ func (a *App) GetUsersInChannelByStatus(options *model.UserGetOptions) ([]*model } func (a *App) GetUsersInChannelByAdmin(options *model.UserGetOptions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetProfilesInChannelByAdmin(options) + users, err := a.Srv().Store().User().GetProfilesInChannelByAdmin(options) if err != nil { return nil, model.NewAppError("GetUsersInChannelByAdmin", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -580,7 +580,7 @@ func (a *App) GetUsersInChannelPageByAdmin(options *model.UserGetOptions, asAdmi } func (a *App) GetUsersNotInChannel(teamID string, channelID string, groupConstrained bool, offset int, limit int, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetProfilesNotInChannel(teamID, channelID, groupConstrained, offset, limit, viewRestrictions) + users, err := a.Srv().Store().User().GetProfilesNotInChannel(teamID, channelID, groupConstrained, offset, limit, viewRestrictions) if err != nil { return nil, model.NewAppError("GetUsersNotInChannel", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -633,7 +633,7 @@ func (a *App) GetUsersWithoutTeam(options *model.UserGetOptions) ([]*model.User, // GetTeamGroupUsers returns the users who are associated to the team via GroupTeams and GroupMembers. func (a *App) GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetTeamGroupUsers(teamID) + users, err := a.Srv().Store().User().GetTeamGroupUsers(teamID) if err != nil { return nil, model.NewAppError("GetTeamGroupUsers", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -643,7 +643,7 @@ func (a *App) GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError) // GetChannelGroupUsers returns the users who are associated to the channel via GroupChannels and GroupMembers. func (a *App) GetChannelGroupUsers(channelID string) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetChannelGroupUsers(channelID) + users, err := a.Srv().Store().User().GetChannelGroupUsers(channelID) if err != nil { return nil, model.NewAppError("GetChannelGroupUsers", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -661,7 +661,7 @@ func (a *App) GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ( } func (a *App) GetUsersByGroupChannelIds(c *request.Context, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError) { - usersByChannelId, err := a.Srv().Store.User().GetProfileByGroupChannelIdsForUser(c.Session().UserId, channelIDs) + usersByChannelId, err := a.Srv().Store().User().GetProfileByGroupChannelIdsForUser(c.Session().UserId, channelIDs) if err != nil { return nil, model.NewAppError("GetUsersByGroupChannelIds", "app.user.get_profile_by_group_channel_ids_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -770,7 +770,7 @@ func (a *App) SetDefaultProfileImage(c request.CTX, user *model.User) *model.App return err } - if err := a.Srv().Store.User().ResetLastPictureUpdate(user.Id); err != nil { + if err := a.Srv().Store().User().ResetLastPictureUpdate(user.Id); err != nil { c.Logger().Warn("Failed to reset last picture update", mlog.Err(err)) } @@ -846,7 +846,7 @@ func (a *App) SetProfileImageFromFile(c request.CTX, userID string, file io.Read return model.NewAppError("SetProfileImage", "api.user.upload_profile_user.upload_profile.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.User().UpdateLastPictureUpdate(userID); err != nil { + if err := a.Srv().Store().User().UpdateLastPictureUpdate(userID); err != nil { c.Logger().Warn("Error with updating last picture update", mlog.Err(err)) } a.invalidateUserCacheAndPublish(userID) @@ -972,14 +972,20 @@ func (a *App) DeactivateGuests(c *request.Context) *model.AppError { return model.NewAppError("DeactivateGuests", "app.user.update_active_for_multiple_users.updating.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } + for _, userID := range userIDs { + if err := a.Srv().Platform().RevokeAllSessions(userID); err != nil { + return model.NewAppError("DeactivateGuests", "app.user.update_active_for_multiple_users.updating.app_error", nil, "", http.StatusInternalServerError).Wrap(err) + } + } + for _, userID := range userIDs { if err := a.userDeactivated(c, userID); err != nil { return err } } - a.Srv().Store.Channel().ClearCaches() - a.Srv().Store.User().ClearCaches() + a.Srv().Store().Channel().ClearCaches() + a.Srv().Store().User().ClearCaches() message := model.NewWebSocketEvent(model.WebsocketEventGuestsDeactivated, "", "", "", nil, "") a.Publish(message) @@ -1055,7 +1061,7 @@ func (a *App) PatchUser(c request.CTX, userID string, patch *model.UserPatch, as func (a *App) UpdateUserAuth(userID string, userAuth *model.UserAuth) (*model.UserAuth, *model.AppError) { userAuth.Password = "" - if _, err := a.Srv().Store.User().UpdateAuthData(userID, userAuth.AuthService, userAuth.AuthData, "", false); err != nil { + if _, err := a.Srv().Store().User().UpdateAuthData(userID, userAuth.AuthService, userAuth.AuthData, "", false); err != nil { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): @@ -1100,7 +1106,7 @@ func (a *App) isUniqueToGroupNames(val string) *model.AppError { return nil } var notFoundErr *store.ErrNotFound - group, err := a.Srv().Store.Group().GetByName(val, model.GroupSearchOpts{}) + group, err := a.Srv().Store().Group().GetByName(val, model.GroupSearchOpts{}) if err != nil && !errors.As(err, ¬FoundErr) { return model.NewAppError("isUniqueToGroupNames", model.NoTranslation, nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1291,7 +1297,7 @@ func (a *App) UpdatePassword(user *model.User, newPassword string) *model.AppErr hashedPassword := model.HashPassword(newPassword) - if err := a.Srv().Store.User().UpdatePassword(user.Id, hashedPassword); err != nil { + if err := a.Srv().Store().User().UpdatePassword(user.Id, hashedPassword); err != nil { return model.NewAppError("UpdatePassword", "api.user.update_password.failed.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1324,7 +1330,7 @@ func (a *App) UpdateHashedPasswordByUserId(userID, newHashedPassword string) *mo } func (a *App) UpdateHashedPassword(user *model.User, newHashedPassword string) *model.AppError { - if err := a.Srv().Store.User().UpdatePassword(user.Id, newHashedPassword); err != nil { + if err := a.Srv().Store().User().UpdatePassword(user.Id, newHashedPassword); err != nil { return model.NewAppError("UpdatePassword", "api.user.update_password.failed.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1420,7 +1426,7 @@ func (a *App) CreatePasswordRecoveryToken(userID, email string) (*model.Token, * token := model.NewToken(TokenTypePasswordRecovery, string(jsonData)) - if err := a.Srv().Store.Token().Save(token); err != nil { + if err := a.Srv().Store().Token().Save(token); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -1434,7 +1440,7 @@ func (a *App) CreatePasswordRecoveryToken(userID, email string) (*model.Token, * } func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError) { - rtoken, err := a.Srv().Store.Token().GetByToken(token) + rtoken, err := a.Srv().Store().Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetPasswordRecoveryToken", "api.user.reset_password.invalid_link.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1445,7 +1451,7 @@ func (a *App) GetPasswordRecoveryToken(token string) (*model.Token, *model.AppEr } func (a *App) GetTokenById(token string) (*model.Token, *model.AppError) { - rtoken, err := a.Srv().Store.Token().GetByToken(token) + rtoken, err := a.Srv().Store().Token().GetByToken(token) if err != nil { var status int @@ -1464,7 +1470,7 @@ func (a *App) GetTokenById(token string) (*model.Token, *model.AppError) { } func (a *App) DeleteToken(token *model.Token) *model.AppError { - err := a.Srv().Store.Token().Delete(token.Token) + err := a.Srv().Store().Token().Delete(token.Token) if err != nil { return model.NewAppError("DeleteToken", "app.recover.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1490,14 +1496,14 @@ func (a *App) UpdateUserRolesWithUser(c request.CTX, user *model.User, newRoles user.Roles = newRoles uchan := make(chan store.StoreResult, 1) go func() { - userUpdate, err := a.Srv().Store.User().Update(user, true) + userUpdate, err := a.Srv().Store().User().Update(user, true) uchan <- store.StoreResult{Data: userUpdate, NErr: err} close(uchan) }() schan := make(chan store.StoreResult, 1) go func() { - id, err := a.Srv().Store.Session().UpdateRoles(user.Id, newRoles) + id, err := a.Srv().Store().Session().UpdateRoles(user.Id, newRoles) schan <- store.StoreResult{Data: id, NErr: err} close(schan) }() @@ -1545,47 +1551,47 @@ func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.A return err } - if err := a.Srv().Store.Session().PermanentDeleteSessionsByUser(user.Id); err != nil { + if err := a.Srv().Store().Session().PermanentDeleteSessionsByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.session.permanent_delete_sessions_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.UserAccessToken().DeleteAllForUser(user.Id); err != nil { + if err := a.Srv().Store().UserAccessToken().DeleteAllForUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.user_access_token.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.OAuth().PermanentDeleteAuthDataByUser(user.Id); err != nil { + if err := a.Srv().Store().OAuth().PermanentDeleteAuthDataByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.oauth.permanent_delete_auth_data_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Webhook().PermanentDeleteIncomingByUser(user.Id); err != nil { + if err := a.Srv().Store().Webhook().PermanentDeleteIncomingByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.webhooks.permanent_delete_incoming_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Webhook().PermanentDeleteOutgoingByUser(user.Id); err != nil { + if err := a.Srv().Store().Webhook().PermanentDeleteOutgoingByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.webhooks.permanent_delete_outgoing_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Command().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store().Command().PermanentDeleteByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.user.permanentdeleteuser.internal_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Preference().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store().Preference().PermanentDeleteByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.preference.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Channel().PermanentDeleteMembersByUser(user.Id); err != nil { + if err := a.Srv().Store().Channel().PermanentDeleteMembersByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.channel.permanent_delete_members_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Group().PermanentDeleteMembersByUser(user.Id); err != nil { + if err := a.Srv().Store().Group().PermanentDeleteMembersByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.group.permanent_delete_members_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Post().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store().Post().PermanentDeleteByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.post.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Bot().PermanentDelete(user.Id); err != nil { + if err := a.Srv().Store().Bot().PermanentDelete(user.Id); err != nil { var invErr *store.ErrInvalidInput switch { case errors.As(err, &invErr): @@ -1595,7 +1601,7 @@ func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.A } } - infos, err := a.Srv().Store.FileInfo().GetForUser(user.Id) + infos, err := a.Srv().Store().FileInfo().GetForUser(user.Id) if err != nil { c.Logger().Warn("Error getting file list for user from FileInfoStore", mlog.Err(err)) } @@ -1656,19 +1662,19 @@ func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.A } } - if _, err := a.Srv().Store.FileInfo().PermanentDeleteByUser(user.Id); err != nil { + if _, err := a.Srv().Store().FileInfo().PermanentDeleteByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.file_info.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.User().PermanentDelete(user.Id); err != nil { + if err := a.Srv().Store().User().PermanentDelete(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.user.permanent_delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Audit().PermanentDeleteByUser(user.Id); err != nil { + if err := a.Srv().Store().Audit().PermanentDeleteByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.audit.permanent_delete_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - if err := a.Srv().Store.Team().RemoveAllMembersByUser(user.Id); err != nil { + if err := a.Srv().Store().Team().RemoveAllMembersByUser(user.Id); err != nil { return model.NewAppError("PermanentDeleteUser", "app.team.remove_member.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1684,7 +1690,7 @@ func (a *App) PermanentDeleteUser(c *request.Context, user *model.User) *model.A } func (a *App) PermanentDeleteAllUsers(c *request.Context) *model.AppError { - users, err := a.Srv().Store.User().GetAll() + users, err := a.Srv().Store().User().GetAll() if err != nil { return model.NewAppError("PermanentDeleteAllUsers", "app.user.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1770,7 +1776,7 @@ func (a *App) VerifyEmailFromToken(c request.CTX, userSuppliedTokenString string } func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) { - rtoken, err := a.Srv().Store.Token().GetByToken(token) + rtoken, err := a.Srv().Store().Token().GetByToken(token) if err != nil { return nil, model.NewAppError("GetVerifyEmailToken", "api.user.verify_email.bad_link.app_error", nil, "", http.StatusBadRequest).Wrap(err) } @@ -1782,7 +1788,7 @@ func (a *App) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) // GetTotalUsersStats is used for the DM list total func (a *App) GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) (*model.UsersStats, *model.AppError) { - count, err := a.Srv().Store.User().Count(model.UserCountOptions{ + count, err := a.Srv().Store().User().Count(model.UserCountOptions{ IncludeBotAccounts: true, ViewRestrictions: viewRestrictions, }) @@ -1797,7 +1803,7 @@ func (a *App) GetTotalUsersStats(viewRestrictions *model.ViewUsersRestrictions) // GetFilteredUsersStats is used to get a count of users based on the set of filters supported by UserCountOptions. func (a *App) GetFilteredUsersStats(options *model.UserCountOptions) (*model.UsersStats, *model.AppError) { - count, err := a.Srv().Store.User().Count(*options) + count, err := a.Srv().Store().User().Count(*options) if err != nil { return nil, model.NewAppError("GetFilteredUsersStats", "app.user.get_total_users_count.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1808,7 +1814,7 @@ func (a *App) GetFilteredUsersStats(options *model.UserCountOptions) (*model.Use } func (a *App) VerifyUserEmail(userID, email string) *model.AppError { - if _, err := a.Srv().Store.User().VerifyEmail(userID, email); err != nil { + if _, err := a.Srv().Store().User().VerifyEmail(userID, email); err != nil { return model.NewAppError("VerifyUserEmail", "app.user.verify_email.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1849,7 +1855,7 @@ func (a *App) SearchUsers(props *model.UserSearch, options *model.UserSearchOpti func (a *App) SearchUsersInChannel(channelID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchInChannel(channelID, term, options) + users, err := a.Srv().Store().User().SearchInChannel(channelID, term, options) if err != nil { return nil, model.NewAppError("SearchUsersInChannel", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1862,7 +1868,7 @@ func (a *App) SearchUsersInChannel(channelID string, term string, options *model func (a *App) SearchUsersNotInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchNotInChannel(teamID, channelID, term, options) + users, err := a.Srv().Store().User().SearchNotInChannel(teamID, channelID, term, options) if err != nil { return nil, model.NewAppError("SearchUsersNotInChannel", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1877,7 +1883,7 @@ func (a *App) SearchUsersNotInChannel(teamID string, channelID string, term stri func (a *App) SearchUsersInTeam(teamID, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().Search(teamID, term, options) + users, err := a.Srv().Store().User().Search(teamID, term, options) if err != nil { return nil, model.NewAppError("SearchUsersInTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1891,7 +1897,7 @@ func (a *App) SearchUsersInTeam(teamID, term string, options *model.UserSearchOp func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchNotInTeam(notInTeamId, term, options) + users, err := a.Srv().Store().User().SearchNotInTeam(notInTeamId, term, options) if err != nil { return nil, model.NewAppError("SearchUsersNotInTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1905,7 +1911,7 @@ func (a *App) SearchUsersNotInTeam(notInTeamId string, term string, options *mod func (a *App) SearchUsersWithoutTeam(term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchWithoutTeam(term, options) + users, err := a.Srv().Store().User().SearchWithoutTeam(term, options) if err != nil { return nil, model.NewAppError("SearchUsersWithoutTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1919,7 +1925,7 @@ func (a *App) SearchUsersWithoutTeam(term string, options *model.UserSearchOptio func (a *App) SearchUsersInGroup(groupID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchInGroup(groupID, term, options) + users, err := a.Srv().Store().User().SearchInGroup(groupID, term, options) if err != nil { return nil, model.NewAppError("SearchUsersInGroup", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1933,7 +1939,7 @@ func (a *App) SearchUsersInGroup(groupID string, term string, options *model.Use func (a *App) SearchUsersNotInGroup(groupID string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().SearchNotInGroup(groupID, term, options) + users, err := a.Srv().Store().User().SearchNotInGroup(groupID, term, options) if err != nil { return nil, model.NewAppError("SearchUsersNotInGroup", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1948,7 +1954,7 @@ func (a *App) SearchUsersNotInGroup(groupID string, term string, options *model. func (a *App) AutocompleteUsersInChannel(teamID string, channelID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInChannel, *model.AppError) { term = strings.TrimSpace(term) - autocomplete, err := a.Srv().Store.User().AutocompleteUsersInChannel(teamID, channelID, term, options) + autocomplete, err := a.Srv().Store().User().AutocompleteUsersInChannel(teamID, channelID, term, options) if err != nil { return nil, model.NewAppError("AutocompleteUsersInChannel", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -1967,7 +1973,7 @@ func (a *App) AutocompleteUsersInChannel(teamID string, channelID string, term s func (a *App) AutocompleteUsersInTeam(teamID string, term string, options *model.UserSearchOptions) (*model.UserAutocompleteInTeam, *model.AppError) { term = strings.TrimSpace(term) - users, err := a.Srv().Store.User().Search(teamID, term, options) + users, err := a.Srv().Store().User().Search(teamID, term, options) if err != nil { return nil, model.NewAppError("AutocompleteUsersInTeam", "app.user.search.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2016,7 +2022,7 @@ func (a *App) UpdateOAuthUserAttrs(userData io.Reader, user *model.User, provide } if userAttrsChanged { - users, err := a.Srv().Store.User().Update(user, true) + users, err := a.Srv().Store().User().Update(user, true) if err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -2071,7 +2077,7 @@ func (a *App) FilterNonGroupChannelMembers(userIDs []string, channel *model.Chan // and returns the list of normal users present in userIDs but not in groupUsers. func (a *App) filterNonGroupUsers(userIDs []string, groupUsers []*model.User) ([]string, error) { nonMemberIds := []string{} - users, err := a.Srv().Store.User().GetProfileByIds(context.Background(), userIDs, nil, false) + users, err := a.Srv().Store().User().GetProfileByIds(context.Background(), userIDs, nil, false) if err != nil { return nil, err } @@ -2118,7 +2124,7 @@ func (a *App) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *mod } if len(restrictions.Teams) > 0 { - result, err := a.Srv().Store.Team().UserBelongsToTeams(otherUserId, restrictions.Teams) + result, err := a.Srv().Store().Team().UserBelongsToTeams(otherUserId, restrictions.Teams) if err != nil { return false, model.NewAppError("UserCanSeeOtherUser", "app.team.user_belongs_to_teams.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2141,7 +2147,7 @@ func (a *App) UserCanSeeOtherUser(userID string, otherUserId string) (bool, *mod } func (a *App) userBelongsToChannels(userID string, channelIDs []string) (bool, *model.AppError) { - belongs, err := a.Srv().Store.Channel().UserBelongsToChannels(userID, channelIDs) + belongs, err := a.Srv().Store().Channel().UserBelongsToChannels(userID, channelIDs) if err != nil { return false, model.NewAppError("userBelongsToChannels", "app.channel.user_belongs_to_channels.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2154,7 +2160,7 @@ func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestricti return nil, nil } - teamIDs, nErr := a.Srv().Store.Team().GetUserTeamIds(userID, true) + teamIDs, nErr := a.Srv().Store().Team().GetUserTeamIds(userID, true) if nErr != nil { return nil, model.NewAppError("GetViewUsersRestrictions", "app.team.get_user_team_ids.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2166,7 +2172,7 @@ func (a *App) GetViewUsersRestrictions(userID string) (*model.ViewUsersRestricti } } - userChannelMembers, err := a.Srv().Store.Channel().GetAllChannelMembersForUser(userID, true, true) + userChannelMembers, err := a.Srv().Store().Channel().GetAllChannelMembersForUser(userID, true, true) if err != nil { return nil, model.NewAppError("GetViewUsersRestrictions", "app.channel.get_channels.get.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2187,7 +2193,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor if nErr != nil { return model.NewAppError("PromoteGuestToUser", "app.user.promote_guest.user_update.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } - userTeams, nErr := a.Srv().Store.Team().GetTeamsByUserId(user.Id) + userTeams, nErr := a.Srv().Store().Team().GetTeamsByUserId(user.Id) if nErr != nil { return model.NewAppError("PromoteGuestToUser", "app.team.get_all.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2204,7 +2210,7 @@ func (a *App) PromoteGuestToUser(c *request.Context, user *model.User, requestor c.Logger().Warn("Failed to get user on promote guest to user", mlog.Err(err)) } else { a.sendUpdatedUserEvent(*promotedUser) - if uErr := a.ch.srv.userService.UpdateSessionsIsGuest(promotedUser.Id, promotedUser.IsGuest()); uErr != nil { + if uErr := a.ch.srv.platform.UpdateSessionsIsGuest(promotedUser.Id, promotedUser.IsGuest()); uErr != nil { c.Logger().Warn("Unable to update user sessions", mlog.String("user_id", promotedUser.Id), mlog.Err(uErr)) } } @@ -2249,7 +2255,7 @@ func (a *App) DemoteUserToGuest(c request.CTX, user *model.User) *model.AppError } a.sendUpdatedUserEvent(*demotedUser) - if uErr := a.ch.srv.userService.UpdateSessionsIsGuest(demotedUser.Id, demotedUser.IsGuest()); uErr != nil { + if uErr := a.ch.srv.platform.UpdateSessionsIsGuest(demotedUser.Id, demotedUser.IsGuest()); uErr != nil { c.Logger().Warn("Unable to update user sessions", mlog.String("user_id", demotedUser.Id), mlog.Err(uErr)) } @@ -2318,7 +2324,7 @@ func (a *App) invalidateUserCacheAndPublish(userID string) { // relationship with a user. That means any user sharing any channel, including // direct and group channels. func (a *App) GetKnownUsers(userID string) ([]string, *model.AppError) { - users, err := a.Srv().Store.User().GetKnownUsers(userID) + users, err := a.Srv().Store().User().GetKnownUsers(userID) if err != nil { return nil, model.NewAppError("GetKnownUsers", "app.user.get_known_users.get_users.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2328,7 +2334,7 @@ func (a *App) GetKnownUsers(userID string) ([]string, *model.AppError) { // ConvertBotToUser converts a bot to user. func (a *App) ConvertBotToUser(c request.CTX, bot *model.Bot, userPatch *model.UserPatch, sysadmin bool) (*model.User, *model.AppError) { - user, nErr := a.Srv().Store.User().Get(c.Context(), bot.UserId) + user, nErr := a.Srv().Store().User().Get(c.Context(), bot.UserId) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -2361,7 +2367,7 @@ func (a *App) ConvertBotToUser(c request.CTX, bot *model.Bot, userPatch *model.U return nil, err } - appErr := a.Srv().Store.Bot().PermanentDelete(bot.UserId) + appErr := a.Srv().Store().Bot().PermanentDelete(bot.UserId) if appErr != nil { return nil, model.NewAppError("ConvertBotToUser", "app.user.convert_bot_to_user.app_error", nil, "", http.StatusInternalServerError).Wrap(appErr) } @@ -2375,7 +2381,7 @@ func (a *App) GetThreadsForUser(userID, teamID string, options model.GetUserThre if !options.ThreadsOnly { eg.Go(func() error { - totalUnreadThreads, err := a.Srv().Store.Thread().GetTotalUnreadThreads(userID, teamID, options) + totalUnreadThreads, err := a.Srv().Store().Thread().GetTotalUnreadThreads(userID, teamID, options) if err != nil { return errors.Wrapf(err, "failed to count unread threads for user id=%s", userID) } @@ -2389,7 +2395,7 @@ func (a *App) GetThreadsForUser(userID, teamID string, options model.GetUserThre // and send back duplicate values down below. if !options.Unread { eg.Go(func() error { - totalCount, err := a.Srv().Store.Thread().GetTotalThreads(userID, teamID, options) + totalCount, err := a.Srv().Store().Thread().GetTotalThreads(userID, teamID, options) if err != nil { return errors.Wrapf(err, "failed to count threads for user id=%s", userID) } @@ -2400,7 +2406,7 @@ func (a *App) GetThreadsForUser(userID, teamID string, options model.GetUserThre } eg.Go(func() error { - totalUnreadMentions, err := a.Srv().Store.Thread().GetTotalUnreadMentions(userID, teamID, options) + totalUnreadMentions, err := a.Srv().Store().Thread().GetTotalUnreadMentions(userID, teamID, options) if err != nil { return errors.Wrapf(err, "failed to count threads for user id=%s", userID) } @@ -2412,7 +2418,7 @@ func (a *App) GetThreadsForUser(userID, teamID string, options model.GetUserThre if !options.TotalsOnly { eg.Go(func() error { - threads, err := a.Srv().Store.Thread().GetThreadsForUser(userID, teamID, options) + threads, err := a.Srv().Store().Thread().GetThreadsForUser(userID, teamID, options) if err != nil { return errors.Wrapf(err, "failed to get threads for user id=%s", userID) } @@ -2439,7 +2445,7 @@ func (a *App) GetThreadsForUser(userID, teamID string, options model.GetUserThre } func (a *App) GetThreadMembershipForUser(userId, threadId string) (*model.ThreadMembership, *model.AppError) { - threadMembership, err := a.Srv().Store.Thread().GetMembershipForUser(userId, threadId) + threadMembership, err := a.Srv().Store().Thread().GetMembershipForUser(userId, threadId) if err != nil { return nil, model.NewAppError("GetThreadMembershipForUser", "app.user.get_thread_membership_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2450,7 +2456,7 @@ func (a *App) GetThreadMembershipForUser(userId, threadId string) (*model.Thread } func (a *App) GetThreadForUser(teamID string, threadMembership *model.ThreadMembership, extended bool) (*model.ThreadResponse, *model.AppError) { - thread, err := a.Srv().Store.Thread().GetThreadForUser(teamID, threadMembership, extended) + thread, err := a.Srv().Store().Thread().GetThreadForUser(teamID, threadMembership, extended) if err != nil { return nil, model.NewAppError("GetThreadForUser", "app.user.get_threads_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2463,7 +2469,7 @@ func (a *App) GetThreadForUser(teamID string, threadMembership *model.ThreadMemb } func (a *App) UpdateThreadsReadForUser(userID, teamID string) *model.AppError { - nErr := a.Srv().Store.Thread().MarkAllAsReadByTeam(userID, teamID) + nErr := a.Srv().Store().Thread().MarkAllAsReadByTeam(userID, teamID) if nErr != nil { return model.NewAppError("UpdateThreadsReadForUser", "app.user.update_threads_read_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2480,11 +2486,11 @@ func (a *App) UpdateThreadFollowForUser(userID, teamID, threadID string, state b UpdateViewedTimestamp: state, UpdateParticipants: false, } - _, err := a.Srv().Store.Thread().MaintainMembership(userID, threadID, opts) + _, err := a.Srv().Store().Thread().MaintainMembership(userID, threadID, opts) if err != nil { return model.NewAppError("UpdateThreadFollowForUser", "app.user.update_thread_follow_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - thread, err := a.Srv().Store.Thread().Get(threadID) + thread, err := a.Srv().Store().Thread().Get(threadID) if err != nil { return model.NewAppError("UpdateThreadFollowForUser", "app.user.update_thread_follow_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2508,7 +2514,7 @@ func (a *App) UpdateThreadFollowForUserFromChannelAdd(c request.CTX, userID, tea UpdateViewedTimestamp: false, UpdateParticipants: false, } - tm, err := a.Srv().Store.Thread().MaintainMembership(userID, threadID, opts) + tm, err := a.Srv().Store().Thread().MaintainMembership(userID, threadID, opts) if err != nil { return model.NewAppError("UpdateThreadFollowForUserFromChannelAdd", "app.user.update_thread_follow_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -2526,13 +2532,14 @@ func (a *App) UpdateThreadFollowForUserFromChannelAdd(c request.CTX, userID, tea return appErr } tm.LastViewed = post.CreateAt - 1 - _, err = a.Srv().Store.Thread().UpdateMembership(tm) + _, err = a.Srv().Store().Thread().UpdateMembership(tm) if err != nil { return model.NewAppError("UpdateThreadFollowForUserFromChannelAdd", "app.user.update_thread_follow_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } message := model.NewWebSocketEvent(model.WebsocketEventThreadUpdated, teamID, "", userID, nil, "") - userThread, err := a.Srv().Store.Thread().GetThreadForUser(teamID, tm, true) + userThread, err := a.Srv().Store().Thread().GetThreadForUser(teamID, tm, true) + if err != nil { var errNotFound *store.ErrNotFound if errors.As(err, &errNotFound) { @@ -2583,13 +2590,13 @@ func (a *App) UpdateThreadReadForUser(c request.CTX, currentSessionId, userID, t Following: true, UpdateFollowing: true, } - membership, storeErr := a.Srv().Store.Thread().MaintainMembership(userID, threadID, opts) + membership, storeErr := a.Srv().Store().Thread().MaintainMembership(userID, threadID, opts) if storeErr != nil { return nil, model.NewAppError("UpdateThreadReadForUser", "app.user.update_thread_read_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(storeErr) } previousUnreadMentions := membership.UnreadMentions - previousUnreadReplies, nErr := a.Srv().Store.Thread().GetThreadUnreadReplyCount(membership) + previousUnreadReplies, nErr := a.Srv().Store().Thread().GetThreadUnreadReplyCount(membership) if nErr != nil { return nil, model.NewAppError("UpdateThreadReadForUser", "app.user.update_thread_read_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2602,14 +2609,14 @@ func (a *App) UpdateThreadReadForUser(c request.CTX, currentSessionId, userID, t if err != nil { return nil, err } - _, nErr = a.Srv().Store.Thread().UpdateMembership(membership) + _, nErr = a.Srv().Store().Thread().UpdateMembership(membership) if nErr != nil { return nil, model.NewAppError("UpdateThreadReadForUser", "app.user.update_thread_read_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } membership.LastViewed = timestamp - nErr = a.Srv().Store.Thread().MarkAsRead(userID, threadID, timestamp) + nErr = a.Srv().Store().Thread().MarkAsRead(userID, threadID, timestamp) if nErr != nil { return nil, model.NewAppError("UpdateThreadReadForUser", "app.user.update_thread_read_for_user.app_error", nil, "", http.StatusInternalServerError).Wrap(nErr) } @@ -2636,7 +2643,7 @@ func (a *App) UpdateThreadReadForUser(c request.CTX, currentSessionId, userID, t } func (a *App) GetUsersWithInvalidEmails(page int, perPage int) ([]*model.User, *model.AppError) { - users, err := a.Srv().Store.User().GetUsersWithInvalidEmails(page, perPage, *a.Config().TeamSettings.RestrictCreationToDomains) + users, err := a.Srv().Store().User().GetUsersWithInvalidEmails(page, perPage, *a.Config().TeamSettings.RestrictCreationToDomains) if err != nil { return nil, model.NewAppError("GetUsersPage", "app.user.get_profiles.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } diff --git a/app/user_terms_of_service.go b/app/user_terms_of_service.go index d201bd274d..d3e406313f 100644 --- a/app/user_terms_of_service.go +++ b/app/user_terms_of_service.go @@ -12,7 +12,7 @@ import ( ) func (a *App) GetUserTermsOfService(userID string) (*model.UserTermsOfService, *model.AppError) { - u, err := a.Srv().Store.UserTermsOfService().GetByUser(userID) + u, err := a.Srv().Store().UserTermsOfService().GetByUser(userID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -33,7 +33,7 @@ func (a *App) SaveUserTermsOfService(userID, termsOfServiceId string, accepted b TermsOfServiceId: termsOfServiceId, } - if _, err := a.Srv().Store.UserTermsOfService().Save(userTermsOfService); err != nil { + if _, err := a.Srv().Store().UserTermsOfService().Save(userTermsOfService); err != nil { var appErr *model.AppError switch { case errors.As(err, &appErr): @@ -43,7 +43,7 @@ func (a *App) SaveUserTermsOfService(userID, termsOfServiceId string, accepted b } } } else { - if err := a.Srv().Store.UserTermsOfService().Delete(userID, termsOfServiceId); err != nil { + if err := a.Srv().Store().UserTermsOfService().Delete(userID, termsOfServiceId); err != nil { return model.NewAppError("SaveUserTermsOfService", "app.user_terms_of_service.delete.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } } diff --git a/app/user_test.go b/app/user_test.go index acdfc7ef74..174c193deb 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -65,14 +65,14 @@ func TestCreateOAuthUser(t *testing.T) { einterfaces.RegisterOAuthProvider(model.ServiceOffice365, providerMock) // Update user to be OAuth, formatting to match Office365 OAuth data - s, er2 := th.App.Srv().Store.User().UpdateAuthData(dbUser.Id, model.ServiceOffice365, model.NewString("e711000764be43d898404a7e9c26b710"), "", false) + s, er2 := th.App.Srv().Store().User().UpdateAuthData(dbUser.Id, model.ServiceOffice365, model.NewString("e711000764be43d898404a7e9c26b710"), "", false) assert.NoError(t, er2) assert.Equal(t, dbUser.Id, s) // data passed doesn't matter as return is mocked _, err := th.App.CreateOAuthUser(th.Context, model.ServiceOffice365, strings.NewReader("{}"), th.BasicTeam.Id, nil) assert.Nil(t, err) - u, er := th.App.Srv().Store.User().GetByEmail(dbUser.Email) + u, er := th.App.Srv().Store().User().GetByEmail(dbUser.Email) assert.NoError(t, er) // make sure authdata is updated assert.Equal(t, "e7110007-64be-43d8-9840-4a7e9c26b710", *u.AuthData) @@ -469,13 +469,13 @@ func TestCreateUserConflict(t *testing.T) { Email: "test@localhost", Username: model.NewId(), } - user, err := th.App.Srv().Store.User().Save(user) + user, err := th.App.Srv().Store().User().Save(user) require.NoError(t, err) username := user.Username var invErr *store.ErrInvalidInput // Same id - _, err = th.App.Srv().Store.User().Save(user) + _, err = th.App.Srv().Store().User().Save(user) require.Error(t, err) require.True(t, errors.As(err, &invErr)) assert.Equal(t, "id", invErr.Field) @@ -485,7 +485,7 @@ func TestCreateUserConflict(t *testing.T) { Email: "test@localhost", Username: model.NewId(), } - _, err = th.App.Srv().Store.User().Save(user) + _, err = th.App.Srv().Store().User().Save(user) require.Error(t, err) require.True(t, errors.As(err, &invErr)) assert.Equal(t, "email", invErr.Field) @@ -495,7 +495,7 @@ func TestCreateUserConflict(t *testing.T) { Email: "test2@localhost", Username: username, } - _, err = th.App.Srv().Store.User().Save(user) + _, err = th.App.Srv().Store().User().Save(user) require.Error(t, err) require.True(t, errors.As(err, &invErr)) assert.Equal(t, "username", invErr.Field) @@ -538,7 +538,7 @@ func TestUpdateUserEmail(t *testing.T) { Username: model.NewId(), IsBot: true, } - _, nErr := th.App.Srv().Store.User().Save(&botuser) + _, nErr := th.App.Srv().Store().User().Save(&botuser) assert.NoError(t, nErr) newBotEmail := th.MakeEmail() @@ -582,7 +582,7 @@ func TestUpdateUserEmail(t *testing.T) { Username: model.NewId(), IsBot: true, } - _, nErr := th.App.Srv().Store.User().Save(&botuser) + _, nErr := th.App.Srv().Store().User().Save(&botuser) assert.NoError(t, nErr) newBotEmail := th.MakeEmail() @@ -621,7 +621,7 @@ func TestUpdateUserEmail(t *testing.T) { tokens := []*model.Token{} require.Eventually(t, func() bool { var err error - tokens, err = th.App.Srv().Store.Token().GetAllTokensByType(TokenTypeVerifyEmail) + tokens, err = th.App.Srv().Store().Token().GetAllTokensByType(TokenTypeVerifyEmail) return err == nil && len(tokens) == 1 }, 100*time.Millisecond, 10*time.Millisecond) @@ -636,7 +636,7 @@ func TestUpdateUserEmail(t *testing.T) { require.Eventually(t, func() bool { var err error - tokens, err = th.App.Srv().Store.Token().GetAllTokensByType(TokenTypeVerifyEmail) + tokens, err = th.App.Srv().Store().Token().GetAllTokensByType(TokenTypeVerifyEmail) // We verify the same conditions as the earlier function, // but we also need to ensure that this is not the same token // as before, which is possible if the token update goroutine @@ -645,7 +645,7 @@ func TestUpdateUserEmail(t *testing.T) { }, 100*time.Millisecond, 10*time.Millisecond) secondToken := tokens[0] - _, err := th.App.Srv().Store.Token().GetByToken(firstToken.Token) + _, err := th.App.Srv().Store().Token().GetByToken(firstToken.Token) require.Error(t, err) require.NotNil(t, th.App.VerifyEmailFromToken(th.Context, firstToken.Token)) @@ -710,7 +710,7 @@ func TestGetUsersByStatus(t *testing.T) { th.LinkUserToTeam(user, team) th.AddUserToChannel(user, channel) - th.App.SaveAndBroadcastStatus(&model.Status{ + th.App.Srv().Platform().SaveAndBroadcastStatus(&model.Status{ UserId: user.Id, Status: status, Manual: true, @@ -832,7 +832,7 @@ func TestCreateUserWithInviteId(t *testing.T) { t.Run("invalid domain", func(t *testing.T) { th.BasicTeam.AllowedDomains = "mattermost.com" - _, nErr := th.App.Srv().Store.Team().Update(th.BasicTeam) + _, nErr := th.App.Srv().Store().Team().Update(th.BasicTeam) require.NoError(t, nErr) _, err := th.App.CreateUserWithInviteId(th.Context, &user, th.BasicTeam.InviteId, "") require.NotNil(t, err) @@ -856,7 +856,7 @@ func TestCreateUserWithToken(t *testing.T) { TokenTypeVerifyEmail, model.MapToJSON(map[string]string{"teamID": th.BasicTeam.Id, "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on bad token type") @@ -869,7 +869,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err) }) @@ -880,7 +880,7 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": user.Email}), ) token.CreateAt = model.GetMillis() - InvitationExpiryTime - 1 - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on expired token") @@ -891,7 +891,7 @@ func TestCreateUserWithToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": model.NewId(), "email": user.Email}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) defer th.App.DeleteToken(token) _, err := th.App.CreateUserWithToken(th.Context, &user, token) require.NotNil(t, err, "Should fail on bad team id") @@ -904,13 +904,13 @@ func TestCreateUserWithToken(t *testing.T) { TokenTypeTeamInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) newUser, err := th.App.CreateUserWithToken(th.Context, &u, token) require.Nil(t, err, "Should add user to the team. err=%v", err) assert.False(t, newUser.IsGuest()) require.Equal(t, invitationEmail, newUser.Email, "The user email must be the invitation one") - _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newUser.Id) @@ -925,14 +925,14 @@ func TestCreateUserWithToken(t *testing.T) { model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) guest := model.User{Email: invitationEmail, Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} newGuest, err := th.App.CreateUserWithToken(th.Context, &guest, token) require.Nil(t, err, "Should add user to the team. err=%v", err) assert.True(t, newGuest.IsGuest()) require.Equal(t, invitationEmail, newGuest.Email, "The user email must be the invitation one") - _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, nErr, "The token must be deleted after be used") members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) @@ -959,8 +959,8 @@ func TestCreateUserWithToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": grantedInvitationEmail, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(forbiddenDomainToken)) - require.NoError(t, th.App.Srv().Store.Token().Save(grantedDomainToken)) + require.NoError(t, th.App.Srv().Store().Token().Save(forbiddenDomainToken)) + require.NoError(t, th.App.Srv().Store().Token().Save(grantedDomainToken)) guest := model.User{ Email: forbiddenInvitationEmail, Nickname: "Darth Vader", @@ -978,7 +978,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Nil(t, err) assert.True(t, newGuest.IsGuest()) require.Equal(t, grantedInvitationEmail, newGuest.Email) - _, nErr := th.App.Srv().Store.Token().GetByToken(grantedDomainToken.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(grantedDomainToken.Token) require.Error(t, nErr) members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) @@ -1003,7 +1003,7 @@ func TestCreateUserWithToken(t *testing.T) { TokenTypeGuestInvitation, model.MapToJSON(map[string]string{"teamId": th.BasicTeam.Id, "email": invitationEmail, "channels": th.BasicChannel.Id}), ) - require.NoError(t, th.App.Srv().Store.Token().Save(token)) + require.NoError(t, th.App.Srv().Store().Token().Save(token)) guest := model.User{ Email: invitationEmail, Nickname: "Darth Vader", @@ -1015,7 +1015,7 @@ func TestCreateUserWithToken(t *testing.T) { require.Nil(t, err) assert.True(t, newGuest.IsGuest()) assert.Equal(t, invitationEmail, newGuest.Email, "The user email must be the invitation one") - _, nErr := th.App.Srv().Store.Token().GetByToken(token.Token) + _, nErr := th.App.Srv().Store().Token().GetByToken(token.Token) require.Error(t, nErr) members, err := th.App.GetChannelMembersForUser(th.Context, th.BasicTeam.Id, newGuest.Id) @@ -1709,7 +1709,7 @@ func TestUpdateThreadReadForUser(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*storemocks.Store) + mockStore := th.App.Srv().Store().(*storemocks.Store) mockUserStore := storemocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockUserStore.On("Get", mock.Anything, "user1").Return(&model.User{Id: "user1"}, nil) diff --git a/app/users/errors.go b/app/users/errors.go index db6f69bb7a..7faa7575d9 100644 --- a/app/users/errors.go +++ b/app/users/errors.go @@ -12,10 +12,6 @@ var ( UserCreationDisabledError = errors.New("user creation is not allowed") UserStoreIsEmptyError = errors.New("could not check if the user store is empty") - GetTokenError = errors.New("could not get token") - GetSessionError = errors.New("could not get session") - DeleteTokenError = errors.New("could not delete token") - DeleteSessionError = errors.New("could not delete session") DeleteAllAccessDataError = errors.New("could not delete all access data") DefaultFontError = errors.New("could not get default font") diff --git a/app/users/helper_test.go b/app/users/helper_test.go index 44e55114b6..694bac437c 100644 --- a/app/users/helper_test.go +++ b/app/users/helper_test.go @@ -7,14 +7,12 @@ import ( "bytes" "os" "path/filepath" - "runtime" "sync" "testing" "github.com/mattermost/mattermost-server/v6/app/request" "github.com/mattermost/mattermost-server/v6/config" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/store" ) @@ -73,27 +71,12 @@ func setupTestHelper(s store.Store, includeCacheLayer bool, tb testing.TB) *Test configStore.Set(config) buffer := &bytes.Buffer{} - provider := cache.NewProvider() - cache, err := provider.NewCache(&cache.CacheOptions{ - Size: model.SessionCacheSize, - Striped: true, - StripedBuckets: maxInt(runtime.NumCPU()-1, 1), - }) - if err != nil { - panic(err) - } return &TestHelper{ service: &UserService{ store: s.User(), sessionStore: s.Session(), oAuthStore: s.OAuth(), - sessionCache: cache, config: configStore.Get, - sessionPool: sync.Pool{ - New: func() any { - return &model.Session{} - }, - }, }, Context: request.EmptyContext(nil), configStore: configStore, diff --git a/app/users/service.go b/app/users/service.go index 98a65958a2..90f8902f7e 100644 --- a/app/users/service.go +++ b/app/users/service.go @@ -5,13 +5,9 @@ package users import ( "errors" - "fmt" - "runtime" - "sync" "github.com/mattermost/mattermost-server/v6/einterfaces" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/services/cache" "github.com/mattermost/mattermost-server/v6/store" ) @@ -19,8 +15,6 @@ type UserService struct { store store.UserStore sessionStore store.SessionStore oAuthStore store.OAuthStore - sessionCache cache.Cache - sessionPool sync.Pool metrics einterfaces.MetricsInterface cluster einterfaces.ClusterInterface config func() *model.Config @@ -45,20 +39,6 @@ func New(c ServiceConfig) (*UserService, error) { return nil, err } - cacheProvider := cache.NewProvider() - if err := cacheProvider.Connect(); err != nil { - return nil, fmt.Errorf("could not connect to cache provider: %w", err) - } - - sessionCache, err := cacheProvider.NewCache(&cache.CacheOptions{ - Size: model.SessionCacheSize, - Striped: true, - StripedBuckets: maxInt(runtime.NumCPU()-1, 1), - }) - if err != nil { - return nil, fmt.Errorf("could not create session cache: %w", err) - } - return &UserService{ store: c.UserStore, sessionStore: c.SessionStore, @@ -67,12 +47,6 @@ func New(c ServiceConfig) (*UserService, error) { license: c.LicenseFn, metrics: c.Metrics, cluster: c.Cluster, - sessionCache: sessionCache, - sessionPool: sync.Pool{ - New: func() any { - return &model.Session{} - }, - }, }, nil } diff --git a/app/users/session.go b/app/users/session.go deleted file mode 100644 index 7deed60df1..0000000000 --- a/app/users/session.go +++ /dev/null @@ -1,263 +0,0 @@ -// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. -// See LICENSE.txt for license information. - -package users - -import ( - "context" - "fmt" - "time" - - "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/shared/mlog" - "github.com/mattermost/mattermost-server/v6/store/sqlstore" - "github.com/pkg/errors" -) - -func (us *UserService) ReturnSessionToPool(session *model.Session) { - if session != nil { - session.Id = "" - us.sessionPool.Put(session) - } -} - -func (us *UserService) CreateSession(session *model.Session) (*model.Session, error) { - session.Token = "" - - session, err := us.sessionStore.Save(session) - if err != nil { - return nil, err - } - - us.AddSessionToCache(session) - - return session, nil -} - -func (us *UserService) GetSession(token string) (*model.Session, error) { - var session = us.sessionPool.Get().(*model.Session) - if err := us.sessionCache.Get(token, session); err == nil { - if us.metrics != nil { - us.metrics.IncrementMemCacheHitCounterSession() - } - } else { - if us.metrics != nil { - us.metrics.IncrementMemCacheMissCounterSession() - } - } - - if session.Id != "" { - return session, nil - } - - return us.GetSessionContext(sqlstore.WithMaster(context.Background()), token) -} - -func (us *UserService) GetSessionContext(ctx context.Context, token string) (*model.Session, error) { - return us.sessionStore.Get(ctx, token) -} - -func (us *UserService) GetSessions(userID string) ([]*model.Session, error) { - return us.sessionStore.GetSessions(userID) -} - -func (us *UserService) AddSessionToCache(session *model.Session) { - us.sessionCache.SetWithExpiry(session.Token, session, time.Duration(int64(*us.config().ServiceSettings.SessionCacheInMinutes))*time.Minute) -} - -func (us *UserService) SessionCacheLength() int { - if l, err := us.sessionCache.Len(); err == nil { - return l - } - return 0 -} - -func (us *UserService) ClearUserSessionCacheLocal(userID string) { - if keys, err := us.sessionCache.Keys(); err == nil { - var session *model.Session - for _, key := range keys { - if err := us.sessionCache.Get(key, &session); err == nil { - if session.UserId == userID { - us.sessionCache.Remove(key) - if us.metrics != nil { - us.metrics.IncrementMemCacheInvalidationCounterSession() - } - } - } - } - } -} - -func (us *UserService) ClearAllUsersSessionCacheLocal() { - us.sessionCache.Purge() -} - -func (us *UserService) ClearUserSessionCache(userID string) { - us.ClearUserSessionCacheLocal(userID) - - if us.cluster != nil { - msg := &model.ClusterMessage{ - Event: model.ClusterEventClearSessionCacheForUser, - SendType: model.ClusterSendReliable, - Data: []byte(userID), - } - us.cluster.SendClusterMessage(msg) - } -} - -func (us *UserService) ClearAllUsersSessionCache() { - us.ClearAllUsersSessionCacheLocal() - - if us.cluster != nil { - msg := &model.ClusterMessage{ - Event: model.ClusterEventClearSessionCacheForAllUsers, - SendType: model.ClusterSendReliable, - } - us.cluster.SendClusterMessage(msg) - } -} - -func (us *UserService) GetSessionByID(sessionID string) (*model.Session, error) { - return us.sessionStore.Get(context.Background(), sessionID) -} - -func (us *UserService) RevokeSessionsFromAllUsers() error { - // revoke tokens before sessions so they can't be used to relogin - nErr := us.oAuthStore.RemoveAllAccessData() - if nErr != nil { - return errors.Wrap(DeleteAllAccessDataError, nErr.Error()) - } - err := us.sessionStore.RemoveAllSessions() - if err != nil { - return err - } - - us.ClearAllUsersSessionCache() - return nil -} - -func (us *UserService) RevokeSessionsForDeviceId(userID string, deviceID string, currentSessionId string) error { - sessions, err := us.sessionStore.GetSessions(userID) - if err != nil { - return err - } - for _, session := range sessions { - if session.DeviceId == deviceID && session.Id != currentSessionId { - mlog.Debug("Revoking sessionId for userId. Re-login with the same device Id", mlog.String("session_id", session.Id), mlog.String("user_id", userID)) - if err := us.RevokeSession(session); err != nil { - mlog.Warn("Could not revoke session for device", mlog.String("device_id", deviceID), mlog.Err(err)) - } - } - } - - return nil -} - -func (us *UserService) RevokeSession(session *model.Session) error { - if session.IsOAuth { - if err := us.RevokeAccessToken(session.Token); err != nil { - return err - } - } else { - if err := us.sessionStore.Remove(session.Id); err != nil { - return errors.Wrap(DeleteSessionError, err.Error()) - } - } - - us.ClearUserSessionCache(session.UserId) - - return nil -} - -func (us *UserService) RevokeAccessToken(token string) error { - session, _ := us.GetSession(token) - - defer us.ReturnSessionToPool(session) - - schan := make(chan error, 1) - go func() { - schan <- us.sessionStore.Remove(token) - close(schan) - }() - - if _, err := us.oAuthStore.GetAccessData(token); err != nil { - return errors.Wrap(GetTokenError, err.Error()) - } - - if err := us.oAuthStore.RemoveAccessData(token); err != nil { - return errors.Wrap(DeleteTokenError, err.Error()) - } - - if err := <-schan; err != nil { - return errors.Wrap(DeleteSessionError, err.Error()) - } - - if session != nil { - us.ClearUserSessionCache(session.UserId) - } - - return nil -} - -// SetSessionExpireInHours sets the session's expiry the specified number of hours -// relative to either the session creation date or the current time, depending -// on the `ExtendSessionOnActivity` config setting. -func (us *UserService) SetSessionExpireInHours(session *model.Session, hours int) { - if session.CreateAt == 0 || *us.config().ServiceSettings.ExtendSessionLengthWithActivity { - session.ExpiresAt = model.GetMillis() + (1000 * 60 * 60 * int64(hours)) - } else { - session.ExpiresAt = session.CreateAt + (1000 * 60 * 60 * int64(hours)) - } -} - -func (us *UserService) ExtendSessionExpiry(session *model.Session, newExpiry int64) error { - if err := us.sessionStore.UpdateExpiresAt(session.Id, newExpiry); err != nil { - return err - } - - // Update local cache. No need to invalidate cache for cluster as the session cache timeout - // ensures each node will get an extended expiry within the next 10 minutes. - // Worst case is another node may generate a redundant expiry update. - session.ExpiresAt = newExpiry - us.AddSessionToCache(session) - - return nil -} - -func (us *UserService) UpdateSessionsIsGuest(userID string, isGuest bool) error { - sessions, err := us.GetSessions(userID) - if err != nil { - return err - } - - for _, session := range sessions { - session.AddProp(model.SessionPropIsGuest, fmt.Sprintf("%t", isGuest)) - err := us.sessionStore.UpdateProps(session) - if err != nil { - mlog.Warn("Unable to update isGuest session", mlog.Err(err)) - continue - } - us.AddSessionToCache(session) - } - return nil -} - -func (us *UserService) RevokeAllSessions(userID string) error { - sessions, err := us.sessionStore.GetSessions(userID) - if err != nil { - return errors.Wrap(GetSessionError, err.Error()) - } - for _, session := range sessions { - if session.IsOAuth { - us.RevokeAccessToken(session.Token) - } else { - if err := us.sessionStore.Remove(session.Id); err != nil { - return errors.Wrap(DeleteSessionError, err.Error()) - } - } - } - - us.ClearUserSessionCache(userID) - - return nil -} diff --git a/app/users/users.go b/app/users/users.go index 2c424ffda1..4233cb75d9 100644 --- a/app/users/users.go +++ b/app/users/users.go @@ -207,12 +207,6 @@ func (us *UserService) DeactivateAllGuests() ([]string, error) { return nil, err } - for _, userID := range users { - if err := us.RevokeAllSessions(userID); err != nil { - return nil, err - } - } - return users, nil } diff --git a/app/users/utils.go b/app/users/utils.go index d9356f0763..52545432bc 100644 --- a/app/users/utils.go +++ b/app/users/utils.go @@ -9,31 +9,6 @@ import ( "github.com/mattermost/mattermost-server/v6/model" ) -func maxInt(a, b int) int { - if a > b { - return a - } - return b -} - -func (us *UserService) IsFirstUserAccount() bool { - cachedSessions, err := us.sessionCache.Len() - if err != nil { - return false - } - if cachedSessions == 0 { - count, err := us.store.Count(model.UserCountOptions{IncludeDeleted: true}) - if err != nil { - return false - } - if count <= 0 { - return true - } - } - - return false -} - // CheckUserDomain checks that a user's email domain matches a list of space-delimited domains as a string. func CheckUserDomain(user *model.User, domains string) bool { return CheckEmailDomain(user.Email, domains) diff --git a/app/web_conn.go b/app/web_conn.go index 8c4b0b706b..0edc3504ae 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -4,828 +4,17 @@ package app import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "net" - "net/http" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/gorilla/websocket" - "github.com/vmihailenco/msgpack/v5" - + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/plugin" - "github.com/mattermost/mattermost-server/v6/shared/i18n" - "github.com/mattermost/mattermost-server/v6/shared/mlog" ) -const ( - sendQueueSize = 256 - sendSlowWarn = (sendQueueSize * 50) / 100 - sendFullWarn = (sendQueueSize * 95) / 100 - writeWaitTime = 30 * time.Second - pongWaitTime = 100 * time.Second - pingInterval = (pongWaitTime * 6) / 10 - authCheckInterval = 5 * time.Second - webConnMemberCacheTime = 1000 * 60 * 30 // 30 minutes - deadQueueSize = 128 // Approximated from /proc/sys/net/core/wmem_default / 2048 (avg msg size) -) - -const ( - reconnectFound = "success" - reconnectNotFound = "failure" - reconnectLossless = "lossless" -) - -const websocketMessagePluginPrefix = "custom_" - -type pluginWSPostedHook struct { - connectionID string - userID string - req *model.WebSocketRequest -} - -type WebConnConfig struct { - WebSocket *websocket.Conn - Session model.Session - TFunc i18n.TranslateFunc - Locale string - ConnectionID string - Active bool - ReuseCount int - - // These aren't necessary to be exported to api layer. - sequence int - activeQueue chan model.WebSocketMessage - deadQueue []*model.WebSocketEvent - deadQueuePointer int -} - -// WebConn represents a single websocket connection to a user. -// It contains all the necessary state to manage sending/receiving data to/from -// a websocket. -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 - T i18n.TranslateFunc - Locale string - Sequence int64 - UserId string - - allChannelMembers map[string]string - lastAllChannelMembersTime int64 - lastUserActivityAt int64 - send chan model.WebSocketMessage - // deadQueue behaves like a queue of a finite size - // which is used to store all messages that are sent via the websocket. - // It basically acts as the user-space socket buffer, and is used - // to resuscitate any messages that might have got lost when the connection is broken. - // It is implemented by using a circular buffer to keep it fast. - deadQueue []*model.WebSocketEvent - // Pointer which indicates the next slot to insert. - // It is only to be incremented during writing or clearing the queue. - deadQueuePointer int - // active indicates whether there is an open websocket connection attached - // to this webConn or not. - // It is not used as an atomic, because there is no need to. - // So do not use this outside the web hub. - active bool - // reuseCount indicates how many times this connection has been reused. - // This is used to differentiate between a fresh connection and - // a reused connection. - // It's theoretically possible for this number to wrap around. But we - // leave that as an edge-case. - reuseCount int - sessionToken atomic.Value - session atomic.Value - connectionID atomic.Value - endWritePump chan struct{} - pumpFinished chan struct{} - pluginPosted chan pluginWSPostedHook -} - -// CheckConnResult indicates whether a connectionID was present in the hub or not. -// And if so, contains the active and dead queue details. -type CheckConnResult struct { - ConnectionID string - UserID string - ActiveQueue chan model.WebSocketMessage - DeadQueue []*model.WebSocketEvent - DeadQueuePointer int - ReuseCount int -} - // PopulateWebConnConfig checks if the connection id already exists in the hub, // and if so, accordingly populates the other fields of the webconn. -func (a *App) PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error) { - if !model.IsValidId(cfg.ConnectionID) { - return nil, fmt.Errorf("invalid connection id: %s", cfg.ConnectionID) - } - - // This does not handle reconnect requests across nodes in a cluster. - // It falls back to the non-reliable case in that scenario. - res := a.CheckWebConn(s.UserId, cfg.ConnectionID) - if res == nil { - // If the connection is not present, then we assume either timeout, - // or server restart. In that case, we set a new one. - cfg.ConnectionID = model.NewId() - } else { - // Connection is present, we get the active queue, dead queue - cfg.activeQueue = res.ActiveQueue - cfg.deadQueue = res.DeadQueue - cfg.deadQueuePointer = res.DeadQueuePointer - cfg.Active = false - cfg.ReuseCount = res.ReuseCount - // Now we get the sequence number - if seqVal == "" { - // Sequence_number must be sent with connection id. - // A client must be either non-compliant or fully compliant. - return nil, errors.New("sequence number not present in websocket request") - } - var err error - cfg.sequence, err = strconv.Atoi(seqVal) - if err != nil || cfg.sequence < 0 { - return nil, fmt.Errorf("invalid sequence number %s in query param: %v", seqVal, err) - } - } - return cfg, nil +func (a *App) PopulateWebConnConfig(s *model.Session, cfg *platform.WebConnConfig, seqVal string) (*platform.WebConnConfig, error) { + return a.Srv().Platform().PopulateWebConnConfig(s, cfg, seqVal) } // NewWebConn returns a new WebConn instance. -func (a *App) NewWebConn(cfg *WebConnConfig) *WebConn { - if cfg.Session.UserId != "" { - a.Srv().Go(func() { - a.SetStatusOnline(cfg.Session.UserId, false) - a.UpdateLastActivityAtIfNeeded(cfg.Session) - }) - } - - // Disable TCP_NO_DELAY for higher throughput - var tcpConn *net.TCPConn - switch conn := cfg.WebSocket.UnderlyingConn().(type) { - case *net.TCPConn: - tcpConn = conn - case *tls.Conn: - newConn, ok := conn.NetConn().(*net.TCPConn) - if ok { - tcpConn = newConn - } - } - - if tcpConn != nil { - err := tcpConn.SetNoDelay(false) - if err != nil { - mlog.Warn("Error in setting NoDelay socket opts", mlog.Err(err)) - } - } - - if cfg.activeQueue == nil { - cfg.activeQueue = make(chan model.WebSocketMessage, sendQueueSize) - } - - if cfg.deadQueue == nil { - cfg.deadQueue = make([]*model.WebSocketEvent, deadQueueSize) - } - - wc := &WebConn{ - App: a, - send: cfg.activeQueue, - deadQueue: cfg.deadQueue, - deadQueuePointer: cfg.deadQueuePointer, - Sequence: int64(cfg.sequence), - WebSocket: cfg.WebSocket, - lastUserActivityAt: model.GetMillis(), - UserId: cfg.Session.UserId, - T: cfg.TFunc, - Locale: cfg.Locale, - active: cfg.Active, - reuseCount: cfg.ReuseCount, - endWritePump: make(chan struct{}), - pumpFinished: make(chan struct{}), - pluginPosted: make(chan pluginWSPostedHook, 10), - } - - wc.SetSession(&cfg.Session) - wc.SetSessionToken(cfg.Session.Token) - wc.SetSessionExpiresAt(cfg.Session.ExpiresAt) - wc.SetConnectionID(cfg.ConnectionID) - - if pluginsEnvironment := wc.App.GetPluginsEnvironment(); pluginsEnvironment != nil { - wc.App.Srv().Go(func() { - pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { - hooks.OnWebSocketConnect(wc.GetConnectionID(), wc.UserId) - return true - }, plugin.OnWebSocketConnectID) - }) - } - - return wc -} - -func (wc *WebConn) pluginPostedConsumer(wg *sync.WaitGroup) { - defer wg.Done() - - for msg := range wc.pluginPosted { - if pluginsEnvironment := wc.App.GetPluginsEnvironment(); pluginsEnvironment != nil { - pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { - hooks.WebSocketMessageHasBeenPosted(msg.connectionID, msg.userID, msg.req) - return true - }, plugin.WebSocketMessageHasBeenPostedID) - } - } -} - -// Close closes the WebConn. -func (wc *WebConn) Close() { - wc.WebSocket.Close() - <-wc.pumpFinished -} - -// GetSessionExpiresAt returns the time at which the session expires. -func (wc *WebConn) GetSessionExpiresAt() int64 { - return atomic.LoadInt64(&wc.sessionExpiresAt) -} - -// SetSessionExpiresAt sets the time at which the session expires. -func (wc *WebConn) SetSessionExpiresAt(v int64) { - atomic.StoreInt64(&wc.sessionExpiresAt, v) -} - -// GetSessionToken returns the session token of the connection. -func (wc *WebConn) GetSessionToken() string { - return wc.sessionToken.Load().(string) -} - -// SetSessionToken sets the session token of the connection. -func (wc *WebConn) SetSessionToken(v string) { - wc.sessionToken.Store(v) -} - -// SetConnectionID sets the connection id of the connection. -func (wc *WebConn) SetConnectionID(id string) { - wc.connectionID.Store(id) -} - -// GetConnectionID returns the connection id of the connection. -func (wc *WebConn) GetConnectionID() string { - return wc.connectionID.Load().(string) -} - -// areAllInactive returns whether all of the connections -// are inactive or not. -func areAllInactive(conns []*WebConn) bool { - for _, conn := range conns { - if conn.active { - return false - } - } - return true -} - -// GetSession returns the session of the connection. -func (wc *WebConn) GetSession() *model.Session { - return wc.session.Load().(*model.Session) -} - -// SetSession sets the session of the connection. -func (wc *WebConn) SetSession(v *model.Session) { - if v != nil { - v = v.DeepCopy() - } - - wc.session.Store(v) -} - -// Pump starts the WebConn instance. After this, the websocket -// is ready to send/receive messages. -func (wc *WebConn) Pump() { - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - wc.writePump() - }() - - wg.Add(1) - go wc.pluginPostedConsumer(&wg) - - wc.readPump() - close(wc.endWritePump) - close(wc.pluginPosted) - wg.Wait() - wc.App.HubUnregister(wc) - close(wc.pumpFinished) - - if pluginsEnvironment := wc.App.GetPluginsEnvironment(); pluginsEnvironment != nil { - wc.App.Srv().Go(func() { - pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool { - hooks.OnWebSocketDisconnect(wc.GetConnectionID(), wc.UserId) - return true - }, plugin.OnWebSocketDisconnectID) - }) - } -} - -func (wc *WebConn) readPump() { - defer func() { - wc.WebSocket.Close() - }() - wc.WebSocket.SetReadLimit(model.SocketMaxMessageSizeKb) - wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)) - wc.WebSocket.SetPongHandler(func(string) error { - if err := wc.WebSocket.SetReadDeadline(time.Now().Add(pongWaitTime)); err != nil { - return err - } - if wc.IsAuthenticated() { - wc.App.Srv().Go(func() { - wc.App.SetStatusAwayIfNeeded(wc.UserId, false) - }) - } - return nil - }) - - for { - msgType, rd, err := wc.WebSocket.NextReader() - if err != nil { - wc.logSocketErr("websocket.NextReader", err) - return - } - - var decoder interface { - Decode(v any) error - } - if msgType == websocket.TextMessage { - decoder = json.NewDecoder(rd) - } else { - decoder = msgpack.NewDecoder(rd) - } - var req model.WebSocketRequest - if err = decoder.Decode(&req); err != nil { - wc.logSocketErr("websocket.Decode", err) - return - } - - // Messages which actions are prefixed with the plugin prefix - // should only be dispatched to the plugins - if !strings.HasPrefix(req.Action, websocketMessagePluginPrefix) { - wc.App.Srv().WebSocketRouter.ServeWebSocket(wc, &req) - } - - clonedReq, err := req.Clone() - if err != nil { - wc.logSocketErr("websocket.cloneRequest", err) - continue - } - - wc.pluginPosted <- pluginWSPostedHook{wc.GetConnectionID(), wc.UserId, clonedReq} - } -} - -func (wc *WebConn) writePump() { - ticker := time.NewTicker(pingInterval) - authTicker := time.NewTicker(authCheckInterval) - - defer func() { - ticker.Stop() - authTicker.Stop() - wc.WebSocket.Close() - }() - - if wc.Sequence != 0 { - if ok, index := wc.isInDeadQueue(wc.Sequence); ok { - if err := wc.drainDeadQueue(index); err != nil { - wc.logSocketErr("websocket.drainDeadQueue", err) - return - } - if m := wc.App.Metrics(); m != nil { - m.IncrementWebsocketReconnectEvent(reconnectFound) - } - } else if wc.hasMsgLoss() { - // If the seq number is not in dead queue, but it was supposed to be, - // then generate a different connection ID, - // and set sequence to 0, and clear dead queue. - wc.clearDeadQueue() - wc.SetConnectionID(model.NewId()) - wc.Sequence = 0 - - // Send hello message - msg := wc.createHelloMessage() - wc.addToDeadQueue(msg) - if err := wc.writeMessage(msg); err != nil { - wc.logSocketErr("websocket.sendHello", err) - return - } - if m := wc.App.Metrics(); m != nil { - m.IncrementWebsocketReconnectEvent(reconnectNotFound) - } - } else { - if m := wc.App.Metrics(); m != nil { - m.IncrementWebsocketReconnectEvent(reconnectLossless) - } - } - } - - var buf bytes.Buffer - // 2k is seen to be a good heuristic under which 98.5% of message sizes remain. - buf.Grow(1024 * 2) - enc := json.NewEncoder(&buf) - - for { - select { - case msg, ok := <-wc.send: - if !ok { - wc.writeMessageBuf(websocket.CloseMessage, []byte{}) - return - } - - evt, evtOk := msg.(*model.WebSocketEvent) - - buf.Reset() - var err error - if evtOk { - evt = evt.SetSequence(wc.Sequence) - err = evt.Encode(enc) - wc.Sequence++ - } else { - err = enc.Encode(msg) - } - if err != nil { - mlog.Warn("Error in encoding websocket message", mlog.Err(err)) - continue - } - - if len(wc.send) >= sendFullWarn { - logData := []mlog.Field{ - mlog.String("user_id", wc.UserId), - mlog.String("type", msg.EventType()), - mlog.Int("size", buf.Len()), - } - if evtOk { - logData = append(logData, mlog.String("channel_id", evt.GetBroadcast().ChannelId)) - } - - mlog.Warn("websocket.full", logData...) - } - - if evtOk { - wc.addToDeadQueue(evt) - } - - if err := wc.writeMessageBuf(websocket.TextMessage, buf.Bytes()); err != nil { - wc.logSocketErr("websocket.send", err) - return - } - - if wc.App.Metrics() != nil { - wc.App.Metrics().IncrementWebSocketBroadcast(msg.EventType()) - } - case <-ticker.C: - if err := wc.writeMessageBuf(websocket.PingMessage, []byte{}); err != nil { - wc.logSocketErr("websocket.ticker", err) - return - } - - case <-wc.endWritePump: - return - - case <-authTicker.C: - if wc.GetSessionToken() == "" { - mlog.Debug("websocket.authTicker: did not authenticate", mlog.Any("ip_address", wc.WebSocket.RemoteAddr())) - return - } - authTicker.Stop() - } - } -} - -// writeMessageBuf is a helper utility that wraps the write to the socket -// along with setting the write deadline. -func (wc *WebConn) writeMessageBuf(msgType int, data []byte) error { - wc.WebSocket.SetWriteDeadline(time.Now().Add(writeWaitTime)) - return wc.WebSocket.WriteMessage(msgType, data) -} - -func (wc *WebConn) writeMessage(msg *model.WebSocketEvent) error { - // We don't use the encoder from the write pump because it's unwieldy to pass encoders - // around, and this is only called during initialization of the webConn. - var buf bytes.Buffer - err := msg.Encode(json.NewEncoder(&buf)) - if err != nil { - mlog.Warn("Error in encoding websocket message", mlog.Err(err)) - return nil - } - wc.Sequence++ - - return wc.writeMessageBuf(websocket.TextMessage, buf.Bytes()) -} - -// addToDeadQueue appends a message to the dead queue. -func (wc *WebConn) addToDeadQueue(msg *model.WebSocketEvent) { - wc.deadQueue[wc.deadQueuePointer] = msg - wc.deadQueuePointer = (wc.deadQueuePointer + 1) % deadQueueSize -} - -// hasMsgLoss indicates whether the next wanted sequence is right after -// the latest element in the dead queue, which would mean there is no message loss. -func (wc *WebConn) hasMsgLoss() bool { - var index int - // deadQueuePointer = 0 means either no msg written or the pointer - // has rolled over to its starting position. - if wc.deadQueuePointer == 0 { - // If last entry is nil, it means no msg is written. - if wc.deadQueue[deadQueueSize-1] == nil { - return false - } - // If it's not nil, that means it has rolled over to start, and we - // check the last position. - index = deadQueueSize - 1 - } else { // deadQueuePointer != 0 means it's somewhere in the middle. - index = wc.deadQueuePointer - 1 - } - - if wc.deadQueue[index].GetSequence() == wc.Sequence-1 { - return false - } - return true -} - -// isInDeadQueue checks whether a given sequence number is in the dead queue or not. -// And if it is, it returns that index. -func (wc *WebConn) isInDeadQueue(seq int64) (bool, int) { - // Can be optimized to traverse backwards from deadQueuePointer - // Hopefully, traversing 128 elements is not too much overhead. - for i := 0; i < deadQueueSize; i++ { - elem := wc.deadQueue[i] - if elem == nil { - return false, 0 - } - - if elem.GetSequence() == seq { - return true, i - } - } - return false, 0 -} - -func (wc *WebConn) clearDeadQueue() { - for i := 0; i < deadQueueSize; i++ { - if wc.deadQueue[i] == nil { - break - } - wc.deadQueue[i] = nil - } - wc.deadQueuePointer = 0 -} - -// drainDeadQueue will write all messages from a given index to the socket. -// It is called with the assumption that the item with wc.Sequence is present -// in it, because otherwise it would have been cleared from WebConn. -func (wc *WebConn) drainDeadQueue(index int) error { - if wc.deadQueue[0] == nil { - // Empty queue - return nil - } - - // This means pointer hasn't rolled over. - if wc.deadQueue[wc.deadQueuePointer] == nil { - // Clear till the end of queue. - for i := index; i < wc.deadQueuePointer; i++ { - if err := wc.writeMessage(wc.deadQueue[i]); err != nil { - return err - } - } - return nil - } - - // We go on until next sequence number is smaller than previous one. - // Which means it has rolled over. - currPtr := index - for { - if err := wc.writeMessage(wc.deadQueue[currPtr]); err != nil { - return err - } - oldSeq := wc.deadQueue[currPtr].GetSequence() // TODO: possibly move this - currPtr = (currPtr + 1) % deadQueueSize // to for loop condition - newSeq := wc.deadQueue[currPtr].GetSequence() - if oldSeq > newSeq { - break - } - } - return nil -} - -// InvalidateCache resets all internal data of the WebConn. -func (wc *WebConn) InvalidateCache() { - wc.allChannelMembers = nil - wc.lastAllChannelMembersTime = 0 - wc.SetSession(nil) - wc.SetSessionExpiresAt(0) -} - -// IsAuthenticated returns whether the given WebConn is authenticated or not. -func (wc *WebConn) IsAuthenticated() bool { - // Check the expiry to see if we need to check for a new session - if wc.GetSessionExpiresAt() < model.GetMillis() { - if wc.GetSessionToken() == "" { - return false - } - - session, err := wc.App.GetSession(wc.GetSessionToken()) - if err != nil { - if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { - mlog.Debug("Invalid session.", mlog.Err(err)) - } else { - mlog.Error("Could not get session", mlog.String("session_token", wc.GetSessionToken()), mlog.Err(err)) - } - - wc.SetSessionToken("") - wc.SetSession(nil) - wc.SetSessionExpiresAt(0) - return false - } - - wc.SetSession(session) - wc.SetSessionExpiresAt(session.ExpiresAt) - } - - return true -} - -func (wc *WebConn) createHelloMessage() *model.WebSocketEvent { - msg := model.NewWebSocketEvent(model.WebsocketEventHello, "", "", wc.UserId, nil, "") - msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, - model.BuildNumber, - wc.App.ClientConfigHash(), - wc.App.Channels().License() != nil)) - msg.Add("connection_id", wc.connectionID.Load()) - return msg -} - -func (wc *WebConn) shouldSendEventToGuest(msg *model.WebSocketEvent) bool { - var userID string - var canSee bool - - switch msg.EventType() { - case model.WebsocketEventUserUpdated: - user, ok := msg.GetData()["user"].(*model.User) - if !ok { - mlog.Debug("webhub.shouldSendEvent: user not found in message", mlog.Any("user", msg.GetData()["user"])) - return false - } - userID = user.Id - case model.WebsocketEventNewUser: - userID = msg.GetData()["user_id"].(string) - default: - return true - } - - canSee, err := wc.App.UserCanSeeOtherUser(wc.UserId, userID) - if err != nil { - mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) - return false - } - - return canSee -} - -// shouldSendEvent returns whether the message should be sent or not. -func (wc *WebConn) shouldSendEvent(msg *model.WebSocketEvent) bool { - // IMPORTANT: Do not send event if WebConn does not have a session - if !wc.IsAuthenticated() { - return false - } - - // When the pump starts to get slow we'll drop non-critical - // messages. We should skip those frames before they are - // queued to wc.send buffered channel. - if len(wc.send) >= sendSlowWarn { - switch msg.EventType() { - case model.WebsocketEventTyping, - model.WebsocketEventStatusChange, - model.WebsocketEventChannelViewed: - mlog.Warn( - "websocket.slow: dropping message", - mlog.String("user_id", wc.UserId), - mlog.String("type", msg.EventType()), - ) - return false - } - } - - // If the event contains sanitized data, only send to users that don't have permission to - // see sensitive data. Prevents admin clients from receiving events with bad data - var hasReadPrivateDataPermission *bool - if msg.GetBroadcast().ContainsSanitizedData { - hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) - - if *hasReadPrivateDataPermission { - return false - } - } - - // If the event contains sensitive data, only send to users with permission to see it - if msg.GetBroadcast().ContainsSensitiveData { - if hasReadPrivateDataPermission == nil { - hasReadPrivateDataPermission = model.NewBool(wc.App.RolesGrantPermission(wc.GetSession().GetUserRoles(), model.PermissionManageSystem.Id)) - } - - if !*hasReadPrivateDataPermission { - return false - } - } - - // If the event is destined to a specific connection - if msg.GetBroadcast().ConnectionId != "" { - return wc.GetConnectionID() == msg.GetBroadcast().ConnectionId - } - - // if the connection is omitted don't send the message - if wc.GetConnectionID() == msg.GetBroadcast().OmitConnectionId { - return false - } - - // If the event is destined to a specific user - if msg.GetBroadcast().UserId != "" { - return wc.UserId == msg.GetBroadcast().UserId - } - - // if the user is omitted don't send the message - if len(msg.GetBroadcast().OmitUsers) > 0 { - if _, ok := msg.GetBroadcast().OmitUsers[wc.UserId]; ok { - return false - } - } - - // Only report events to users who are in the channel for the event - if msg.GetBroadcast().ChannelId != "" { - if model.GetMillis()-wc.lastAllChannelMembersTime > webConnMemberCacheTime { - wc.allChannelMembers = nil - wc.lastAllChannelMembersTime = 0 - } - - if wc.allChannelMembers == nil { - result, err := wc.App.Srv().Store.Channel().GetAllChannelMembersForUser(wc.UserId, false, false) - if err != nil { - mlog.Error("webhub.shouldSendEvent.", mlog.Err(err)) - return false - } - wc.allChannelMembers = result - wc.lastAllChannelMembersTime = model.GetMillis() - } - - if _, ok := wc.allChannelMembers[msg.GetBroadcast().ChannelId]; ok { - return true - } - return false - } - - // Only report events to users who are in the team for the event - if msg.GetBroadcast().TeamId != "" { - return wc.isMemberOfTeam(msg.GetBroadcast().TeamId) - } - - if wc.GetSession().Props[model.SessionPropIsGuest] == "true" { - return wc.shouldSendEventToGuest(msg) - } - - return true -} - -// IsMemberOfTeam returns whether the user of the WebConn -// is a member of the given teamID or not. -func (wc *WebConn) isMemberOfTeam(teamID string) bool { - currentSession := wc.GetSession() - - if currentSession == nil || currentSession.Token == "" { - session, err := wc.App.GetSession(wc.GetSessionToken()) - if err != nil { - if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { - mlog.Debug("Invalid session.", mlog.Err(err)) - } else { - mlog.Error("Could not get session", mlog.String("session_token", wc.GetSessionToken()), mlog.Err(err)) - } - return false - } - wc.SetSession(session) - currentSession = session - } - - return currentSession.GetTeamByTeamId(teamID) != nil -} - -func (wc *WebConn) logSocketErr(source string, err error) { - // browsers will appear as CloseNoStatusReceived - if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseNoStatusReceived) { - mlog.Debug(source+": client side closed socket", mlog.String("user_id", wc.UserId)) - } else { - mlog.Debug(source+": closing websocket", mlog.String("user_id", wc.UserId), mlog.Err(err)) - } +func (a *App) NewWebConn(cfg *platform.WebConnConfig) *platform.WebConn { + return a.Srv().Platform().NewWebConn(cfg, a, a.ch.GetPluginsEnvironment) } diff --git a/app/web_conn_test.go b/app/web_conn_test.go index a28673e6e7..6c05aacf56 100644 --- a/app/web_conn_test.go +++ b/app/web_conn_test.go @@ -4,16 +4,12 @@ package app import ( - "bytes" - "net" - "net/http" - "net/http/httptest" "testing" - "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" ) @@ -30,10 +26,11 @@ func TestWebConnShouldSendEvent(t *testing.T) { }}) require.Nil(t, err) - basicUserWc := &WebConn{ - App: th.App, - UserId: th.BasicUser.Id, - T: i18n.T, + basicUserWc := &platform.WebConn{ + Platform: th.Server.Platform(), + Suite: th.App, + UserId: th.BasicUser.Id, + T: i18n.T, } user1ConnID := model.NewId() @@ -51,10 +48,11 @@ func TestWebConnShouldSendEvent(t *testing.T) { }}) require.Nil(t, err) - basicUser2Wc := &WebConn{ - App: th.App, - UserId: th.BasicUser2.Id, - T: i18n.T, + basicUser2Wc := &platform.WebConn{ + Platform: th.Server.Platform(), + Suite: th.App, + UserId: th.BasicUser2.Id, + T: i18n.T, } user2ConnID := model.NewId() @@ -66,10 +64,11 @@ func TestWebConnShouldSendEvent(t *testing.T) { session3, err := th.App.CreateSession(&model.Session{UserId: th.SystemAdminUser.Id, Roles: th.SystemAdminUser.GetRawRoles()}) require.Nil(t, err) - adminUserWc := &WebConn{ - App: th.App, - UserId: th.SystemAdminUser.Id, - T: i18n.T, + adminUserWc := &platform.WebConn{ + Platform: th.Server.Platform(), + Suite: th.App, + UserId: th.SystemAdminUser.Id, + T: i18n.T, } adminConnID := model.NewId() @@ -87,10 +86,11 @@ func TestWebConnShouldSendEvent(t *testing.T) { }}) require.Nil(t, err) - basicUserWc2 := &WebConn{ - App: th.App, - UserId: th.BasicUser.Id, - T: i18n.T, + basicUserWc2 := &platform.WebConn{ + Platform: th.Server.Platform(), + Suite: th.App, + UserId: th.BasicUser.Id, + T: i18n.T, } user1Conn2ID := model.NewId() @@ -131,24 +131,24 @@ func TestWebConnShouldSendEvent(t *testing.T) { t.Run(c.Description, func(t *testing.T) { event = event.SetBroadcast(c.Broadcast) if c.User1Expected { - assert.True(t, basicUserWc.shouldSendEvent(event), "expected user 1") + assert.True(t, basicUserWc.ShouldSendEvent(event), "expected user 1") } else { - assert.False(t, basicUserWc.shouldSendEvent(event), "did not expect user 1") + assert.False(t, basicUserWc.ShouldSendEvent(event), "did not expect user 1") } if c.User2Expected { - assert.True(t, basicUser2Wc.shouldSendEvent(event), "expected user 2") + assert.True(t, basicUser2Wc.ShouldSendEvent(event), "expected user 2") } else { - assert.False(t, basicUser2Wc.shouldSendEvent(event), "did not expect user 2") + assert.False(t, basicUser2Wc.ShouldSendEvent(event), "did not expect user 2") } if c.AdminExpected { - assert.True(t, adminUserWc.shouldSendEvent(event), "expected admin") + assert.True(t, adminUserWc.ShouldSendEvent(event), "expected admin") } else { - assert.False(t, adminUserWc.shouldSendEvent(event), "did not expect admin") + assert.False(t, adminUserWc.ShouldSendEvent(event), "did not expect admin") } if c.User1Conn2Expected { - assert.True(t, basicUserWc2.shouldSendEvent(event), "expected user 1 conn 2") + assert.True(t, basicUserWc2.ShouldSendEvent(event), "expected user 1 conn 2") } else { - assert.False(t, basicUserWc2.shouldSendEvent(event), "did not expect user 1 conn 2") + assert.False(t, basicUserWc2.ShouldSendEvent(event), "did not expect user 1 conn 2") } }) } @@ -156,17 +156,17 @@ func TestWebConnShouldSendEvent(t *testing.T) { t.Run("should send to basic user in basic channel", func(t *testing.T) { event = event.SetBroadcast(&model.WebsocketBroadcast{ChannelId: th.BasicChannel.Id}) - assert.True(t, basicUserWc.shouldSendEvent(event), "expected user 1") - assert.False(t, basicUser2Wc.shouldSendEvent(event), "did not expect user 2") - assert.False(t, adminUserWc.shouldSendEvent(event), "did not expect admin") + assert.True(t, basicUserWc.ShouldSendEvent(event), "expected user 1") + assert.False(t, basicUser2Wc.ShouldSendEvent(event), "did not expect user 2") + assert.False(t, adminUserWc.ShouldSendEvent(event), "did not expect admin") }) t.Run("should send to basic user and admin in channel2", func(t *testing.T) { event = event.SetBroadcast(&model.WebsocketBroadcast{ChannelId: channel2.Id}) - assert.True(t, basicUserWc.shouldSendEvent(event), "expected user 1") - assert.False(t, basicUser2Wc.shouldSendEvent(event), "did not expect user 2") - assert.True(t, adminUserWc.shouldSendEvent(event), "expected admin") + assert.True(t, basicUserWc.ShouldSendEvent(event), "expected user 1") + assert.False(t, basicUser2Wc.ShouldSendEvent(event), "did not expect user 2") + assert.True(t, adminUserWc.ShouldSendEvent(event), "expected admin") }) t.Run("channel member cache invalidated after user added to channel", func(t *testing.T) { @@ -174,224 +174,16 @@ func TestWebConnShouldSendEvent(t *testing.T) { basicUser2Wc.InvalidateCache() event = event.SetBroadcast(&model.WebsocketBroadcast{ChannelId: channel2.Id}) - assert.True(t, basicUserWc.shouldSendEvent(event), "expected user 1") - assert.True(t, basicUser2Wc.shouldSendEvent(event), "expected user 2") - assert.True(t, adminUserWc.shouldSendEvent(event), "expected admin") + assert.True(t, basicUserWc.ShouldSendEvent(event), "expected user 1") + assert.True(t, basicUser2Wc.ShouldSendEvent(event), "expected user 2") + assert.True(t, adminUserWc.ShouldSendEvent(event), "expected admin") }) event2 := model.NewWebSocketEvent(model.WebsocketEventUpdateTeam, th.BasicTeam.Id, "", "", nil, "") - assert.True(t, basicUserWc.shouldSendEvent(event2)) - assert.True(t, basicUser2Wc.shouldSendEvent(event2)) + assert.True(t, basicUserWc.ShouldSendEvent(event2)) + assert.True(t, basicUser2Wc.ShouldSendEvent(event2)) event3 := model.NewWebSocketEvent(model.WebsocketEventUpdateTeam, "wrongId", "", "", nil, "") - assert.False(t, basicUserWc.shouldSendEvent(event3)) -} - -func TestWebConnAddDeadQueue(t *testing.T) { - th := Setup(t) - defer th.TearDown() - - wc := th.App.NewWebConn(&WebConnConfig{ - WebSocket: &websocket.Conn{}, - }) - - for i := 0; i < 2; i++ { - msg := &model.WebSocketEvent{} - msg = msg.SetSequence(int64(i)) - wc.addToDeadQueue(msg) - } - - for i := 0; i < 2; i++ { - assert.Equal(t, int64(i), wc.deadQueue[i].GetSequence()) - } - - // Should push out the first two elements - for i := 0; i < deadQueueSize; i++ { - msg := &model.WebSocketEvent{} - msg = msg.SetSequence(int64(i + 2)) - wc.addToDeadQueue(msg) - } - for i := 0; i < deadQueueSize; i++ { - assert.Equal(t, int64(i+2), wc.deadQueue[(i+2)%deadQueueSize].GetSequence()) - } -} - -func TestWebConnIsInDeadQueue(t *testing.T) { - th := Setup(t) - defer th.TearDown() - - wc := th.App.NewWebConn(&WebConnConfig{ - WebSocket: &websocket.Conn{}, - }) - - var i int - for ; i < 2; i++ { - msg := &model.WebSocketEvent{} - msg = msg.SetSequence(int64(i)) - wc.addToDeadQueue(msg) - } - - wc.Sequence = int64(0) - ok, ind := wc.isInDeadQueue(wc.Sequence) - assert.True(t, ok) - assert.Equal(t, 0, ind) - assert.True(t, wc.hasMsgLoss()) - wc.Sequence = int64(1) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.True(t, ok) - assert.Equal(t, 1, ind) - assert.True(t, wc.hasMsgLoss()) - wc.Sequence = int64(2) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.False(t, ok) - assert.Equal(t, 0, ind) - assert.False(t, wc.hasMsgLoss()) - - for ; i < deadQueueSize+2; i++ { - msg := &model.WebSocketEvent{} - msg = msg.SetSequence(int64(i)) - wc.addToDeadQueue(msg) - } - - wc.Sequence = int64(129) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.True(t, ok) - assert.Equal(t, 1, ind) - wc.Sequence = int64(128) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.True(t, ok) - assert.Equal(t, 0, ind) - wc.Sequence = int64(2) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.True(t, ok) - assert.Equal(t, 2, ind) - assert.True(t, wc.hasMsgLoss()) - wc.Sequence = int64(0) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.False(t, ok) - assert.Equal(t, 0, ind) - wc.Sequence = int64(130) - ok, ind = wc.isInDeadQueue(wc.Sequence) - assert.False(t, ok) - assert.Equal(t, 0, ind) - assert.False(t, wc.hasMsgLoss()) -} - -func TestWebConnClearDeadQueue(t *testing.T) { - th := Setup(t) - defer th.TearDown() - - wc := th.App.NewWebConn(&WebConnConfig{ - WebSocket: &websocket.Conn{}, - }) - - var i int - for ; i < 2; i++ { - msg := &model.WebSocketEvent{} - msg = msg.SetSequence(int64(i)) - wc.addToDeadQueue(msg) - } - - wc.clearDeadQueue() - - assert.Equal(t, 0, wc.deadQueuePointer) -} - -func TestWebConnDrainDeadQueue(t *testing.T) { - th := Setup(t) - defer th.TearDown() - - var dialConn = func(t *testing.T, a *App, addr net.Addr) *WebConn { - d := websocket.Dialer{} - c, _, err := d.Dial("ws://"+addr.String()+"/ws", nil) - require.NoError(t, err) - - cfg := &WebConnConfig{ - WebSocket: c, - } - return a.NewWebConn(cfg) - } - - t.Run("Empty Queue", func(t *testing.T) { - var handler = func(t *testing.T) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - upgrader := &websocket.Upgrader{} - conn, err := upgrader.Upgrade(w, req, nil) - cnt := 0 - for err == nil { - _, _, err = conn.ReadMessage() - cnt++ - } - assert.Equal(t, 1, cnt) - if _, ok := err.(*websocket.CloseError); !ok { - require.NoError(t, err) - } - } - } - s := httptest.NewServer(handler(t)) - defer s.Close() - - wc := dialConn(t, th.App, s.Listener.Addr()) - defer wc.WebSocket.Close() - wc.clearDeadQueue() - - err := wc.drainDeadQueue(0) - require.NoError(t, err) - }) - - var handler = func(t *testing.T, seqNum int64, limit int) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - upgrader := &websocket.Upgrader{} - conn, err := upgrader.Upgrade(w, req, nil) - var buf []byte - i := seqNum - for err == nil { - _, buf, err = conn.ReadMessage() - if err != nil && len(buf) > 0 { - ev, jsonErr := model.WebSocketEventFromJSON(bytes.NewReader(buf)) - require.NoError(t, jsonErr) - require.LessOrEqual(t, int(i), limit) - assert.Equal(t, i, ev.GetSequence()) - i++ - } - } - if _, ok := err.(*websocket.CloseError); !ok { - require.NoError(t, err) - } - } - } - - run := func(seqNum int64, limit int) { - s := httptest.NewServer(handler(t, seqNum, limit)) - defer s.Close() - - wc := dialConn(t, th.App, s.Listener.Addr()) - defer wc.WebSocket.Close() - - for i := 0; i < limit; i++ { - msg := model.NewWebSocketEvent("", "", "", "", map[string]bool{}, "") - msg = msg.SetSequence(int64(i)) - wc.addToDeadQueue(msg) - } - wc.Sequence = seqNum - ok, index := wc.isInDeadQueue(wc.Sequence) - require.True(t, ok) - - err := wc.drainDeadQueue(index) - require.NoError(t, err) - } - - t.Run("Half-full Queue", func(t *testing.T) { - t.Run("Middle", func(t *testing.T) { run(int64(2), 10) }) - t.Run("Beginning", func(t *testing.T) { run(int64(0), 10) }) - t.Run("End", func(t *testing.T) { run(int64(9), 10) }) - t.Run("Full", func(t *testing.T) { run(int64(deadQueueSize-1), deadQueueSize) }) - }) - - t.Run("Cycled Queue", func(t *testing.T) { - t.Run("First un-overwritten", func(t *testing.T) { run(int64(10), deadQueueSize+10) }) - t.Run("End", func(t *testing.T) { run(int64(127), deadQueueSize+10) }) - t.Run("Cycled End", func(t *testing.T) { run(int64(137), deadQueueSize+10) }) - t.Run("Overwritten First", func(t *testing.T) { run(int64(128), deadQueueSize+10) }) - }) + assert.False(t, basicUserWc.ShouldSendEvent(event3)) + } diff --git a/app/web_hub.go b/app/web_hub.go index b73ed86f38..fe2a7114da 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -4,705 +4,66 @@ package app import ( - "hash/maphash" - "runtime" - "runtime/debug" - "strconv" - "sync/atomic" - "time" - + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/shared/mlog" ) -const ( - broadcastQueueSize = 4096 - inactiveConnReaperInterval = 5 * time.Minute -) - -type webConnActivityMessage struct { - userID string - sessionToken string - activityAt int64 -} - -type webConnDirectMessage struct { - conn *WebConn - msg model.WebSocketMessage -} - -type webConnSessionMessage struct { - userID string - sessionToken string - isRegistered chan bool -} - -type webConnCheckMessage struct { - userID string - connectionID string - result chan *CheckConnResult -} - -// Hub is the central place to manage all websocket connections in the server. -// It handles different websocket events and sending messages to individual -// user connections. -type Hub struct { - // connectionCount should be kept first. - // See https://github.com/mattermost/mattermost-server/pull/7281 - connectionCount int64 - srv *Server - connectionIndex int - register chan *WebConn - unregister chan *WebConn - broadcast chan *model.WebSocketEvent - stop chan struct{} - didStop chan struct{} - invalidateUser chan string - activity chan *webConnActivityMessage - directMsg chan *webConnDirectMessage - explicitStop bool - checkRegistered chan *webConnSessionMessage - checkConn chan *webConnCheckMessage -} - -// newWebHub creates a new Hub. -func newWebHub(s *Server) *Hub { - return &Hub{ - srv: s, - register: make(chan *WebConn), - unregister: make(chan *WebConn), - broadcast: make(chan *model.WebSocketEvent, broadcastQueueSize), - stop: make(chan struct{}), - didStop: make(chan struct{}), - invalidateUser: make(chan string), - activity: make(chan *webConnActivityMessage), - directMsg: make(chan *webConnDirectMessage), - checkRegistered: make(chan *webConnSessionMessage), - checkConn: make(chan *webConnCheckMessage), - } -} - func (a *App) TotalWebsocketConnections() int { - return a.Srv().TotalWebsocketConnections() + return a.Srv().Platform().TotalWebsocketConnections() } -// HubStart starts all the hubs. -func (s *Server) HubStart() { - // Total number of hubs is twice the number of CPUs. - numberOfHubs := runtime.NumCPU() * 2 - s.Log().Info("Starting websocket hubs", mlog.Int("number_of_hubs", numberOfHubs)) - - hubs := make([]*Hub, numberOfHubs) - - for i := 0; i < numberOfHubs; i++ { - hubs[i] = newWebHub(s) - hubs[i].connectionIndex = i - hubs[i].Start() - } - // Assigning to the hubs slice without any mutex is fine because it is only assigned once - // during the start of the program and always read from after that. - s.hubs = hubs -} - -func (a *App) invalidateCacheForWebhook(webhookID string) { - a.Srv().Store.Webhook().InvalidateWebhookCache(webhookID) -} - -// HubStop stops all the hubs. -func (s *Server) HubStop() { - mlog.Info("stopping websocket hub connections") - - for _, hub := range s.hubs { - hub.Stop() - } -} - -// GetHubForUserId returns the hub for a given user id. -func (s *Server) GetHubForUserId(userID string) *Hub { - // TODO: check if caching the userID -> hub mapping - // is worth the memory tradeoff. - // https://mattermost.atlassian.net/browse/MM-26629. - var hash maphash.Hash - hash.SetSeed(s.hashSeed) - hash.Write([]byte(userID)) - index := hash.Sum64() % uint64(len(s.hubs)) - - return s.hubs[int(index)] -} - -func (a *App) GetHubForUserId(userID string) *Hub { - return a.Srv().GetHubForUserId(userID) +func (a *App) GetHubForUserId(userID string) *platform.Hub { + return a.Srv().Platform().GetHubForUserId(userID) } // HubRegister registers a connection to a hub. -func (a *App) HubRegister(webConn *WebConn) { - hub := a.GetHubForUserId(webConn.UserId) - if hub != nil { - if metrics := a.Metrics(); metrics != nil { - metrics.IncrementWebSocketBroadcastUsersRegistered(strconv.Itoa(hub.connectionIndex), 1) - } - hub.Register(webConn) - } +func (a *App) HubRegister(webConn *platform.WebConn) { + a.Srv().Platform().HubRegister(webConn) } // HubUnregister unregisters a connection from a hub. -func (a *App) HubUnregister(webConn *WebConn) { - hub := a.GetHubForUserId(webConn.UserId) - if hub != nil { - if metrics := a.Metrics(); metrics != nil { - metrics.DecrementWebSocketBroadcastUsersRegistered(strconv.Itoa(hub.connectionIndex), 1) - } - hub.Unregister(webConn) - } -} - -func (s *Server) Publish(message *model.WebSocketEvent) { - if s.GetMetrics() != nil { - s.GetMetrics().IncrementWebsocketEvent(message.EventType()) - } - - s.PublishSkipClusterSend(message) - - if s.Cluster != nil { - data, err := message.ToJSON() - if err != nil { - mlog.Warn("Failed to encode message to JSON", mlog.Err(err)) - } - cm := &model.ClusterMessage{ - Event: model.ClusterEventPublish, - SendType: model.ClusterSendBestEffort, - Data: data, - } - - if message.EventType() == model.WebsocketEventPosted || - message.EventType() == model.WebsocketEventPostEdited || - message.EventType() == model.WebsocketEventDirectAdded || - message.EventType() == model.WebsocketEventGroupAdded || - message.EventType() == model.WebsocketEventAddedToTeam || - message.GetBroadcast().ReliableClusterSend { - cm.SendType = model.ClusterSendReliable - } - - s.Cluster.SendClusterMessage(cm) - } +func (a *App) HubUnregister(webConn *platform.WebConn) { + a.Srv().Platform().HubUnregister(webConn) } func (a *App) Publish(message *model.WebSocketEvent) { - a.Srv().Publish(message) + a.Srv().Platform().Publish(message) } func (ch *Channels) Publish(message *model.WebSocketEvent) { - ch.srv.Publish(message) -} - -func (s *Server) PublishSkipClusterSend(event *model.WebSocketEvent) { - if event.GetBroadcast().UserId != "" { - hub := s.GetHubForUserId(event.GetBroadcast().UserId) - if hub != nil { - hub.Broadcast(event) - } - } else { - for _, hub := range s.hubs { - hub.Broadcast(event) - } - } - - // Notify shared channel sync service - s.SharedChannelSyncHandler(event) -} - -func (a *App) invalidateCacheForChannel(channel *model.Channel) { - a.Srv().Store.Channel().InvalidateChannel(channel.Id) - a.Srv().invalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) - - if a.Cluster() != nil { - nameMsg := &model.ClusterMessage{ - Event: model.ClusterEventInvalidateCacheForChannelByName, - SendType: model.ClusterSendBestEffort, - Props: make(map[string]string), - } - - nameMsg.Props["name"] = channel.Name - if channel.TeamId == "" { - nameMsg.Props["id"] = "dm" - } else { - nameMsg.Props["id"] = channel.TeamId - } - - a.Cluster().SendClusterMessage(nameMsg) - } + ch.srv.Platform().Publish(message) } func (a *App) invalidateCacheForChannelMembers(channelID string) { - a.Srv().Store.User().InvalidateProfilesInChannelCache(channelID) - a.Srv().Store.Channel().InvalidateMemberCount(channelID) - a.Srv().Store.Channel().InvalidateGuestCount(channelID) + a.Srv().Platform().InvalidateCacheForChannelMembers(channelID) } func (a *App) invalidateCacheForChannelMembersNotifyProps(channelID string) { - a.Srv().invalidateCacheForChannelMembersNotifyPropsSkipClusterSend(channelID) - - if a.Cluster() != nil { - msg := &model.ClusterMessage{ - Event: model.ClusterEventInvalidateCacheForChannelMembersNotifyProps, - SendType: model.ClusterSendBestEffort, - Data: []byte(channelID), - } - a.Cluster().SendClusterMessage(msg) - } + a.Srv().Platform().InvalidateCacheForChannelMembersNotifyProps(channelID) } func (a *App) invalidateCacheForChannelPosts(channelID string) { - a.Srv().Store.Channel().InvalidatePinnedPostCount(channelID) - a.Srv().Store.Post().InvalidateLastPostTimeCache(channelID) + a.Srv().Platform().InvalidateCacheForChannelPosts(channelID) } func (a *App) InvalidateCacheForUser(userID string) { - a.Srv().invalidateCacheForUserSkipClusterSend(userID) - - a.ch.srv.userService.InvalidateCacheForUser(userID) + a.Srv().Platform().InvalidateCacheForUser(userID) } func (a *App) invalidateCacheForUserTeams(userID string) { - a.Srv().invalidateWebConnSessionCacheForUser(userID) - a.Srv().Store.Team().InvalidateAllTeamIdsForUser(userID) - - if a.Cluster() != nil { - msg := &model.ClusterMessage{ - Event: model.ClusterEventInvalidateCacheForUserTeams, - SendType: model.ClusterSendBestEffort, - Data: []byte(userID), - } - a.Cluster().SendClusterMessage(msg) - } + a.Srv().Platform().InvalidateCacheForUserTeams(userID) } // UpdateWebConnUserActivity sets the LastUserActivityAt of the hub for the given session. func (a *App) UpdateWebConnUserActivity(session model.Session, activityAt int64) { - hub := a.GetHubForUserId(session.UserId) - if hub != nil { - hub.UpdateActivity(session.UserId, session.Token, activityAt) - } + a.Srv().Platform().UpdateWebConnUserActivity(session, activityAt) } // SessionIsRegistered determines if a specific session has been registered func (a *App) SessionIsRegistered(session model.Session) bool { - hub := a.GetHubForUserId(session.UserId) - if hub != nil { - return hub.IsRegistered(session.UserId, session.Token) - } - return false + return a.Srv().Platform().SessionIsRegistered(session) } -func (a *App) CheckWebConn(userID, connectionID string) *CheckConnResult { - hub := a.GetHubForUserId(userID) - if hub != nil { - return hub.CheckConn(userID, connectionID) - } - return nil -} - -// Register registers a connection to the hub. -func (h *Hub) Register(webConn *WebConn) { - select { - case h.register <- webConn: - case <-h.stop: - } -} - -// Unregister unregisters a connection from the hub. -func (h *Hub) Unregister(webConn *WebConn) { - select { - case h.unregister <- webConn: - case <-h.stop: - } -} - -// Determines if a user's session is registered a connection from the hub. -func (h *Hub) IsRegistered(userID, sessionToken string) bool { - ws := &webConnSessionMessage{ - userID: userID, - sessionToken: sessionToken, - isRegistered: make(chan bool), - } - select { - case h.checkRegistered <- ws: - return <-ws.isRegistered - case <-h.stop: - } - return false -} - -func (h *Hub) CheckConn(userID, connectionID string) *CheckConnResult { - req := &webConnCheckMessage{ - userID: userID, - connectionID: connectionID, - result: make(chan *CheckConnResult), - } - select { - case h.checkConn <- req: - return <-req.result - case <-h.stop: - } - return nil -} - -// Broadcast broadcasts the message to all connections in the hub. -func (h *Hub) Broadcast(message *model.WebSocketEvent) { - // XXX: The hub nil check is because of the way we setup our tests. We call - // `app.NewServer()` which returns a server, but only after that, we call - // `wsapi.Init()` to initialize the hub. But in the `NewServer` call - // itself proceeds to broadcast some messages happily. This needs to be - // fixed once the wsapi cyclic dependency with server/app goes away. - // And possibly, we can look into doing the hub initialization inside - // NewServer itself. - if h != nil && message != nil { - if metrics := h.srv.GetMetrics(); metrics != nil { - metrics.IncrementWebSocketBroadcastBufferSize(strconv.Itoa(h.connectionIndex), 1) - } - select { - case h.broadcast <- message: - case <-h.stop: - } - } -} - -// InvalidateUser invalidates the cache for the given user. -func (h *Hub) InvalidateUser(userID string) { - select { - case h.invalidateUser <- userID: - case <-h.stop: - } -} - -// UpdateActivity sets the LastUserActivityAt field for the connection -// of the user. -func (h *Hub) UpdateActivity(userID, sessionToken string, activityAt int64) { - select { - case h.activity <- &webConnActivityMessage{ - userID: userID, - sessionToken: sessionToken, - activityAt: activityAt, - }: - case <-h.stop: - } -} - -// SendMessage sends the given message to the given connection. -func (h *Hub) SendMessage(conn *WebConn, msg model.WebSocketMessage) { - select { - case h.directMsg <- &webConnDirectMessage{ - conn: conn, - msg: msg, - }: - case <-h.stop: - } -} - -// Stop stops the hub. -func (h *Hub) Stop() { - close(h.stop) - <-h.didStop -} - -// Start starts the hub. -func (h *Hub) Start() { - var doStart func() - var doRecoverableStart func() - var doRecover func() - - doStart = func() { - mlog.Debug("Hub is starting", mlog.Int("index", h.connectionIndex)) - - ticker := time.NewTicker(inactiveConnReaperInterval) - defer ticker.Stop() - - appInstance := New(ServerConnector(h.srv.Channels())) - - connIndex := newHubConnectionIndex(inactiveConnReaperInterval) - - for { - select { - case webSessionMessage := <-h.checkRegistered: - conns := connIndex.ForUser(webSessionMessage.userID) - var isRegistered bool - for _, conn := range conns { - if !conn.active { - continue - } - if conn.GetSessionToken() == webSessionMessage.sessionToken { - isRegistered = true - } - } - webSessionMessage.isRegistered <- isRegistered - case req := <-h.checkConn: - var res *CheckConnResult - conn := connIndex.RemoveInactiveByConnectionID(req.userID, req.connectionID) - if conn != nil { - res = &CheckConnResult{ - ConnectionID: req.connectionID, - UserID: req.userID, - ActiveQueue: conn.send, - DeadQueue: conn.deadQueue, - DeadQueuePointer: conn.deadQueuePointer, - ReuseCount: conn.reuseCount + 1, - } - } - req.result <- res - case <-ticker.C: - connIndex.RemoveInactiveConnections() - case webConn := <-h.register: - // Mark the current one as active. - // There is no need to check if it was inactive or not, - // we will anyways need to make it active. - webConn.active = true - - connIndex.Add(webConn) - atomic.StoreInt64(&h.connectionCount, int64(connIndex.AllActive())) - - if webConn.IsAuthenticated() && webConn.reuseCount == 0 { - // The hello message should only be sent when the reuseCount is 0. - // i.e in server restart, or long timeout, or fresh connection case. - // In case of seq number not found in dead queue, it is handled by - // the webconn write pump. - webConn.send <- webConn.createHelloMessage() - } - case webConn := <-h.unregister: - // If already removed (via queue full), then removing again becomes a noop. - // But if not removed, mark inactive. - webConn.active = false - - atomic.StoreInt64(&h.connectionCount, int64(connIndex.AllActive())) - - if webConn.UserId == "" { - continue - } - - conns := connIndex.ForUser(webConn.UserId) - if len(conns) == 0 || areAllInactive(conns) { - h.srv.Go(func() { - appInstance.SetStatusOffline(webConn.UserId, false) - }) - continue - } - var latestActivity int64 = 0 - for _, conn := range conns { - if !conn.active { - continue - } - if conn.lastUserActivityAt > latestActivity { - latestActivity = conn.lastUserActivityAt - } - } - - if appInstance.IsUserAway(latestActivity) { - h.srv.Go(func() { - appInstance.SetStatusLastActivityAt(webConn.UserId, latestActivity) - }) - } - case userID := <-h.invalidateUser: - for _, webConn := range connIndex.ForUser(userID) { - webConn.InvalidateCache() - } - case activity := <-h.activity: - for _, webConn := range connIndex.ForUser(activity.userID) { - if !webConn.active { - continue - } - if webConn.GetSessionToken() == activity.sessionToken { - webConn.lastUserActivityAt = activity.activityAt - } - } - case directMsg := <-h.directMsg: - if !connIndex.Has(directMsg.conn) { - continue - } - select { - case directMsg.conn.send <- directMsg.msg: - default: - mlog.Error("webhub.broadcast: cannot send, closing websocket for user", mlog.String("user_id", directMsg.conn.UserId)) - close(directMsg.conn.send) - connIndex.Remove(directMsg.conn) - } - case msg := <-h.broadcast: - if metrics := h.srv.GetMetrics(); metrics != nil { - metrics.DecrementWebSocketBroadcastBufferSize(strconv.Itoa(h.connectionIndex), 1) - } - msg = msg.PrecomputeJSON() - broadcast := func(webConn *WebConn) { - if !connIndex.Has(webConn) { - return - } - if webConn.shouldSendEvent(msg) { - select { - case webConn.send <- msg: - default: - mlog.Error("webhub.broadcast: cannot send, closing websocket for user", mlog.String("user_id", webConn.UserId)) - close(webConn.send) - connIndex.Remove(webConn) - } - } - } - - if connID := msg.GetBroadcast().ConnectionId; connID != "" { - if webConn := connIndex.byConnectionId[connID]; webConn != nil { - broadcast(webConn) - continue - } - } else if msg.GetBroadcast().UserId != "" { - candidates := connIndex.ForUser(msg.GetBroadcast().UserId) - for _, webConn := range candidates { - broadcast(webConn) - } - continue - } - - candidates := connIndex.All() - for webConn := range candidates { - broadcast(webConn) - } - case <-h.stop: - for webConn := range connIndex.All() { - webConn.Close() - appInstance.SetStatusOffline(webConn.UserId, false) - } - - h.explicitStop = true - close(h.didStop) - - return - } - } - } - - doRecoverableStart = func() { - defer doRecover() - doStart() - } - - doRecover = func() { - if !h.explicitStop { - if r := recover(); r != nil { - mlog.Error("Recovering from Hub panic.", mlog.Any("panic", r)) - } else { - mlog.Error("Webhub stopped unexpectedly. Recovering.") - } - - mlog.Error(string(debug.Stack())) - - go doRecoverableStart() - } - } - - go doRecoverableStart() -} - -// hubConnectionIndex provides fast addition, removal, and iteration of web connections. -// It requires 3 functionalities which need to be very fast: -// - check if a connection exists or not. -// - get all connections for a given userID. -// - get all connections. -type hubConnectionIndex struct { - // byUserId stores the list of connections for a given userID - byUserId map[string][]*WebConn - // byConnection serves the dual purpose of storing the index of the webconn - // in the value of byUserId map, and also to get all connections. - byConnection map[*WebConn]int - byConnectionId map[string]*WebConn - // staleThreshold is the limit beyond which inactive connections - // will be deleted. - staleThreshold time.Duration -} - -func newHubConnectionIndex(interval time.Duration) *hubConnectionIndex { - return &hubConnectionIndex{ - byUserId: make(map[string][]*WebConn), - byConnection: make(map[*WebConn]int), - byConnectionId: make(map[string]*WebConn), - staleThreshold: interval, - } -} - -func (i *hubConnectionIndex) Add(wc *WebConn) { - i.byUserId[wc.UserId] = append(i.byUserId[wc.UserId], wc) - i.byConnection[wc] = len(i.byUserId[wc.UserId]) - 1 - i.byConnectionId[wc.GetConnectionID()] = wc -} - -func (i *hubConnectionIndex) Remove(wc *WebConn) { - wc.App.Srv().userService.ReturnSessionToPool(wc.GetSession()) - - userConnIndex, ok := i.byConnection[wc] - if !ok { - return - } - - // get the conn slice. - userConnections := i.byUserId[wc.UserId] - // get the last connection. - last := userConnections[len(userConnections)-1] - // set the slot that we are trying to remove to be the last connection. - userConnections[userConnIndex] = last - // remove the last connection from the slice. - i.byUserId[wc.UserId] = userConnections[:len(userConnections)-1] - // set the index of the connection that was moved to the new index. - i.byConnection[last] = userConnIndex - - delete(i.byConnection, wc) - delete(i.byConnectionId, wc.GetConnectionID()) -} - -func (i *hubConnectionIndex) Has(wc *WebConn) bool { - _, ok := i.byConnection[wc] - return ok -} - -// ForUser returns all connections for a user ID. -func (i *hubConnectionIndex) ForUser(id string) []*WebConn { - return i.byUserId[id] -} - -// All returns the full webConn index. -func (i *hubConnectionIndex) All() map[*WebConn]int { - return i.byConnection -} - -// RemoveInactiveByConnectionID removes an inactive connection for the given -// userID and connectionID. -func (i *hubConnectionIndex) RemoveInactiveByConnectionID(userID, connectionID string) *WebConn { - // To handle empty sessions. - if userID == "" { - return nil - } - for _, conn := range i.ForUser(userID) { - if conn.GetConnectionID() == connectionID && !conn.active { - i.Remove(conn) - return conn - } - } - return nil -} - -// RemoveInactiveConnections removes all inactive connections whose lastUserActivityAt -// exceeded staleThreshold. -func (i *hubConnectionIndex) RemoveInactiveConnections() { - now := model.GetMillis() - for conn := range i.byConnection { - if !conn.active && now-conn.lastUserActivityAt > i.staleThreshold.Milliseconds() { - i.Remove(conn) - } - } -} - -// AllActive returns the number of active connections. -// This is only called during register/unregister so we can take -// a bit of perf hit here. -func (i *hubConnectionIndex) AllActive() int { - cnt := 0 - for conn := range i.byConnection { - if conn.active { - cnt++ - } - } - return cnt +func (a *App) CheckWebConn(userID, connectionID string) *platform.CheckConnResult { + return a.Srv().Platform().CheckWebConn(userID, connectionID) } diff --git a/app/webhook.go b/app/webhook.go index e519d74353..c782af9a0c 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -37,7 +37,7 @@ func (a *App) handleWebhookEvents(c request.CTX, post *model.Post, team *model.T return nil } - hooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(team.Id, -1, -1) + hooks, err := a.Srv().Store().Webhook().GetOutgoingByTeam(team.Id, -1, -1) if err != nil { return model.NewAppError("handleWebhookEvents", "app.webhooks.get_outgoing_by_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -341,7 +341,7 @@ func (a *App) CreateIncomingWebhookForChannel(creatorId string, channel *model.C return nil, model.NewAppError("CreateIncomingWebhookForChannel", "api.incoming_webhook.invalid_username.app_error", nil, "", http.StatusBadRequest) } - webhook, err := a.Srv().Store.Webhook().SaveIncoming(hook) + webhook, err := a.Srv().Store().Webhook().SaveIncoming(hook) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -381,11 +381,11 @@ func (a *App) UpdateIncomingWebhook(oldHook, updatedHook *model.IncomingWebhook) updatedHook.TeamId = oldHook.TeamId updatedHook.DeleteAt = oldHook.DeleteAt - newWebhook, err := a.Srv().Store.Webhook().UpdateIncoming(updatedHook) + newWebhook, err := a.Srv().Store().Webhook().UpdateIncoming(updatedHook) if err != nil { return nil, model.NewAppError("UpdateIncomingWebhook", "app.webhooks.update_incoming.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - a.invalidateCacheForWebhook(oldHook.Id) + a.Srv().Platform().InvalidateCacheForWebhook(oldHook.Id) return newWebhook, nil } @@ -394,11 +394,11 @@ func (a *App) DeleteIncomingWebhook(hookID string) *model.AppError { return model.NewAppError("DeleteIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if err := a.Srv().Store.Webhook().DeleteIncoming(hookID, model.GetMillis()); err != nil { + if err := a.Srv().Store().Webhook().DeleteIncoming(hookID, model.GetMillis()); err != nil { return model.NewAppError("DeleteIncomingWebhook", "app.webhooks.delete_incoming.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } - a.invalidateCacheForWebhook(hookID) + a.Srv().Platform().InvalidateCacheForWebhook(hookID) return nil } @@ -408,7 +408,7 @@ func (a *App) GetIncomingWebhook(hookID string) (*model.IncomingWebhook, *model. return nil, model.NewAppError("GetIncomingWebhook", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhook, err := a.Srv().Store.Webhook().GetIncoming(hookID, true) + webhook, err := a.Srv().Store().Webhook().GetIncoming(hookID, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -431,7 +431,7 @@ func (a *App) GetIncomingWebhooksForTeamPageByUser(teamID string, userID string, return nil, model.NewAppError("GetIncomingWebhooksForTeamPage", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhooks, err := a.Srv().Store.Webhook().GetIncomingByTeamByUser(teamID, userID, page*perPage, perPage) + webhooks, err := a.Srv().Store().Webhook().GetIncomingByTeamByUser(teamID, userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetIncomingWebhooksForTeamPage", "app.webhooks.get_incoming_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -444,7 +444,7 @@ func (a *App) GetIncomingWebhooksPageByUser(userID string, page, perPage int) ([ return nil, model.NewAppError("GetIncomingWebhooksPageByUser", "api.incoming_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhooks, err := a.Srv().Store.Webhook().GetIncomingListByUser(userID, page*perPage, perPage) + webhooks, err := a.Srv().Store().Webhook().GetIncomingListByUser(userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetIncomingWebhooksPageByUser", "app.webhooks.get_incoming_by_user.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -462,7 +462,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } if hook.ChannelId != "" { - channel, errCh := a.Srv().Store.Channel().Get(hook.ChannelId, true) + channel, errCh := a.Srv().Store().Channel().Get(hook.ChannelId, true) if errCh != nil { var nfErr *store.ErrNotFound switch { @@ -484,7 +484,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin return nil, model.NewAppError("CreateOutgoingWebhook", "api.webhook.create_outgoing.triggers.app_error", nil, "", http.StatusBadRequest) } - allHooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1) + allHooks, err := a.Srv().Store().Webhook().GetOutgoingByTeam(hook.TeamId, -1, -1) if err != nil { return nil, model.NewAppError("CreateOutgoingWebhook", "app.webhooks.get_outgoing_by_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -497,7 +497,7 @@ func (a *App) CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.Outgoin } } - webhook, err := a.Srv().Store.Webhook().SaveOutgoing(hook) + webhook, err := a.Srv().Store().Webhook().SaveOutgoing(hook) if err != nil { var appErr *model.AppError var invErr *store.ErrInvalidInput @@ -536,7 +536,7 @@ func (a *App) UpdateOutgoingWebhook(c request.CTX, oldHook, updatedHook *model.O return nil, model.NewAppError("UpdateOutgoingWebhook", "api.webhook.create_outgoing.triggers.app_error", nil, "", http.StatusInternalServerError) } - allHooks, err := a.Srv().Store.Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1) + allHooks, err := a.Srv().Store().Webhook().GetOutgoingByTeam(oldHook.TeamId, -1, -1) if err != nil { return nil, model.NewAppError("UpdateOutgoingWebhook", "app.webhooks.get_outgoing_by_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -556,7 +556,7 @@ func (a *App) UpdateOutgoingWebhook(c request.CTX, oldHook, updatedHook *model.O updatedHook.TeamId = oldHook.TeamId updatedHook.UpdateAt = model.GetMillis() - webhook, err := a.Srv().Store.Webhook().UpdateOutgoing(updatedHook) + webhook, err := a.Srv().Store().Webhook().UpdateOutgoing(updatedHook) if err != nil { return nil, model.NewAppError("UpdateOutgoingWebhook", "app.webhooks.update_outgoing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -569,7 +569,7 @@ func (a *App) GetOutgoingWebhook(hookID string) (*model.OutgoingWebhook, *model. return nil, model.NewAppError("GetOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhook, err := a.Srv().Store.Webhook().GetOutgoing(hookID) + webhook, err := a.Srv().Store().Webhook().GetOutgoing(hookID) if err != nil { var nfErr *store.ErrNotFound switch { @@ -592,7 +592,7 @@ func (a *App) GetOutgoingWebhooksPageByUser(userID string, page, perPage int) ([ return nil, model.NewAppError("GetOutgoingWebhooksPageByUser", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhooks, err := a.Srv().Store.Webhook().GetOutgoingListByUser(userID, page*perPage, perPage) + webhooks, err := a.Srv().Store().Webhook().GetOutgoingListByUser(userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetOutgoingWebhooksPageByUser", "app.webhooks.get_outgoing_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -605,7 +605,7 @@ func (a *App) GetOutgoingWebhooksForChannelPageByUser(channelID string, userID s return nil, model.NewAppError("GetOutgoingWebhooksForChannelPage", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhooks, err := a.Srv().Store.Webhook().GetOutgoingByChannelByUser(channelID, userID, page*perPage, perPage) + webhooks, err := a.Srv().Store().Webhook().GetOutgoingByChannelByUser(channelID, userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetOutgoingWebhooksForChannelPage", "app.webhooks.get_outgoing_by_channel.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -622,7 +622,7 @@ func (a *App) GetOutgoingWebhooksForTeamPageByUser(teamID string, userID string, return nil, model.NewAppError("GetOutgoingWebhooksForTeamPageByUser", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - webhooks, err := a.Srv().Store.Webhook().GetOutgoingByTeamByUser(teamID, userID, page*perPage, perPage) + webhooks, err := a.Srv().Store().Webhook().GetOutgoingByTeamByUser(teamID, userID, page*perPage, perPage) if err != nil { return nil, model.NewAppError("GetOutgoingWebhooksForTeamPageByUser", "app.webhooks.get_outgoing_by_team.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -635,7 +635,7 @@ func (a *App) DeleteOutgoingWebhook(hookID string) *model.AppError { return model.NewAppError("DeleteOutgoingWebhook", "api.outgoing_webhook.disabled.app_error", nil, "", http.StatusNotImplemented) } - if err := a.Srv().Store.Webhook().DeleteOutgoing(hookID, model.GetMillis()); err != nil { + if err := a.Srv().Store().Webhook().DeleteOutgoing(hookID, model.GetMillis()); err != nil { return model.NewAppError("DeleteOutgoingWebhook", "app.webhooks.delete_outgoing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -649,7 +649,7 @@ func (a *App) RegenOutgoingWebhookToken(hook *model.OutgoingWebhook) (*model.Out hook.Token = model.NewId() - webhook, err := a.Srv().Store.Webhook().UpdateOutgoing(hook) + webhook, err := a.Srv().Store().Webhook().UpdateOutgoing(hook) if err != nil { return nil, model.NewAppError("RegenOutgoingWebhookToken", "app.webhooks.update_outgoing.app_error", nil, "", http.StatusInternalServerError).Wrap(err) } @@ -664,7 +664,7 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode hchan := make(chan store.StoreResult, 1) go func() { - webhook, err := a.Srv().Store.Webhook().GetIncoming(hookID, true) + webhook, err := a.Srv().Store().Webhook().GetIncoming(hookID, true) hchan <- store.StoreResult{Data: webhook, NErr: err} close(hchan) }() @@ -690,7 +690,7 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode uchan := make(chan store.StoreResult, 1) go func() { - user, err := a.Srv().Store.User().Get(context.Background(), hook.UserId) + user, err := a.Srv().Store().User().Get(context.Background(), hook.UserId) uchan <- store.StoreResult{Data: user, NErr: err} close(uchan) }() @@ -714,7 +714,7 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode if channelName != "" { if channelName[0] == '@' { - result, nErr := a.Srv().Store.User().GetByUsername(channelName[1:]) + result, nErr := a.Srv().Store().User().GetByUsername(channelName[1:]) if nErr != nil { return model.NewAppError("HandleIncomingWebhook", "web.incoming_webhook.user.app_error", nil, "", http.StatusBadRequest).Wrap(nErr) } @@ -726,21 +726,21 @@ func (a *App) HandleIncomingWebhook(c *request.Context, hookID string, req *mode } else if channelName[0] == '#' { cchan = make(chan store.StoreResult, 1) go func() { - chnn, chnnErr := a.Srv().Store.Channel().GetByName(hook.TeamId, channelName[1:], true) + chnn, chnnErr := a.Srv().Store().Channel().GetByName(hook.TeamId, channelName[1:], true) cchan <- store.StoreResult{Data: chnn, NErr: chnnErr} close(cchan) }() } else { cchan = make(chan store.StoreResult, 1) go func() { - chnn, chnnErr := a.Srv().Store.Channel().GetByName(hook.TeamId, channelName, true) + chnn, chnnErr := a.Srv().Store().Channel().GetByName(hook.TeamId, channelName, true) cchan <- store.StoreResult{Data: chnn, NErr: chnnErr} close(cchan) }() } } else { var err error - channel, err = a.Srv().Store.Channel().Get(hook.ChannelId, true) + channel, err = a.Srv().Store().Channel().Get(hook.ChannelId, true) if err != nil { var nfErr *store.ErrNotFound switch { @@ -801,7 +801,7 @@ func (a *App) CreateCommandWebhook(commandID string, args *model.CommandArgs) (* RootId: args.RootId, } - savedHook, err := a.Srv().Store.CommandWebhook().Save(hook) + savedHook, err := a.Srv().Store().CommandWebhook().Save(hook) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -823,7 +823,7 @@ func (a *App) HandleCommandWebhook(c *request.Context, hookID string, response * return model.NewAppError("HandleCommandWebhook", "app.command_webhook.handle_command_webhook.parse", nil, "", http.StatusBadRequest) } - hook, nErr := a.Srv().Store.CommandWebhook().Get(hookID) + hook, nErr := a.Srv().Store().CommandWebhook().Get(hookID) if nErr != nil { var nfErr *store.ErrNotFound switch { @@ -834,7 +834,7 @@ func (a *App) HandleCommandWebhook(c *request.Context, hookID string, response * } } - cmd, cmdErr := a.Srv().Store.Command().Get(hook.CommandId) + cmd, cmdErr := a.Srv().Store().Command().Get(hook.CommandId) if cmdErr != nil { var appErr *model.AppError switch { @@ -852,7 +852,7 @@ func (a *App) HandleCommandWebhook(c *request.Context, hookID string, response * RootId: hook.RootId, } - if nErr := a.Srv().Store.CommandWebhook().TryUse(hook.Id, 5); nErr != nil { + if nErr := a.Srv().Store().CommandWebhook().TryUse(hook.Id, 5); nErr != nil { var invErr *store.ErrInvalidInput switch { case errors.As(nErr, &invErr): diff --git a/app/websocket_router.go b/app/websocket_router.go index 82884a17da..eb88aeacf6 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -3,111 +3,111 @@ package app -import ( - "net/http" +// import ( +// "net/http" - "github.com/mattermost/mattermost-server/v6/model" - "github.com/mattermost/mattermost-server/v6/shared/i18n" - "github.com/mattermost/mattermost-server/v6/shared/mlog" -) +// "github.com/mattermost/mattermost-server/v6/model" +// "github.com/mattermost/mattermost-server/v6/shared/i18n" +// "github.com/mattermost/mattermost-server/v6/shared/mlog" +// ) -type webSocketHandler interface { - ServeWebSocket(*WebConn, *model.WebSocketRequest) -} +// type webSocketHandler interface { +// ServeWebSocket(*WebConn, *model.WebSocketRequest) +// } -type WebSocketRouter struct { - handlers map[string]webSocketHandler -} +// type WebSocketRouter struct { +// handlers map[string]webSocketHandler +// } -func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) { - wr.handlers[action] = handler -} +// func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) { +// wr.handlers[action] = handler +// } -func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { - if r.Action == "" { - err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) - returnWebSocketError(conn.App, conn, r, err) - return - } +// func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { +// if r.Action == "" { +// err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) +// returnWebSocketError(conn.App, conn, r, err) +// return +// } - if r.Seq <= 0 { - err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_seq.app_error", nil, "", http.StatusBadRequest) - returnWebSocketError(conn.App, conn, r, err) - return - } +// if r.Seq <= 0 { +// err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_seq.app_error", nil, "", http.StatusBadRequest) +// returnWebSocketError(conn.App, conn, r, err) +// return +// } - if r.Action == model.WebsocketAuthenticationChallenge { - if conn.GetSessionToken() != "" { - return - } +// if r.Action == model.WebsocketAuthenticationChallenge { +// if conn.GetSessionToken() != "" { +// return +// } - token, ok := r.Data["token"].(string) - if !ok { - conn.WebSocket.Close() - return - } +// token, ok := r.Data["token"].(string) +// if !ok { +// conn.WebSocket.Close() +// return +// } - session, err := conn.App.GetSession(token) - if err != nil { - conn.WebSocket.Close() - return - } - conn.SetSession(session) - conn.SetSessionToken(session.Token) - conn.UserId = session.UserId +// session, err := conn.App.GetSession(token) +// if err != nil { +// conn.WebSocket.Close() +// return +// } +// conn.SetSession(session) +// conn.SetSessionToken(session.Token) +// conn.UserId = session.UserId - conn.App.HubRegister(conn) +// conn.App.HubRegister(conn) - conn.App.Srv().Go(func() { - conn.App.SetStatusOnline(session.UserId, false) - conn.App.UpdateLastActivityAtIfNeeded(*session) - }) +// conn.App.Srv().Go(func() { +// conn.App.SetStatusOnline(session.UserId, false) +// conn.App.UpdateLastActivityAtIfNeeded(*session) +// }) - resp := model.NewWebSocketResponse(model.StatusOk, r.Seq, nil) - hub := conn.App.GetHubForUserId(conn.UserId) - if hub == nil { - return - } - hub.SendMessage(conn, resp) +// resp := model.NewWebSocketResponse(model.StatusOk, r.Seq, nil) +// hub := conn.App.GetHubForUserId(conn.UserId) +// if hub == nil { +// return +// } +// hub.SendMessage(conn, resp) - return - } +// return +// } - if !conn.IsAuthenticated() { - err := model.NewAppError("ServeWebSocket", "api.web_socket_router.not_authenticated.app_error", nil, "", http.StatusUnauthorized) - returnWebSocketError(conn.App, conn, r, err) - return - } +// if !conn.IsAuthenticated() { +// err := model.NewAppError("ServeWebSocket", "api.web_socket_router.not_authenticated.app_error", nil, "", http.StatusUnauthorized) +// returnWebSocketError(conn.App, conn, r, err) +// return +// } - handler, ok := wr.handlers[r.Action] - if !ok { - err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_action.app_error", nil, "", http.StatusInternalServerError) - returnWebSocketError(conn.App, conn, r, err) - return - } +// handler, ok := wr.handlers[r.Action] +// if !ok { +// err := model.NewAppError("ServeWebSocket", "api.web_socket_router.bad_action.app_error", nil, "", http.StatusInternalServerError) +// returnWebSocketError(conn.App, conn, r, err) +// return +// } - handler.ServeWebSocket(conn, r) -} +// handler.ServeWebSocket(conn, r) +// } -func returnWebSocketError(app *App, conn *WebConn, r *model.WebSocketRequest, err *model.AppError) { - logF := mlog.Error - if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { - logF = mlog.Debug - } - logF( - "websocket routing error.", - mlog.Int64("seq", r.Seq), - mlog.String("user_id", conn.UserId), - mlog.String("system_message", err.SystemMessage(i18n.T)), - mlog.Err(err), - ) +// func returnWebSocketError(app *App, conn *WebConn, r *model.WebSocketRequest, err *model.AppError) { +// logF := mlog.Error +// if err.StatusCode >= http.StatusBadRequest && err.StatusCode < http.StatusInternalServerError { +// logF = mlog.Debug +// } +// logF( +// "websocket routing error.", +// mlog.Int64("seq", r.Seq), +// mlog.String("user_id", conn.UserId), +// mlog.String("system_message", err.SystemMessage(i18n.T)), +// mlog.Err(err), +// ) - hub := app.GetHubForUserId(conn.UserId) - if hub == nil { - return - } +// hub := app.GetHubForUserId(conn.UserId) +// if hub == nil { +// return +// } - err.DetailedError = "" - errorResp := model.NewWebSocketError(r.Seq, err) - hub.SendMessage(conn, errorResp) -} +// err.DetailedError = "" +// errorResp := model.NewWebSocketError(r.Seq, err) +// hub.SendMessage(conn, errorResp) +// } diff --git a/cmd/mattermost/commands/cmdtestlib.go b/cmd/mattermost/commands/cmdtestlib.go index 34a572d6b1..12ec896c4d 100644 --- a/cmd/mattermost/commands/cmdtestlib.go +++ b/cmd/mattermost/commands/cmdtestlib.go @@ -70,8 +70,8 @@ func SetupWithStoreMock(t testing.TB) *testHelper { systemStore.On("Get").Return(make(model.StringMap), nil) licenseStore := mocks.LicenseStore{} licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil) - api4TestHelper.App.Srv().Store.(*mocks.Store).On("System").Return(&systemStore) - api4TestHelper.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore) + api4TestHelper.App.Srv().Store().(*mocks.Store).On("System").Return(&systemStore) + api4TestHelper.App.Srv().Store().(*mocks.Store).On("License").Return(&licenseStore) testHelper := &testHelper{ TestHelper: api4TestHelper, diff --git a/cmd/mattermost/commands/db.go b/cmd/mattermost/commands/db.go index dfe8c81b7b..db33032297 100644 --- a/cmd/mattermost/commands/db.go +++ b/cmd/mattermost/commands/db.go @@ -122,7 +122,7 @@ func resetCmdF(command *cobra.Command, args []string) error { } } - a.Srv().Store.DropAllTables() + a.Srv().Store().DropAllTables() CommandPrettyPrintln("Database successfully reset") auditRec := a.MakeAuditRecord("reset", audit.Success) diff --git a/cmd/mattermost/commands/import.go b/cmd/mattermost/commands/import.go index 634b490dda..b17256d4c2 100644 --- a/cmd/mattermost/commands/import.go +++ b/cmd/mattermost/commands/import.go @@ -174,11 +174,11 @@ func bulkImportCmdF(command *cobra.Command, args []string) error { func getTeamFromTeamArg(a *app.App, teamArg string) *model.Team { var team *model.Team - team, err := a.Srv().Store.Team().GetByName(teamArg) + team, err := a.Srv().Store().Team().GetByName(teamArg) if err != nil { var t *model.Team - if t, err = a.Srv().Store.Team().Get(teamArg); err == nil { + if t, err = a.Srv().Store().Team().Get(teamArg); err == nil { team = t } } diff --git a/cmd/mattermost/commands/init.go b/cmd/mattermost/commands/init.go index dfcb54b2ed..e93d9640fe 100644 --- a/cmd/mattermost/commands/init.go +++ b/cmd/mattermost/commands/init.go @@ -45,7 +45,6 @@ func initDBCommandContext(configDSN string, readOnlyConfigStore bool) (*app.App, // The option order is important as app.Config option reads app.StartMetrics option. app.StartMetrics, app.Config(configDSN, readOnlyConfigStore, nil), - app.StartSearchEngine, ) if err != nil { return nil, err diff --git a/cmd/mattermost/commands/server.go b/cmd/mattermost/commands/server.go index 20309b31be..252d3a57e7 100644 --- a/cmd/mattermost/commands/server.go +++ b/cmd/mattermost/commands/server.go @@ -70,7 +70,6 @@ func runServer(configStore *config.Store, interruptChan chan os.Signal) error { app.ConfigStore(configStore), app.RunEssentialJobs, app.JoinCluster, - app.StartSearchEngine, } server, err := app.NewServer(options...) if err != nil { diff --git a/manualtesting/manual_testing.go b/manualtesting/manual_testing.go index 5f5381fc99..c45a709dce 100644 --- a/manualtesting/manual_testing.go +++ b/manualtesting/manual_testing.go @@ -78,7 +78,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { Type: model.TeamOpen, } - createdTeam, err := c.App.Srv().Store.Team().Save(team) + createdTeam, err := c.App.Srv().Store().Team().Save(team) if err != nil { var invErr *store.ErrInvalidInput var appErr *model.AppError @@ -120,8 +120,8 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { return } - c.App.Srv().Store.User().VerifyEmail(user.Id, user.Email) - c.App.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam) + c.App.Srv().Store().User().VerifyEmail(user.Id, user.Email) + c.App.Srv().Store().Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, *c.App.Config().TeamSettings.MaxUsersPerTeam) userID = user.Id @@ -178,7 +178,7 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) { func getChannelID(a app.AppIface, channelname string, teamid string, userid string) (string, bool) { // Grab all the channels - channels, err := a.Srv().Store.Channel().GetChannels(teamid, userid, &model.ChannelSearchOpts{ + channels, err := a.Srv().Store().Channel().GetChannels(teamid, userid, &model.ChannelSearchOpts{ IncludeDeleted: false, LastDeleteAt: 0, }) diff --git a/store/sqlstore/store.go b/store/sqlstore/store.go index 58950dbb48..854e078b7f 100644 --- a/store/sqlstore/store.go +++ b/store/sqlstore/store.go @@ -440,6 +440,15 @@ func (ss *SqlStore) GetInternalReplicaDBs() []*sql.DB { return dbs } +func (ss *SqlStore) GetInternalReplicaDB() *sql.DB { + if len(ss.settings.DataSourceReplicas) == 0 || ss.lockedToMaster || !ss.hasLicense() { + return ss.GetMasterX().DB.DB + } + + rrNum := atomic.AddInt64(&ss.rrCounter, 1) % int64(len(ss.ReplicaXs)) + return ss.ReplicaXs[rrNum].DB.DB +} + func (ss *SqlStore) TotalMasterDbConnections() int { return ss.GetMasterX().Stats().OpenConnections } diff --git a/store/store.go b/store/store.go index 4984612a0b..b917adbede 100644 --- a/store/store.go +++ b/store/store.go @@ -73,6 +73,7 @@ type Store interface { GetInternalMasterDB() *sql.DB // GetInternalReplicaDBs allows access to the raw replica DB // handles for the multi-product architecture. + GetInternalReplicaDB() *sql.DB GetInternalReplicaDBs() []*sql.DB TotalMasterDbConnections() int TotalReadDbConnections() int @@ -974,7 +975,6 @@ type SharedChannelStore interface { // Paginate whether to paginate the results. // Page page requested, if results are paginated. // PerPage number of results per page, if paginated. -// type ChannelSearchOpts struct { Term string NotAssociatedToGroup string diff --git a/store/storetest/mocks/Store.go b/store/storetest/mocks/Store.go index d099b9f640..bd7c7e81c7 100644 --- a/store/storetest/mocks/Store.go +++ b/store/storetest/mocks/Store.go @@ -305,6 +305,22 @@ func (_m *Store) GetInternalMasterDB() *sql.DB { return r0 } +// GetInternalReplicaDB provides a mock function with given fields: +func (_m *Store) GetInternalReplicaDB() *sql.DB { + ret := _m.Called() + + var r0 *sql.DB + if rf, ok := ret.Get(0).(func() *sql.DB); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*sql.DB) + } + } + + return r0 +} + // GetInternalReplicaDBs provides a mock function with given fields: func (_m *Store) GetInternalReplicaDBs() []*sql.DB { ret := _m.Called() diff --git a/store/storetest/store.go b/store/storetest/store.go index 331e0aeb2b..7979f8dac5 100644 --- a/store/storetest/store.go +++ b/store/storetest/store.go @@ -107,6 +107,7 @@ func (s *Store) UnlockFromMaster() { /* do nothing */ } func (s *Store) DropAllTables() { /* do nothing */ } func (s *Store) GetDbVersion(bool) (string, error) { return "", nil } func (s *Store) GetInternalMasterDB() *sql.DB { return nil } +func (s *Store) GetInternalReplicaDB() *sql.DB { return nil } func (s *Store) GetInternalReplicaDBs() []*sql.DB { return nil } func (s *Store) RecycleDBConnections(time.Duration) {} func (s *Store) GetDBSchemaVersion() (int, error) { return 1, nil } diff --git a/web/context.go b/web/context.go index 701f00dd97..d877f1a39f 100644 --- a/web/context.go +++ b/web/context.go @@ -81,7 +81,7 @@ func (c *Context) MakeAuditRecord(event string, initialStatus string) *audit.Rec func (c *Context) LogAudit(extraInfo string) { audit := &model.Audit{UserId: c.AppContext.Session().UserId, IpAddress: c.AppContext.IPAddress(), Action: c.AppContext.Path(), ExtraInfo: extraInfo, SessionId: c.AppContext.Session().Id} - if err := c.App.Srv().Store.Audit().Save(audit); err != nil { + if err := c.App.Srv().Store().Audit().Save(audit); err != nil { appErr := model.NewAppError("LogAudit", "app.audit.save.saving.app_error", nil, "", http.StatusInternalServerError).Wrap(err) c.LogErrorByCode(appErr) } @@ -93,7 +93,7 @@ func (c *Context) LogAuditWithUserId(userId, extraInfo string) { } audit := &model.Audit{UserId: userId, IpAddress: c.AppContext.IPAddress(), Action: c.AppContext.Path(), ExtraInfo: extraInfo, SessionId: c.AppContext.Session().Id} - if err := c.App.Srv().Store.Audit().Save(audit); err != nil { + if err := c.App.Srv().Store().Audit().Save(audit); err != nil { appErr := model.NewAppError("LogAuditWithUserId", "app.audit.save.saving.app_error", nil, "", http.StatusInternalServerError).Wrap(err) c.LogErrorByCode(appErr) } diff --git a/web/context_test.go b/web/context_test.go index 6a78d27fca..3cdb22397c 100644 --- a/web/context_test.go +++ b/web/context_test.go @@ -54,7 +54,7 @@ func TestMfaRequired(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockUserStore.On("Get", context.Background(), "userid").Return(nil, model.NewAppError("Userstore.Get", "storeerror", nil, "store error", http.StatusInternalServerError)) diff --git a/web/handlers.go b/web/handlers.go index f0faa7abe3..9792460aff 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -202,7 +202,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.AppContext.SetContext(ctx) tmpSrv := *c.App.Srv() - tmpSrv.Store = opentracinglayer.New(c.App.Srv().Store, ctx) + tmpSrv.SetStore(opentracinglayer.New(c.App.Srv().Store(), ctx)) c.App.SetServer(&tmpSrv) c.App = app_opentracing.NewOpenTracingAppLayer(c.App, ctx) } @@ -325,7 +325,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.MfaRequired() } - if c.Err == nil && h.DisableWhenBusy && c.App.Srv().Busy.IsBusy() { + if c.Err == nil && h.DisableWhenBusy && c.App.Srv().Platform().Busy.IsBusy() { c.SetServerBusyError() } diff --git a/web/handlers_test.go b/web/handlers_test.go index 906a464b39..e04be652da 100644 --- a/web/handlers_test.go +++ b/web/handlers_test.go @@ -66,7 +66,7 @@ func TestHandlerServeHTTPSecureTransport(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -309,7 +309,7 @@ func TestHandlerServeCSPHeader(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} @@ -630,7 +630,7 @@ func TestCheckCSRFToken(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() - mockStore := th.App.Srv().Store.(*mocks.Store) + mockStore := th.App.Srv().Store().(*mocks.Store) mockUserStore := mocks.UserStore{} mockUserStore.On("Count", mock.Anything).Return(int64(10), nil) mockPostStore := mocks.PostStore{} diff --git a/web/oauth_test.go b/web/oauth_test.go index 1f8c610cc5..6531290300 100644 --- a/web/oauth_test.go +++ b/web/oauth_test.go @@ -346,7 +346,7 @@ func TestOAuthAccessToken(t *testing.T) { require.NoError(t, err) authData := &model.AuthData{ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], UserId: th.BasicUser.Id, Code: model.NewId(), ExpiresIn: -1} - _, err = th.App.Srv().Store.OAuth().SaveAuthData(authData) + _, err = th.App.Srv().Store().OAuth().SaveAuthData(authData) require.NoError(t, err) data.Set("grant_type", model.AccessTokenGrantType) @@ -528,7 +528,7 @@ func TestOAuthComplete(t *testing.T) { closeBody(r) } - _, nErr := th.App.Srv().Store.User().UpdateAuthData( + _, nErr := th.App.Srv().Store().User().UpdateAuthData( th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true) require.NoError(t, nErr) diff --git a/web/web_test.go b/web/web_test.go index d68abdf754..139753675d 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -56,7 +56,7 @@ func SetupWithStoreMock(tb testing.TB) *TestHelper { th := setupTestHelper(tb, false) emptyMockStore := mocks.Store{} emptyMockStore.On("Close").Return(nil) - th.App.Srv().Store = &emptyMockStore + th.App.Srv().SetStore(&emptyMockStore) return th } @@ -95,10 +95,12 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool) *TestHelper { } if includeCacheLayer { // Adds the cache layer to the test store - s.Store, err = localcachelayer.NewLocalCacheLayer(s.Store, s.GetMetrics(), s.Cluster, s.CacheProvider) + var st localcachelayer.LocalCacheStore + st, err = localcachelayer.NewLocalCacheLayer(s.Store(), s.GetMetrics(), s.Platform().Cluster(), s.Platform().CacheProvider()) if err != nil { panic(err) } + s.SetStore(st) } a := app.New(app.ServerConnector(s.Channels())) @@ -123,7 +125,7 @@ func setupTestHelper(tb testing.TB, includeCacheLayer bool) *TestHelper { URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port) apiClient = model.NewAPIv4Client(URL) - s.Store.MarkSystemRanUnitTests() + s.Store().MarkSystemRanUnitTests() a.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true diff --git a/wsapi/api.go b/wsapi/api.go index 98efd84845..9dd70757c8 100644 --- a/wsapi/api.go +++ b/wsapi/api.go @@ -5,18 +5,20 @@ package wsapi import ( "github.com/mattermost/mattermost-server/v6/app" + "github.com/mattermost/mattermost-server/v6/app/platform" ) type API struct { App *app.App - Router *app.WebSocketRouter + Router *platform.WebSocketRouter } func Init(s *app.Server) { a := app.New(app.ServerConnector(s.Channels())) + router := s.Platform().WebSocketRouter api := &API{ App: a, - Router: s.WebSocketRouter, + Router: router, } api.InitUser() diff --git a/wsapi/status.go b/wsapi/status.go index a6898ee9af..8bea2d5b64 100644 --- a/wsapi/status.go +++ b/wsapi/status.go @@ -14,7 +14,7 @@ func (api *API) InitStatus() { } func (api *API) getStatuses(req *model.WebSocketRequest) (map[string]any, *model.AppError) { - statusMap := api.App.GetAllStatuses() + statusMap := api.App.Srv().Platform().GetAllStatuses() return model.StatusMapToInterfaceMap(statusMap), nil } @@ -25,7 +25,7 @@ func (api *API) getStatusesByIds(req *model.WebSocketRequest) (map[string]any, * return nil, NewInvalidWebSocketParamError(req.Action, "user_ids") } - statusMap, err := api.App.GetStatusesByIds(userIds) + statusMap, err := api.App.Srv().Platform().GetStatusesByIds(userIds) if err != nil { return nil, err } diff --git a/wsapi/user.go b/wsapi/user.go index 9cbcdbe78e..6f814fb66d 100644 --- a/wsapi/user.go +++ b/wsapi/user.go @@ -16,7 +16,7 @@ func (api *API) InitUser() { func (api *API) userTyping(req *model.WebSocketRequest) (map[string]any, *model.AppError) { api.App.ExtendSessionExpiryIfNeeded(&req.Session) - if api.App.Srv().Busy.IsBusy() { + if api.App.Srv().Platform().Busy.IsBusy() { // this is considered a non-critical service and will be disabled when server busy. return nil, NewServerBusyWebSocketError(req.Action) } diff --git a/wsapi/websocket_handler.go b/wsapi/websocket_handler.go index 53bd397955..51ffbfcf33 100644 --- a/wsapi/websocket_handler.go +++ b/wsapi/websocket_handler.go @@ -7,6 +7,7 @@ import ( "net/http" "github.com/mattermost/mattermost-server/v6/app" + "github.com/mattermost/mattermost-server/v6/app/platform" "github.com/mattermost/mattermost-server/v6/model" "github.com/mattermost/mattermost-server/v6/shared/i18n" "github.com/mattermost/mattermost-server/v6/shared/mlog" @@ -21,10 +22,10 @@ type webSocketHandler struct { handlerFunc func(*model.WebSocketRequest) (map[string]any, *model.AppError) } -func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketRequest) { +func (wh webSocketHandler) ServeWebSocket(conn *platform.WebConn, r *model.WebSocketRequest) { mlog.Debug("Websocket request", mlog.String("action", r.Action)) - hub := wh.app.GetHubForUserId(conn.UserId) + hub := wh.app.Srv().Platform().GetHubForUserId(conn.UserId) if hub == nil { return }